Skip to content

armgit / cua

Public Imported from GitHub
0

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

feat(cua-driver): add implicit lifecycle sessions (#3013)

Francesco Bonacci858ef13a5b1f
diff --git a/.github/scripts/cua-driver-mcp-compat/expected-tools.json b/.github/scripts/cua-driver-mcp-compat/expected-tools.json
index 85fe3b445f..363114c362 100644
--- a/.github/scripts/cua-driver-mcp-compat/expected-tools.json
+++ b/.github/scripts/cua-driver-mcp-compat/expected-tools.json
@@ -1,9 +1,9 @@
{
"serverName": "cua-driver",
"outputSchemaCountByPlatform": {
- "darwin": 30,
- "linux": 34,
- "win32": 30
+ "darwin": 32,
+ "linux": 36,
+ "win32": 32
},
"baseTools": [
"bring_to_front",
@@ -32,6 +32,7 @@
"get_desktop_state",
"get_recording_state",
"get_screen_size",
+ "get_session",
"get_session_state",
"get_window_state",
"health_report",
@@ -41,6 +42,7 @@
"kill_app",
"launch_app",
"list_apps",
+ "list_sessions",
"list_windows",
"move_cursor",
"page",
diff --git a/.github/scripts/tests/test_cua_driver_release_wiring.py b/.github/scripts/tests/test_cua_driver_release_wiring.py
index 04b9b04bcc..10216eb596 100644
--- a/.github/scripts/tests/test_cua_driver_release_wiring.py
+++ b/.github/scripts/tests/test_cua_driver_release_wiring.py
@@ -621,10 +621,10 @@ class TestCuaDriverReleaseWiring(unittest.TestCase):
self.assertEqual(
len(expected["baseTools"]), len(set(expected["baseTools"]))
)
- self.assertEqual(len(expected["baseTools"]), 54)
+ self.assertEqual(len(expected["baseTools"]), 56)
self.assertEqual(
expected["outputSchemaCountByPlatform"],
- {"darwin": 30, "linux": 34, "win32": 30},
+ {"darwin": 32, "linux": 36, "win32": 32},
)
self.assertEqual(
expected["platformTools"],
diff --git a/.github/workflows/e2e-rust-linux-wayland.yml b/.github/workflows/e2e-rust-linux-wayland.yml
index da15038b2e..a80f78accc 100644
--- a/.github/workflows/e2e-rust-linux-wayland.yml
+++ b/.github/workflows/e2e-rust-linux-wayland.yml
@@ -87,7 +87,7 @@ jobs:
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
sway wf-recorder grim wtype dbus dbus-x11 at-spi2-core libglib2.0-bin \
- python3-gi gir1.2-gtk-3.0 libgtk-3-dev clang pkg-config \
+ python3-gi gir1.2-gtk-3.0 gir1.2-gtk-4.0 libgtk-3-dev clang pkg-config \
libdbus-1-dev libpipewire-0.3-dev libspa-0.2-dev libei-dev \
libwayland-dev libxkbcommon-dev libx11-dev libxi-dev libxtst-dev \
libxext-dev libdrm-dev libgbm-dev libwebkit2gtk-4.1-dev \
diff --git a/docs/content/docs/concepts/capture-and-delivery-modalities.mdx b/docs/content/docs/concepts/capture-and-delivery-modalities.mdx
index d51a89f307..27614f6cf8 100644
--- a/docs/content/docs/concepts/capture-and-delivery-modalities.mdx
+++ b/docs/content/docs/concepts/capture-and-delivery-modalities.mdx
@@ -1,6 +1,6 @@
---
title: "Capture and Delivery Modalities"
-description: "How Cua Driver observes and acts on an app. Perception returns both the accessibility tree and a screenshot; the action call chooses the ax or px rung, delivery mode, and scope."
+description: "How Cua Driver observes and acts on an app. Perception returns both the accessibility tree and a screenshot; each action chooses its target, ax or px rung, and delivery mode."
---
Every Cua Driver action is shaped by four things: **what the agent observes**, **which rung delivers the action**, **how input is delivered**, and **what coordinate space the action targets**. Most callers use the defaults: background, per-window, accessibility-first automation. The key change from earlier versions is that perception is no longer a mode you pick. `get_window_state` returns *both* the accessibility tree and a screenshot in one call. The action call chooses `ax` or `px` by how it addresses the target.
@@ -43,16 +43,18 @@ Only `background` and `foreground` are valid; the historical `auto` heuristic is
`bring_to_front` is not a normal escalation step. Reserve it for focus-proxy surfaces that must stay foreground across multiple calls, such as a remote desktop session. For an ordinary `background_unavailable` response, retry only the refused action with `delivery_mode:"foreground"`.
-### 4. Capture scope: what coordinate space the action targets
+### 4. Action target: what coordinate space the action uses
-Set with `set_config capture_scope=…`.
+Select the target on each action:
-| `capture_scope` | Coordinate space | Capture surface |
+| `target` | Coordinate space | Capture surface |
|---|---|---|
-| `window` (default) | Per-window. Actions carry `pid` + `window_id`; coordinates are window-relative or addressed by `element_index`. | `get_window_state` |
-| `desktop` | Screen-absolute. Window-less actions (no `pid`/`window_id`) land at absolute screen coordinates via hit-testing (`WindowFromPoint`). | `get_desktop_state` with full display, no downscale |
+| `{kind:"window", pid, window_id}` | coordinates relative to the exact window, or an element from that window's snapshot | `get_window_state` |
+| `{kind:"desktop", display_id:"primary"}` | screen coordinates on the primary display | `get_desktop_state` |
-Desktop scope is the "Computer-Use 1.0" loop: the agent reads the whole screen and clicks absolute coordinates, the way a screenshot-only model expects. Window scope is the default because it is what makes background, concurrent automation possible.
+The per-call target keeps window and desktop work independent. A desktop action
+does not change session state or disable window tools for the next call.
+Legacy `capture_scope` configuration remains available during migration.
## Response signals: verification, effect, and escalation
@@ -70,6 +72,6 @@ The driver treats those as surface-aware verification cases. It probes at the el
## Where the exact matrix lives
-Perception is no longer an axis: every `get_window_state` returns both the tree and a screenshot by default. The enforceable constraints are the combination of **capture scope**, **action rung**, and **delivery mode**.
+Perception is no longer an axis: every `get_window_state` returns both the tree and a screenshot by default. The enforceable constraints are the combination of **action target**, **action rung**, and **delivery mode**.
The exact validity matrix and platform-support table live in [Interface contracts](/reference/cua-driver/contracts). Keep this page as the mental model: observe both tree and pixels, start with the accessibility rung, use the screenshot-backed pixel rung when the tree is insufficient, and escalate to foreground only when the target app requires it.
diff --git a/docs/content/docs/concepts/sdk-mcp-and-hosting.mdx b/docs/content/docs/concepts/sdk-mcp-and-hosting.mdx
index 79cbb83574..04b80dba37 100644
--- a/docs/content/docs/concepts/sdk-mcp-and-hosting.mdx
+++ b/docs/content/docs/concepts/sdk-mcp-and-hosting.mdx
@@ -134,7 +134,7 @@ virtualization:
| Runtime ceiling, effective session contexts, revocation | Runtime-owned | Isolated within each opaque runtime generation |
| Tool registry, browser engine and grants, recording session | Runtime-owned | Released only by their owning session/runtime |
| Permission/policy compatibility caches and bounded compatibility manifest | Immutable process configuration | Explicit configured constructors must agree with contradictory environment values or fail |
-| Session activity, capture scopes, element tokens, browser refs, cursor keys | Runtime-namespaced | The same public session label in two runtimes remains independent; stale or cross-runtime handles fail closed |
+| Session activity, modality telemetry, element tokens, browser refs, cursor keys | Runtime-namespaced | The same public session label in two runtimes remains independent; stale or cross-runtime handles fail closed |
| Physical pointer, keyboard, focus, overlay, and platform event loops | Process/platform coordinated | Native input and focus action turns are admitted one at a time; all runtimes still operate the same physical desktop |
| CDP listener claims and the download gate | Process-coordinated | A listener/profile claim or download lease cannot be silently taken over by another runtime |
| Recording platform callbacks, video/PiP factories, policy, observers, ABI executor | Immutable process callbacks/coordinator | Shared only where the process identity and platform configuration are the same |
@@ -144,11 +144,11 @@ recording. Public session labels and element-token wire formats remain
unchanged; the runtime generation is private and never accepted from a tool
argument.
-The reserved anonymous `default` cursor/session fallback is process-shared and
-does not provide lifecycle isolation. Give each concurrent host operation an
-explicit session (or cursor ID). The first enabled runtime initializes the
-process-global overlay template; later runtimes reuse it and can customize
-their own namespaced cursors through the cursor tools.
+Each runtime transport receives a private implicit lifecycle session. Repeated
+unnamed actions on that transport reuse it, while concurrent transports remain
+isolated. An explicit public label is optional. The first enabled runtime
+initializes the process-global overlay template; later runtimes reuse it and
+can customize their own namespaced cursors through the cursor tools.
Arbitrary code in the host process can inspect or interfere with every
runtime. Use separate private workers or services for crash isolation,
diff --git a/docs/content/docs/how-to-guides/driver/run-in-macos-lume-vm.mdx b/docs/content/docs/how-to-guides/driver/run-in-macos-lume-vm.mdx
index f5b1825688..ab967a541f 100644
--- a/docs/content/docs/how-to-guides/driver/run-in-macos-lume-vm.mdx
+++ b/docs/content/docs/how-to-guides/driver/run-in-macos-lume-vm.mdx
@@ -102,10 +102,8 @@ without the system picker. Trigger that request with an actual desktop capture:
```bash
DRIVER=/Users/lume/.local/bin/cua-driver
-"$DRIVER" call set_config '{"capture_scope":"desktop"}'
"$DRIVER" call get_desktop_state '{}' \
> /tmp/cua-driver-desktop-state.json
-"$DRIVER" call set_config '{"capture_scope":"window"}'
```
Choose **Allow** on the direct-capture prompt. Check that the command returned
@@ -169,10 +167,8 @@ assert status['screen_recording_capturable'] is True
assert status['direct_capture_status'] == 'ready'
PY
/Users/lume/.local/bin/cua-driver call get_accessibility_tree '{}'
-/Users/lume/.local/bin/cua-driver call set_config '{"capture_scope":"desktop"}'
/Users/lume/.local/bin/cua-driver call get_desktop_state '{}' \
> /tmp/cua-driver-desktop-state-second.json
-/Users/lume/.local/bin/cua-driver call set_config '{"capture_scope":"window"}'
```
The commands must succeed without opening System Settings or another consent
diff --git a/docs/content/docs/how-to-guides/driver/run-tests-in-macos-lume-vm.mdx b/docs/content/docs/how-to-guides/driver/run-tests-in-macos-lume-vm.mdx
index 5cbe4a6052..8f9e6498b6 100644
--- a/docs/content/docs/how-to-guides/driver/run-tests-in-macos-lume-vm.mdx
+++ b/docs/content/docs/how-to-guides/driver/run-tests-in-macos-lume-vm.mdx
@@ -198,10 +198,8 @@ osascript -e \
# An actual desktop capture triggers Tahoe's separate direct-capture prompt.
DRIVER=/Users/lume/.local/bin/cua-driver
-"$DRIVER" call set_config '{"capture_scope":"desktop"}'
"$DRIVER" call get_desktop_state '{}' \
> /tmp/cua-driver-seed-desktop-state.json
-"$DRIVER" call set_config '{"capture_scope":"window"}'
```
Choose **Allow** for:
diff --git a/docs/content/docs/how-to-guides/driver/use-codex-sdk.mdx b/docs/content/docs/how-to-guides/driver/use-codex-sdk.mdx
index 3e6cbec4f5..2f910cac73 100644
--- a/docs/content/docs/how-to-guides/driver/use-codex-sdk.mdx
+++ b/docs/content/docs/how-to-guides/driver/use-codex-sdk.mdx
@@ -74,5 +74,6 @@ Both scripts:
5. end the session in `finally`.
The filesystem sandbox does not sandbox the separate desktop MCP server.
-Restrict the task itself, choose an appropriate Cua capture scope and policy,
-and never blindly retry a mutation after a timeout or disconnect.
+Restrict the task itself, choose an exact window or desktop target for each Cua
+action, apply the appropriate authorization policy, and never blindly retry a
+mutation after a timeout or disconnect.
diff --git a/docs/content/docs/how-to-guides/driver/use-sdk-in-process.mdx b/docs/content/docs/how-to-guides/driver/use-sdk-in-process.mdx
index f4d95fae63..678136226f 100644
--- a/docs/content/docs/how-to-guides/driver/use-sdk-in-process.mdx
+++ b/docs/content/docs/how-to-guides/driver/use-sdk-in-process.mdx
@@ -35,14 +35,11 @@ npm install @trycua/cua-driver
</Tab>
</Tabs>
-## Start a session and capture the desktop
+## Capture the desktop with an implicit session
-Choose the capture scope when the session starts:
-
-- `AUTO` begins with the window-focused action ladder and permits an explicit
- escalation to desktop tools when narrower options are exhausted.
-- `WINDOW` is strict window-only mode.
-- `DESKTOP` is strict whole-desktop mode.
+The first stateful call creates one implicit session for the SDK transport.
+`start_session` is optional and no capture scope is stored on the session.
+Actions select an exact window or desktop target per call.
<Tabs groupId="language" persist items={['Python', 'TypeScript']}>
<Tab value="Python">
@@ -51,27 +48,18 @@ Choose the capture scope when the session starts:
import asyncio
from cua_driver import (
- CaptureScope,
CuaDriver,
EndSessionInput,
GetDesktopStateInput,
- StartSessionInput,
)
async def main() -> None:
driver = CuaDriver.create()
- session = "desktop-capture"
- await driver.start_session(
- StartSessionInput(
- session=session,
- capture_scope=CaptureScope.DESKTOP,
- )
- )
try:
result = await driver.get_desktop_state(
GetDesktopStateInput(
- session=session,
+ session=None,
screenshot_out_file=None,
)
)
@@ -79,7 +67,7 @@ async def main() -> None:
raise RuntimeError(result.text)
print(result.images[0].mime_type)
finally:
- await driver.end_session(EndSessionInput(session=session))
+ await driver.end_session(EndSessionInput(session=None))
await driver.shutdown()
@@ -91,29 +79,19 @@ asyncio.run(main())
```ts
import {
- CaptureScope,
CuaDriver,
EndSessionInput,
GetDesktopStateInput,
- StartSessionInput,
} from '@trycua/cua-driver';
const driver = CuaDriver.create(undefined);
-const session = 'desktop-capture';
-
-await driver.startSession(
- StartSessionInput.new({
- session,
- captureScope: CaptureScope.Desktop,
- })
-);
try {
- const result = await driver.getDesktopState(GetDesktopStateInput.new({ session }));
+ const result = await driver.getDesktopState(GetDesktopStateInput.new({}));
if (result.isError) throw new Error(result.text);
console.log(result.images[0]?.mimeType);
} finally {
- await driver.endSession(EndSessionInput.new({ session }));
+ await driver.endSession(EndSessionInput.new({}));
await driver.shutdown();
driver.uniffiDestroy();
}
@@ -122,9 +100,10 @@ try {
</Tab>
</Tabs>
-Keep one `CuaDriver` object for the application lifetime. End every session you
-start. `shutdown()` is idempotent and rejects new work after shutdown while
-allowing already-admitted operations to finish.
+Keep one `CuaDriver` object for the application lifetime. Repeated unnamed calls
+reuse its implicit session. End it explicitly when useful; `shutdown()` also
+runs cleanup. `shutdown()` is idempotent and rejects new work after shutdown
+while allowing already-admitted operations to finish.
If an external agent must also connect to your signed desktop application, use
[Expose MCP from a desktop app](/how-to-guides/driver/expose-mcp-from-desktop-app)
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
index c9de21477b..e4c3f266af 100644
--- 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
@@ -145,7 +145,7 @@ naming only the non-browser applications it needs, and keep
`desktop.display: false`. A standard-mode runtime is not a substitute: standard
allows input against any application, including the browser.
-## 3. Choose desktop scope
+## 3. Authorize display access
Application entries with `windows: all` authorize observation and input for
windows belonging to that application.
diff --git a/docs/content/docs/reference/cua-driver/action-selection-policy.mdx b/docs/content/docs/reference/cua-driver/action-selection-policy.mdx
index ed3fd47721..6cb473c216 100644
--- a/docs/content/docs/reference/cua-driver/action-selection-policy.mdx
+++ b/docs/content/docs/reference/cua-driver/action-selection-policy.mdx
@@ -5,7 +5,10 @@ description: "Behavior an agent should follow when choosing element, pixel, page
This policy describes how an agent should choose Cua Driver action parameters. It is meant for agent prompts, wrappers, and evaluators. It is not a user walkthrough.
-Use it when the agent must decide what to pass to `click`, `type_text`, `get_window_state`, and related tools: `element_index` versus `x, y`, `delivery_mode: background` versus `foreground`, and window versus desktop scope.
+Use it when the agent must decide what to pass to `click`, `type_text`,
+`get_window_state`, and related tools: `element_index` versus `x, y`,
+`delivery_mode: background` versus `foreground`, and a window versus desktop
+target.
## Preconditions
@@ -92,17 +95,23 @@ click({ pid, window_id, element_index: 12 })
**Wayland exception.** On a native Wayland session, raw keyboard input has no universal background path. When an AX keyboard action no-ops there, prefer an accessible field action or run the app under XWayland; otherwise escalate only that action to foreground. See [Known limits](/reference/cua-driver/limits#native-wayland-apps-cant-receive-synthetic-keystrokes).
-## Switch to desktop scope only for screen-absolute work
+## Use a desktop target only for screen-absolute work
-Reach for **desktop scope** only when the action has no single window, such as dragging between windows or clicking absolute screen coordinates. It foregrounds and works on pixels, so it cannot provide best-effort background behavior.
+Use a **desktop target** only when the action has no single window, such as
+dragging between windows or clicking absolute screen coordinates. It uses
+foreground pixel input, so it cannot provide best-effort background behavior.
```jsonc
-set_config({ capture_scope: "desktop" })
-get_desktop_state() // full-screen screenshot
-click({ x: 1280, y: 40 }) // screen-absolute, no window_id
+get_desktop_state() // full-screen screenshot
+click({
+ x: 1280,
+ y: 40,
+ target: { kind: "desktop", display_id: "primary" },
+})
```
-A window-less click while scope is still `window` is rejected with `desktop_scope_disabled`. That error is the prompt to switch scope.
+Choose the target on each action. This does not change the session or disable
+window-targeted tools for later calls.
## Confirm the action landed
@@ -119,7 +128,9 @@ get_window_state({ pid, window_id }) // confirm the change against tree
Do not trust the status code on a `verified: false` action. Re-read the window. The snapshot carries both the tree and the screenshot. Confirm the effect; if it did not land, switch rung (element ax action -> element px action off the same screenshot) or escalate delivery (background -> foreground).
**Problem: `desktop_scope_disabled` on a window-less click.**
-The agent is in `window` scope. Either pass a `window_id` (+ `element_index` or `x, y`), or `set_config({ capture_scope: "desktop" })` for genuinely screen-absolute work.
+This is a legacy flat call without an admitted desktop scope. Retry with an
+exact window target, or use
+`target: {kind: "desktop", display_id: "primary"}` for screen-absolute work.
**Problem: keystrokes don't land on a Linux app.**
On native Wayland, raw keys have no background path. Type into accessible fields with `type_text`, drive controls by `element_index`, or run the app under XWayland. See [Known limits](/reference/cua-driver/limits#native-wayland-apps-cant-receive-synthetic-keystrokes).
diff --git a/docs/content/docs/reference/cua-driver/contracts.mdx b/docs/content/docs/reference/cua-driver/contracts.mdx
index bf11d01219..653b7dc67f 100644
--- a/docs/content/docs/reference/cua-driver/contracts.mdx
+++ b/docs/content/docs/reference/cua-driver/contracts.mdx
@@ -1,6 +1,6 @@
---
title: Interface Contracts
-description: "The contracts behind the CLI and MCP surfaces: transport state, config persistence, capture scope, and action routing."
+description: "The contracts behind the CLI and MCP surfaces: lifecycle sessions, per-call targets, config persistence, and action routing."
---
import { Callout } from 'fumadocs-ui/components/callout';
@@ -16,11 +16,11 @@ MCP may own that runtime directly or select `cua-driver serve` explicitly.
| Dimension | CLI (`call`) | MCP (`mcp`) |
|---|---|---|
-| Lifetime | one client process per action; the selected service owns durable state | one process, many actions |
+| Lifetime | each one-shot call gets a disposable implicit session; the selected service may own other durable state | one implicit session per authenticated transport connection |
| `element_index` cache | owned by the selected service; survives until invalidation or service restart | owned by the MCP runtime; lives across calls |
-| Identity | anonymous unless the call declares a public `session` | a minted transport session per connection, plus an optional public `session` |
-| Where `set_config` lands | the persisted global default on disk | an in-memory, session-scoped override |
-| Agent cursor | none | shown when a `session` is declared |
+| Public label | optional `session`; it does not carry authority | optional `session`; it does not carry authority |
+| Where `set_config` lands | the persisted global default when no public session is supplied | an in-memory override when a public session is supplied |
+| Agent cursor | initialized for the call and cleaned up with its disposable session | initialized on the first cursor-bearing action and reused on later unnamed calls |
<Callout type="warn">
`cua-driver call` requires a service at the resolved default endpoint or at the
@@ -34,6 +34,25 @@ macOS. `mcp --socket <endpoint>` explicitly selects a service on every
platform; `mcp --direct` explicitly selects process ownership and is mutually
exclusive with `--socket`.
+## Lifecycle sessions
+
+`start_session` is optional. The first admitted stateful call creates one
+implicit session for the authenticated transport lease. Later unnamed calls on
+that transport reuse the same identity, so several clicks do not create several
+sessions. The runtime does not expose its private implicit ID.
+
+The default session idle TTL is five minutes. This timer controls lifecycle and
+resource cleanup. It is separate from the cursor idle-hide timer, which controls
+visibility only. A call in flight cannot expire, and a completed call refreshes
+the lifecycle timer once. Transport close, explicit end, revocation, and idle
+expiry use the same cleanup hooks.
+
+Use `start_session` for an optional public name or initial cursor theme.
+`get_session` reads one visible session, and `list_sessions` returns content-free
+summaries scoped to the caller's transport. Trusted host code has a separate
+operator listing. `get_session_state` and `escalate_session` remain deprecated
+for legacy capture-scope sessions. There is no `deescalate_session`.
+
---
## Where settings live
@@ -53,71 +72,81 @@ Every tool then reads the **effective** value with this precedence:
effective = call-argument > session override > global default (disk)
```
-Keys that flow through this: `capture_scope`, `max_image_dimension`. `capture_mode` is deprecated and ignored. It is still accepted for back-compat but has no effect; `get_window_state` always returns both the tree and a screenshot. See the [`set_config` reference](/reference/cua-driver/mcp-tools) for the per-session isolation details.
+`max_image_dimension` follows this precedence. The retired `capture_scope`
+configuration key returns a migration error that points callers to the
+per-action `target`; only the deprecated `start_session.capture_scope` field
+remains for legacy session calls. `capture_mode` is deprecated and ignored.
+`get_window_state` always returns both the tree and a screenshot. See the
+[`set_config` reference](/reference/cua-driver/mcp-tools) for the per-session
+isolation details.
---
-## The capture-scope contract
+## The per-call target contract
-`capture_scope` decides **which parameters a call must carry** and **what coordinate space it speaks**.
+Capture modality belongs to each observation or action. A session records the
+modalities used, but it does not lock the caller into a window or desktop mode.
+The input tools `move_cursor`, `click`, `drag`, `scroll`, `type_text`,
+`press_key`, and `hotkey` accept one exact tagged target:
+
+```jsonc
+{ "target": { "kind": "window", "pid": 4711, "window_id": 22 } }
+{ "target": { "kind": "desktop", "display_id": "primary" } }
```
- capture_scope = "window" (default) capture_scope = "desktop"
- ─────────────────────────────────── ──────────────────────────────────
- per window, background-capable whole screen, foreground, vision
-
- observe: get_window_state(pid, window_id) observe: get_desktop_state()
- act: click(pid, …) act: click(x, y)
- element_index + window_id (AX) true screen pixels
- or x, y + pid (window-local px) no pid, no window_id
- needs: pid (+ window_id for elements) skips: window_id, list_windows
-```
-| | `window` (default) | `desktop` |
+`display_id:"primary"` is the portable desktop target in this release. An
+unsupported display ID returns `invalid_action_target`. The target cannot be
+combined with legacy `scope`, `pid`, or `window_id` fields, so the driver never
+has to guess which coordinate space the caller intended.
+
+| | Window target | Desktop target |
|---|---|---|
-| Coordinate space | window-local (the PNG `get_window_state` returns) | true screen pixels |
-| Required params | `pid` (+ `window_id` for `element_index`) | only `x`, `y` |
-| Capture surface | `get_window_state` (tree + screenshot) | `get_desktop_state` (screenshot) |
-| Delivery | background (default) or foreground | foreground only |
-| Action rung | element ax action (`element_index`) or element px action (`x,y`) | element px action (`x,y`) only |
+| Coordinate space | window-local coordinates from `get_window_state` | screen coordinates from `get_desktop_state` |
+| Identity | exact `pid` and `window_id` | exact `display_id`, currently `primary` |
+| Delivery | background by default, or foreground per call | foreground |
+| Action rung | accessibility element or window-local pixel | screen pixel |
-Desktop scope is the screen-absolute "Computer-Use 1.0" loop: read the whole screen, click an absolute coordinate, the way a screenshot-only model expects. Window scope is the default because it is what makes background, concurrent automation possible.
+Legacy callers may keep using flat `pid`, `window_id`, and `scope` fields during
+the compatibility window. An explicit legacy `capture_scope` still invokes the
+old session gate. New callers should use `target` and should not call
+`escalate_session`.
---
## How an action is routed
-Every input tool (`click`, `scroll`, and the keyboard family: `type_text`, `press_key`, `hotkey`) picks its path from the arguments present:
+Every input tool chooses its route from the target and action arguments:
| Arguments | Path | Behavior |
|---|---|---|
-| `element_index` + `window_id` | accessibility action | UIA Invoke / `AXPerformAction` / AT-SPI. Background, no cursor move, no focus steal. |
-| `x`, `y` + `pid` | window-local pixel | coordinates are relative to that window's screenshot. For the **keyboard family** this px form pixel-clicks `(x, y)` to establish real renderer focus, then delivers the keystroke(s) to the now-focused element. Use it for Chromium/Electron inputs the AX layer cannot focus. |
-| `x`, `y`, **no** `pid`/`window_id`, scope `desktop` | screen-absolute | true screen pixels, lands on whatever is frontmost there |
-| `x`, `y`, **no** `pid`/`window_id`, scope `window` | rejected | structured `desktop_scope_disabled` error |
-
-The keyboard family's `x, y` (px) form is mutually exclusive with `element_index` (ax). Pass one or the other.
+| window target plus `element_index` | accessibility action | UIA Invoke, `AXPerformAction`, or AT-SPI. Background, no cursor move, no focus steal. |
+| window target plus `x`, `y` | window-local pixel | coordinates are relative to that window's screenshot. For keyboard tools, this form can click the coordinate to establish renderer focus before sending keys. |
+| desktop target plus `x`, `y` | screen-absolute | true screen pixels on the primary display, with foreground delivery |
-A window-less action is **never silently reinterpreted**. Under window scope it is rejected with a structured `desktop_scope_disabled` error that points the caller at `set_config capture_scope=desktop`, rather than treating screen pixels as window-local pixels.
+The keyboard family's coordinate form is mutually exclusive with
+`element_index`. A malformed, mixed, or ambiguous target fails before
+authorization and platform dispatch.
---
## Valid combinations
-`get_window_state` always returns both the accessibility tree and a screenshot by default, so perception is not a matrix axis. The enforced combinations are `capture_scope`, action rung, and delivery mode:
+`get_window_state` returns both the accessibility tree and a screenshot by
+default. The enforced combinations are target modality, action rung, and
+delivery mode:
-| `capture_scope` | Action rung | `delivery_mode` | Valid? | Why |
+| Target | Action rung | `delivery_mode` | Valid? | Why |
|---|---|---|---|---|
-| `window` | `ax` (`element_index`) | `background` | ✅ | The default. Semantic actions on a background-capable window. |
-| `window` | `ax` (`element_index`) | `foreground` | ✅ | Activate, then act by element. |
-| `window` | `px` (`x`, `y`) | `background` | ✅ | Click a coordinate off the window screenshot without raising the target when the platform/app supports routed delivery. |
-| `window` | `px` (`x`, `y`) | `foreground` | ✅ | Activate, then click by coordinate. |
-| `desktop` | `px` (`x`, `y`) | `foreground` | ✅ | The screen-absolute loop: read the whole desktop, click absolute coordinates on the active desktop. |
-| `desktop` | `ax` (`element_index`) | any | ❌ | A desktop-absolute action has no `window_id`, so there is no element tree to resolve an `element_index` against. |
-| `desktop` | any | `background` | ❌ | Screen-absolute input hits whatever owns those pixels on the active desktop; there is no per-process background route. |
-| `window` | window-less | any | ❌ | A window-less action while scope is `window` returns `desktop_scope_disabled`. |
+| window | `ax` (`element_index`) | `background` | ✅ | Semantic action on a background-capable window. |
+| window | `ax` (`element_index`) | `foreground` | ✅ | Activate, then act by element. |
+| window | `px` (`x`, `y`) | `background` | ✅ | Act at a coordinate from the window screenshot without raising the target when supported. |
+| window | `px` (`x`, `y`) | `foreground` | ✅ | Activate, then act by coordinate. |
+| desktop | `px` (`x`, `y`) | `foreground` | ✅ | Act at screen coordinates on the primary display. |
+| desktop | `ax` (`element_index`) | any | ❌ | A desktop target has no window element tree. |
+| desktop | any | `background` | ❌ | Screen input lands on the active desktop and has no per-process background route. |
-The rejected combinations are enforced. Desktop scope is foreground and pixel-only by design.
+The driver enforces these rejections before it sends input.
---
@@ -166,16 +195,20 @@ Success payloads stay strictly validated: an unknown key on the success shape is
| `delivery_mode: "foreground"` (action-scoped activation and restore) | ✅ | ✅ | ✅ X11; Wayland activation is compositor-constrained |
| `bring_to_front` (persistent activation for focus-proxy surfaces) | ✅ | ✅, chiefly for RDP | ✅ X11 EWMH activation (`_NET_ACTIVE_WINDOW` + input focus); Wayland raise is compositor-constrained |
| `get_desktop_state` (desktop capture) | ✅ | ✅ | ✅ |
-| Window-less desktop click (`click{x,y}`, no `pid`) | ✅ | rolling out | rolling out |
+| Per-call window and primary-display targets | ✅ | ✅ | ✅ |
---
## Mental model
-```
-WINDOW scope = "talk to a window" → needs pid (+window_id for elements); background by default
-DESKTOP scope = "talk to the screen" → needs only x,y; screen-absolute; foreground; vision
+```text
+window target = exact pid + window_id; background by default
+desktop target = exact display_id; screen coordinates and foreground delivery
+
+session = lifecycle, cursor, recording, cleanup, and telemetry ownership
+target = the window or display selected for this call
+authority = the independent permission and policy stack
-CLI = stateless; writes config to DISK (or proxies to a running daemon)
-MCP = stateful session; config override in MEMORY; owns the agent cursor
+CLI call = one disposable implicit session
+MCP = one reusable implicit session per authenticated transport
```
diff --git a/docs/content/docs/reference/cua-driver/embedding.mdx b/docs/content/docs/reference/cua-driver/embedding.mdx
index b9db50b1a9..33635588fc 100644
--- a/docs/content/docs/reference/cua-driver/embedding.mdx
+++ b/docs/content/docs/reference/cua-driver/embedding.mdx
@@ -128,9 +128,10 @@ Destroy the SDK client and call `await embedded.stop()` from every orderly shutd
- The host holds a parent-liveness pipe. EOF shuts down the daemon if the host
exits; Rust destruction also requests a kill as a fallback. This is crash
containment, not a substitute for orderly shutdown.
-- Capture scope is session state, not host state. Concurrent sessions sharing
- one daemon may independently select `auto`, strict `window`, or strict
- `desktop`; always end each session you start.
+- Capture modality is selected by each observation or action target, not by the
+ host or lifecycle session. Concurrent sessions sharing one daemon may issue
+ exact window and desktop calls independently; always close host leases and
+ explicitly end named sessions when deterministic cleanup matters.
- macOS grant changes require a daemon restart. Never start the daemon before
the permission-owning host process is ready.
- Custom endpoints are accepted only when they are absent or a stale socket.
diff --git a/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdx b/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdx
index 572096066a..8105c8d872 100644
--- a/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdx
+++ b/docs/content/docs/reference/cua-driver/mcp-tool-notes.mdx
@@ -11,7 +11,8 @@ Several parameters are a **shared cross-platform contract**: the same JSON shape
| Parameter | Where | Notes |
| --------- | ----- | ----- |
-| `session` | every action and cursor tool | Optional run identity for the agent cursor and per-session state; the same id works over MCP, the CLI, or the raw socket and follows the run across apps and windows. Accepted on all three platforms. Earlier Windows and Linux builds rejected it via `additionalProperties:false`. |
+| `session` | every action and cursor tool | Optional public run label. The runtime creates one private implicit session per authenticated transport when this field is absent, then reuses it for later calls on that transport. A public label is never caller identity or authorization evidence. Accepted on all three platforms. |
+| `target` | `move_cursor`, `click`, `drag`, `scroll`, `type_text`, `press_key`, `hotkey` | Preferred tagged per-call target: `{kind:"window", pid, window_id}` or `{kind:"desktop", display_id:"primary"}`. It cannot be combined with legacy `scope`, `pid`, or `window_id` fields. |
| `delivery_mode` | the input family (`click`, `double_click`, `right_click`, `drag`, `scroll`, `type_text`, `press_key`, `hotkey`) | `"background"` (default) tries to inject without fronting or raising the target. See [Best-effort background](/concepts/the-no-foreground-contract). `"foreground"` briefly fronts the target, acts, then restores the prior frontmost. Use it when a background attempt did not land. Legacy `"auto"` is removed; omitted or unknown values fall back to `"background"` for safety. |
| `capture_mode` | `get_window_state` | **Deprecated and ignored.** Still accepted for back-compat so old callers do not error, but it has no effect. `get_window_state` always returns both the accessibility tree and a screenshot by default. There is no `ax`/`vision`/`som` capture choice; the modality (`ax` vs `px`) is chosen at action time by how you address the target. |
| `include_screenshot` | `get_window_state` | Boolean, default `true` (returns the tree **and** a screenshot). Set `false` to skip the screenshot grab and return the tree only when re-indexing before an element-`ax` action. |
@@ -19,7 +20,17 @@ Several parameters are a **shared cross-platform contract**: the same JSON shape
### Required parameters
-The `required` set is uniform across platforms: `click` requires nothing, `scroll` requires `direction`, and `zoom` requires `window_id` plus `x1`/`y1`/`x2`/`y2`. `pid` is **conditionally** required. Every per-window action needs it; a windowless desktop-scope call omits it. Code validates that rule with a clear error rather than pinning it in the schema, so a client that omits `pid` for a desktop-scope action is not schema-rejected.
+The `required` set is uniform across platforms: `click` requires nothing,
+`scroll` requires `direction`, and `zoom` requires `window_id` plus
+`x1`/`y1`/`x2`/`y2`. The preferred `target` makes the modality explicit.
+Legacy flat calls still validate `pid` conditionally: a window action needs it,
+while a desktop action omits it.
+
+The first admitted stateful call creates the transport's implicit lifecycle
+session. Repeated unnamed clicks on the same MCP connection belong to that one
+session; they do not create one session per click. The default idle TTL is five
+minutes, separate from the cursor's visibility timeout. Transport close,
+explicit end, or idle expiry runs the same cleanup path.
### PID-only window targets
@@ -34,7 +45,7 @@ A few parameters are platform-specific by design and are intentionally NOT part
| `launch_app` identifiers | macOS: `bundle_id`, `urls`. Windows: `aumid`, `launch_path`, `path`, `start_minimized`. | App launch is OS-native. `name` is the portable fallback that works on both. |
| `debug_window_info` | Windows only | A window-handle / class / rect / z-order debug tool with no macOS or Linux counterpart. |
| `check_permissions.prompt` | macOS only | Public tool calls are read-only by default. `prompt:true` is refused before platform dispatch; use the human-run `cua-driver permissions grant` setup command, which launches the installed app through LaunchServices. There is no Windows or Linux equivalent of TCC. |
-| Windowless screen-absolute (desktop-scope) clicks/scrolls | all three platforms, **exposed differently** | The capability exists everywhere, but the knob differs: macOS takes a **per-call `scope:"desktop"`** parameter on the pointer tools, while Windows and Linux gate it on the persisted **`capture_scope:"desktop"`** config (`set_config`). So a per-call `scope` param appears only on macOS; on Windows/Linux you opt in once via config. Unifying this knob is a tracked follow-up. |
+| Per-call window or desktop target | all three platforms | `target` has the same tagged shape on each platform. `display_id:"primary"` is the portable desktop target in this release; unsupported display IDs fail explicitly. Legacy scope/config fields remain only for compatibility. |
| `modifier` on a *background* click | honored on macOS and Linux; dropped on a Windows background click | A Windows background click goes through UIA Invoke / PostMessage, which carry no live keyboard state, so `modifier` takes effect only on the `delivery_mode:"foreground"` (SendInput) rung there. |
## Action response shape
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
index d3f89a1970..5abbef0296 100644
--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx
+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
@@ -12,7 +12,7 @@ description: Reference for every MCP tool Cua Driver exposes
import { Callout } from 'fumadocs-ui/components/callout';
-`cua-driver` exposes 54 MCP tools through a single stdio server (`cua-driver mcp`). Every tool is also callable from the shell as `cua-driver <name> '<JSON-args>'`.
+`cua-driver` exposes 56 MCP tools through a single stdio server (`cua-driver mcp`). Every tool is also callable from the shell as `cua-driver <name> '<JSON-args>'`.
Tool names are `snake_case`. Responses are MCP `CallTool.Result` envelopes: a text content block prefixed with a `✅` summary (or the error reason on failure), plus optional image or structured-content blocks on tools that produce them. See the [CLI reference](/reference/cua-driver/cli-reference) for CLI-specific options like `--socket` and `--screenshot-out-file`.
@@ -80,7 +80,7 @@ Optional `max_elements` / `max_depth` bound the AX walk to mitigate context-wind
- `pid` (integer, required): Target process ID.
- `query` (string, optional): Case-insensitive filter for tree_markdown and structured elements. Returns matching actionable rows plus their actionable ancestors without renumbering element_index values.
- `screenshot_out_file` (string, optional): When set, write the PNG to this file path (~ expanded) instead of embedding base64 in the response. The structured output will contain screenshot_file_path instead.
-- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
+- `session` (string, optional): Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session.
- `window_id` (integer, required): Target window ID from list_windows.
```json
@@ -97,12 +97,12 @@ For the full AX subtree of a single window (with interactive element indices you
### `get_desktop_state`
-Capture a full-display vision screenshot in true screen pixels (no downscale), for scope="desktop" GUI loops where the agent then drives click(x,y, scope="desktop") with no pid/window_id. Returns the PNG at native display resolution plus the true screen size and backing scale factor so screen-absolute pixel picks land exactly. Vision-only: no AX tree walk.
+Capture the full display in true screen pixels with no downscale. Use its native-size PNG as the coordinate source for actions whose target is &#123;kind:"desktop",display_id:"primary"&#125;. Returns the true screen size and backing scale factor. Vision-only: no AX tree walk.
**Arguments:**
- `screenshot_out_file` (string, optional): Write PNG here instead of base64.
-- `session` (string, optional): Optional session id.
+- `session` (string, optional): Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session.
### `get_screen_size`
@@ -110,7 +110,7 @@ Return the logical size of the main display in points plus its backing scale fac
**Arguments:**
-- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
+- `session` (string, optional): Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session.
### `get_cursor_position`
@@ -118,7 +118,7 @@ Return the current mouse cursor position in screen points (origin top-left).
**Arguments:**
-- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
+- `session` (string, optional): Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session.
### `get_config`
@@ -245,11 +245,16 @@ from_zoom: set true after a zoom call to auto-translate zoom-image pixel coordin
- `modifier` (array of string, optional): Modifier keys: cmd, shift, option/alt, ctrl.
- `pid` (integer, optional): Target process ID.
- `scope` (string, optional): Coordinate frame for a windowless screen-absolute click (default "window"). Pass "desktop" when sending x,y with NO pid/window_id — the coordinates are then true screen pixels (read from get_desktop_state with scope="desktop"). Per-call; not a setting.
-- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
+- `session` (string, optional): Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session.
- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.
+- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.
+
+`display_id="primary"` is the portable desktop target in this release.
+Platforms that cannot address another display reject it explicitly rather
+than silently changing coordinate spaces.
- `window_id` (integer, optional): Target window ID. Required for element_index. Optional when element_token is supplied (the token carries it).
-- `x` (number, optional): X in screenshot pixels, read straight off the image you were handed — no scaling math needed. With pid+window_id (capture_scope=window): window-local pixels from the get_window_state PNG (top-left origin). Windowless (no pid/window_id, capture_scope=desktop): pixels from the get_desktop_state PNG (the native full-display image). Either way, the pixel you read IS the pixel that gets clicked; the driver undoes the Retina backing scale + any downscale internally.
-- `y` (number, optional): Y in screenshot pixels (see x). Window-local from get_window_state, or full-display from get_desktop_state under capture_scope=desktop.
+- `x` (number, optional): X in screenshot pixels. A window target uses the get_window_state PNG; a desktop target uses the native get_desktop_state PNG. The driver reverses Retina backing scale and any window-image downscale.
+- `y` (number, optional): Y in screenshot pixels from the image selected by target.
### `double_click`
@@ -265,7 +270,7 @@ Pixel path (x, y provided): two down/up pairs ~80 ms apart at the given coordina
- `element_index` (integer, optional): Element index from get_window_state. Cua Driver 0.17 requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.
- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.
- `pid` (integer, required)
-- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
+- `session` (string, optional): Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session.
- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.
- `window_id` (integer, optional): CGWindowID. Required when element_index is used. Optional when element_token is supplied (the token carries it).
- `x` (number, optional): Screen X coordinate (pixel path).
@@ -292,7 +297,7 @@ Exactly one of `element_index` or (`x` AND `y`) must be provided. `pid` always r
- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.
- `modifier` (array of string, optional): Modifier keys held during the right-click: cmd/shift/option/ctrl. Pixel path only.
- `pid` (integer, required): Target process ID.
-- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
+- `session` (string, optional): Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session.
- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.
- `window_id` (integer, optional): CGWindowID. Required when element_index is used. Optional when element_token is supplied (the token carries it).
- `x` (number, optional): X in window-local screenshot pixels. Must be provided together with y.
@@ -325,8 +330,13 @@ When `from_zoom` is true, coordinates are in the last zoom image for this pid; t
- `modifier` (array of string, optional): Modifier keys held across the entire gesture: cmd/shift/option/ctrl.
- `pid` (integer, optional): Target process ID.
- `scope` (string, optional): Use desktop with no pid/window_id for native get_desktop_state screenshot coordinates. default: `"window"`
-- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
+- `session` (string, optional): Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session.
- `steps` (integer, optional): Number of intermediate mouseDragged events linearly interpolated along the path. Default: 20. range: 1–200
+- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.
+
+`display_id="primary"` is the portable desktop target in this release.
+Platforms that cannot address another display reject it explicitly rather
+than silently changing coordinate spaces.
- `to_x` (number, required): Drag-end X in window-local screenshot pixels.
- `to_y` (number, required): Drag-end Y in window-local screenshot pixels.
- `window_id` (integer, optional): CGWindowID for the window the pixel coordinates were measured against. Optional only when pid owns exactly one eligible top-level window; otherwise the action refuses with ambiguous_window_target.
@@ -351,8 +361,13 @@ WEB CONTENT (Chromium/WebKit/Electron — browser tabs, Slack, VS Code, X's comp
- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.
- `pid` (integer, optional): Target process ID.
- `scope` (string, optional): Use desktop with no pid/window_id to type into the frontmost application. default: `"window"`
-- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
+- `session` (string, optional): Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session.
- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.
+- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.
+
+`display_id="primary"` is the portable desktop target in this release.
+Platforms that cannot address another display reject it explicitly rather
+than silently changing coordinate spaces.
- `text` (string, required): Text to insert at the target's cursor.
- `window_id` (integer, optional): CGWindowID. Required when element_index is used. Optional when element_token is supplied (the token carries it).
- `x` (number, optional): Screenshot-pixel X of the field to type into — the element px action form. Pass x,y (no element_index) and the tool pixel-clicks there to establish real renderer focus, then types. Use for Chromium/Electron inputs the AX path can't reach. Read straight off the get_window_state PNG, same convention as click.
@@ -379,8 +394,13 @@ A key press is confirmed only when a bounded native AX value/selection read-back
- `modifiers` (array of string, optional): Modifier keys: cmd, shift, option/alt, ctrl, fn.
- `pid` (integer, optional)
- `scope` (string, optional): Use desktop with no pid/window_id to send the key to the frontmost application. default: `"window"`
-- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
+- `session` (string, optional): Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session.
- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.
+- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.
+
+`display_id="primary"` is the portable desktop target in this release.
+Platforms that cannot address another display reject it explicitly rather
+than silently changing coordinate spaces.
- `window_id` (integer, optional): Target window. Required for delivery_mode:"foreground". Does NOT itself raise the window — raising is gated on delivery_mode.
- `x` (number, optional): Screenshot-pixel X — the element px action form: pixel-click there to focus, then send the key. Use when the key must go to a Chromium/Electron surface the AX path can't focus. Pass with y, no element_index.
- `y` (number, optional): Screenshot-pixel Y (see x).
@@ -405,7 +425,12 @@ Recognized modifiers: cmd/command, shift, option/alt, ctrl/control, fn. Non-modi
- `keys` (array of string, required): Modifier(s) and one non-modifier key, e.g. ["cmd", "c"]. items: 2–unbounded
- `pid` (integer, optional): Target process ID.
- `scope` (string, optional): Use desktop with no pid/window_id to send the chord to the frontmost application. default: `"window"`
-- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
+- `session` (string, optional): Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session.
+- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.
+
+`display_id="primary"` is the portable desktop target in this release.
+Platforms that cannot address another display reject it explicitly rather
+than silently changing coordinate spaces.
- `window_id` (integer, optional): Target window. Required for delivery_mode:"foreground" (the NSMenu activation needs a window). Does NOT itself raise the window — raising is gated on delivery_mode.
- `x` (number, optional): Screenshot-pixel X — the element px action form: pixel-click there to focus, then send the combo (so e.g. Cmd+V pastes into that field). Pass with y. Use for Chromium/Electron surfaces the background combo can't reach.
- `y` (number, optional): Screenshot-pixel Y (see x).
@@ -429,7 +454,7 @@ For free-form text entry into web inputs, prefer `type_text_chars` which synthes
- `element_index` (integer, optional): Element index from get_window_state. Cua Driver 0.17 requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.
- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.
- `pid` (integer, required)
-- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
+- `session` (string, optional): Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session.
- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.
- `value` (string, required): New value. AX will coerce to the element's native type.
- `window_id` (integer, optional): CGWindowID for the window whose get_window_state produced the element_index. Required when element_index is used; optional when element_token is supplied (the token carries it).
@@ -458,8 +483,13 @@ Mapping: by='page' → larger step; by='line' → smaller step; amount = number
- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. If element_index, snapshot_id, or window_id are also supplied they must agree. Returns an explicit stale error once a newer snapshot supersedes it.
- `pid` (integer, optional)
- `scope` (string, optional): Use desktop with x,y and no pid/window_id for native get_desktop_state screenshot coordinates. default: `"window"`
-- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
+- `session` (string, optional): Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session.
- `snapshot_id` (string, optional): Snapshot handle from get_window_state. Required when targeting by element_index; stale snapshots fail closed.
+- `target` (window target or desktop target, optional): Exact capture/input target selected independently for each action.
+
+`display_id="primary"` is the portable desktop target in this release.
+Platforms that cannot address another display reject it explicitly rather
+than silently changing coordinate spaces.
- `window_id` (integer, optional)
- `x` (number, optional): Window-local screenshot X (top-left origin of the PNG from get_window_state). With `y`, routes through the pixel-wheel path at this point — use for a scrollable surface that isn't in the AX tree. Requires window_id to anchor the window→screen conversion.
- `y` (number, optional): Window-local screenshot Y. See `x`.
@@ -476,7 +506,8 @@ Move a cursor to (x, y). In window scope (default), moves only the agent cursor
- `cursor_id` (string, optional): Cursor instance to move. Default: 'default'.
- `scope` (string, optional): default: `"window"`
-- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
+- `session` (string, optional): Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session.
+- `target` (window target or desktop target, optional): Preferred per-call target. New callers should set this field.
- `x` (number, required)
- `y` (number, required)
@@ -626,7 +657,7 @@ Caveats:
Update cua-driver-rs configuration. Changes to max_image_dimension take effect immediately. The experimental_pip keys are persisted to ~/.cua-driver/config.json and take effect on the next daemon restart (the PiP backend is initialised once at startup).
-Note: capture_mode is a per-call param (on get_window_state / click), not a stored setting. Capture scope is selected by start_session, not set_config.
+Note: capture_mode is a per-call param (on get_window_state / click), not a stored setting. Capture modality is selected by each action's target; the old capture_scope config key is retired.
**Arguments:**
@@ -634,34 +665,30 @@ Note: capture_mode is a per-call param (on get_window_state / click), not a stor
- `experimental_pip_geometry` (string, optional): PiP window size + optional position in `WxH` or `WxH+X+Y` form (e.g. `320x200+24+24`). Applies on next daemon restart.
- `key` (string, optional): Name of a single config field to write (&#123;key, value&#125; shape, matching the CLI `config set` and the Windows/Linux tools). Pair with `value`. Equivalent to passing the field directly.
- `max_image_dimension` (integer, optional): Max dimension for screenshot resizing (0 = no limit).
-- `value` (undefined, optional): New value for `key`. JSON type depends on the key.
+- `value` (unknown, optional): New value for `key`. JSON type depends on the key.
### `start_session`
-Declare a session — a named, color-coded identity for THIS agent run. Pass a stable `session` id and choose capture_scope=auto|window|desktop; the agent cursor, capture policy, per-session config, and recording all key on it, and it follows the run across any apps/windows. The cursor's color is derived from the id, so distinct runs are visually distinct. A cursor is shown only for a declared session — call this (or pass `session` on your first action) to opt in. Idempotent: re-calling with the same id just refreshes its idle-TTL. End it with `end_session` (or let the idle-TTL reclaim it). Concurrent runs/subagents each pass their own `session` to get their own cursor.
+Optionally name and start a lifecycle session for this agent run. When `session` is omitted, create or return the authenticated transport lease's implicit session. Ordinary actions create that implicit session automatically, so this tool is optional. `capture_scope` is deprecated compatibility input; new callers select window or desktop modality per action. Idempotent.
**Arguments:**
-- `capture_scope` (string, optional): Per-session perception/action modality. auto starts window-only and requires explicit escalation before desktop tools; escalation permanently switches that session to desktop scope. To recover window scope, call end_session, then start_session with a new session id. window and desktop are strict. Immutable for the live session. default: `"auto"`
+- `capture_scope` (string, optional): Deprecated compatibility policy. New callers select window or desktop
+modality on each action instead of storing it on the session.
- `cursor_theme` (object or null, optional): Optional initial cursor theme. The host applies it before the cursor is
first made visible, avoiding a flash of the default theme.
-- `session` (string, required): Stable session id for this run (e.g. "research-run-1").
-
-```json
-{"session":"example"}
-```
+- `session` (string, optional): Optional stable public label for this run (e.g. "research-run-1").
+When omitted, the authenticated transport lease's implicit session is
+created or returned.
### `end_session`
-End a session declared with `start_session`: removes its agent cursor, stops any recording it owns, and clears its per-session config. Call this when a run finishes so its cursor doesn't linger (otherwise the idle-TTL reclaims it after a period of inactivity). Idempotent.
+End one visible lifecycle session and run its cursor, recording, configuration, and other cleanup hooks exactly once. Omit `session` to end the authenticated transport's implicit session. Idempotent.
**Arguments:**
-- `session` (string, required): The session id to end.
-
-```json
-{"session":"example"}
-```
+- `session` (string, optional): Optional public label to end. When omitted, end the caller's attached
+implicit session.
### `set_agent_cursor_enabled`
@@ -786,7 +813,8 @@ Deterministically verify bounded predicates against one exact window. The driver
- `include_screenshot` (boolean or null, optional): Return the final window screenshot as image content for a multimodal
caller. The driver does not interpret that image.
- `pid` (integer, required): Exact process whose window may be observed. range: 1–unbounded
-- `session` (string, optional): Optional session id for capture-scope and authorization continuity.
+- `session` (string, optional): Optional public session label for lifecycle continuity. It never selects
+capture modality or authorization.
- `stable_samples` (integer, optional): Consecutive satisfied samples required before returning success. default: `2`; range: 1–5
- `timeout_ms` (integer, optional): Bounded wait. Zero performs one sample. default: `5000`; range: 0–10000
- `window_id` (integer, required): Exact native window identifier.
@@ -835,7 +863,7 @@ Read-only browser inspection. Mode 1 (bind): pass pid + window_id of a native br
- `pid` (integer, optional): Native browser process id (bind mode).
- `query` (string, optional): Read-only semantic match over role, accessible name, and visible text.
- `scope_ref` (string, optional): Current semantic/content ref whose subtree should be observed.
-- `session` (string, optional): Stable caller-declared session id. Browser targets, tabs, and refs are scoped to this session.
+- `session` (string, optional): Optional public session label. Browser targets, tabs, and refs use the authenticated transport's implicit lifecycle session when omitted.
- `snapshot_format` (string, optional): Versioned snapshot contract. dom_refs_v1 remains the compatibility default.
- `tab_id` (string, optional): Opaque tab id from get_browser_state (session-scoped).
- `target_id` (string, optional): Opaque browser target id minted by get_browser_state (session-scoped; never a CDP id).
@@ -851,7 +879,7 @@ Explicitly prepare an owned DevTools endpoint for a browser pid. Existing endpoi
- `approval_token` (string, optional): Legacy single-use setup token. Existing-profile use is disabled unless a trusted launcher explicitly enables the same-user-writable compatibility path.
- `pid` (integer, required): Browser process id to prepare.
- `profile` (object, optional)
-- `session` (string, optional): Stable caller-declared session id. Browser targets, tabs, and refs are scoped to this session.
+- `session` (string, optional): Optional public session label. Browser targets, tabs, and refs use the authenticated transport's implicit lifecycle session when omitted.
- `strategy` (object, optional)
- `window_id` (integer, optional): Exact native window approval anchor; required for strategy.kind=existing_profile.
@@ -865,7 +893,7 @@ Navigate one tab of an exactly-bound browser target to a new URL (http/https/abo
**Arguments:**
-- `session` (string, optional): Stable caller-declared session id. Browser targets, tabs, and refs are scoped to this session.
+- `session` (string, optional): Optional public session label. Browser targets, tabs, and refs use the authenticated transport's implicit lifecycle session when omitted.
- `tab_id` (string, required): Opaque tab id from get_browser_state (session-scoped).
- `target_id` (string, required): Opaque browser target id minted by get_browser_state (session-scoped; never a CDP id).
- `url` (string, required): Destination URL (http:, https:, or about:).
@@ -882,7 +910,7 @@ Click a page element (by ref) or viewport coordinates in an exactly-bound tab. D
- `input_route` (string, optional): "trusted" (default): Input.dispatchMouseEvent. It refuses rather than foregrounding a standalone browser. "dom_event": synthetic full-background DOM click, only when explicitly requested. Dispatch does not prove the control activated; refresh page state and verify the expected postcondition.
- `ref` (string, optional): Page element ref in the p&lt;snapshot&gt;:&lt;index&gt; namespace from get_browser_state. Refs are invalidated by navigation and by newer snapshots of the same tab.
-- `session` (string, optional): Stable caller-declared session id. Browser targets, tabs, and refs are scoped to this session.
+- `session` (string, optional): Optional public session label. Browser targets, tabs, and refs use the authenticated transport's implicit lifecycle session when omitted.
- `tab_id` (string, required): Opaque tab id from get_browser_state (session-scoped).
- `target_id` (string, required): Opaque browser target id minted by get_browser_state (session-scoped; never a CDP id).
- `x` (number, optional): Viewport x (CSS px) — alternative to ref.
@@ -901,7 +929,7 @@ Type text into an exactly-bound tab via the Input domain. mode="insert_text" (de
- `mode` (string, optional): insert_text (default): bulk Input.insertText. keystrokes: per-character Input.dispatchKeyEvent.
- `ref` (string, required): Page element ref in the p&lt;snapshot&gt;:&lt;index&gt; namespace from get_browser_state. Refs are invalidated by navigation and by newer snapshots of the same tab.
- `replace` (boolean, optional): false (default): insert at the caret, appending to whatever the field already holds. true: select the element's whole content first so the text replaces it — with an empty text this clears the field. Replacement goes through the selection, so beforeinput/input still fire and framework state stays consistent.
-- `session` (string, optional): Stable caller-declared session id. Browser targets, tabs, and refs are scoped to this session.
+- `session` (string, optional): Optional public session label. Browser targets, tabs, and refs use the authenticated transport's implicit lifecycle session when omitted.
- `tab_id` (string, required): Opaque tab id from get_browser_state (session-scoped).
- `target_id` (string, required): Opaque browser target id minted by get_browser_state (session-scoped; never a CDP id).
- `text` (string, required): Text to type.
@@ -920,7 +948,7 @@ Inspect or resolve a page-owned JavaScript alert, confirm, prompt, or beforeunlo
- `delivery_mode` (string, optional): Requested foreground posture for accept/dismiss. Linux Chromium requires foreground; inspect is read-only. default: `"background"`
- `dialog_id` (string, optional): Opaque current dialog generation returned by action=inspect.
- `prompt_text` (string, optional): Sensitive response text, valid only when accepting a prompt dialog.
-- `session` (string, optional): Stable caller-declared session id. Browser targets, tabs, and refs are scoped to this session.
+- `session` (string, optional): Optional public session label. Browser targets, tabs, and refs use the authenticated transport's implicit lifecycle session when omitted.
- `tab_id` (string, required): Opaque tab id from get_browser_state (session-scoped).
- `target_id` (string, required): Opaque browser target id minted by get_browser_state (session-scoped; never a CDP id).
@@ -936,7 +964,7 @@ Assign one or more explicit absolute local files to an exact live &lt;input type
- `files` (array of string, required): items: 1–32
- `ref` (string, required): Page element ref in the p&lt;snapshot&gt;:&lt;index&gt; namespace from get_browser_state. Refs are invalidated by navigation and by newer snapshots of the same tab.
-- `session` (string, optional): Stable caller-declared session id. Browser targets, tabs, and refs are scoped to this session.
+- `session` (string, optional): Optional public session label. Browser targets, tabs, and refs use the authenticated transport's implicit lifecycle session when omitted.
- `tab_id` (string, required): Opaque tab id from get_browser_state (session-scoped).
- `target_id` (string, required): Opaque browser target id minted by get_browser_state (session-scoped; never a CDP id).
@@ -986,7 +1014,7 @@ Perform hover, right-click, double-click, scroll, or drag in an exactly-bound br
### `escalate_session`
-Unlock the desktop phase of an auto capture-scope session after the window action ladder has been exhausted and verified. Escalation is permanent for that session and disables window-scoped tools. To recover window scope, call end_session, then start_session with a new session id.
+Deprecated compatibility tool for legacy capture-scope sessions. New callers select window or desktop modality on each action. No deescalate_session tool exists.
**Arguments:**
@@ -998,14 +1026,30 @@ Unlock the desktop phase of an auto capture-scope session after the window actio
{"reason":"ax_tree_pixel_mismatch","session":"example"}
```
-### `get_session_state`
+### `get_session`
-Read the live session's capture policy and effective scope.
+Read content-free lifecycle, cursor, recording, and idle status for one session visible to this authenticated transport. Omit `session` to inspect its implicit session.
**Arguments:**
-- `session` (string, required)
+- `session` (string, optional): Optional public label. When omitted, inspect the caller's attached
+implicit session.
-```json
-{"session":"example"}
-```
+### `list_sessions`
+
+List content-free lifecycle summaries attached to this authenticated transport lease. It does not enumerate other callers' sessions.
+
+**Arguments:**
+
+- `cursor` (string, optional): Opaque continuation cursor returned by a previous call.
+- `limit` (integer or null, optional): Maximum number of content-free summaries to return (default 50, max
+100). Ordinary agent transports are scoped to their own lease. range: 0–unbounded
+
+### `get_session_state`
+
+Deprecated compatibility alias that reads a live legacy session's capture policy. Use get_session for lifecycle state.
+
+**Arguments:**
+
+- `session` (string, optional): Optional public label. When omitted, inspect the caller's attached
+implicit session.
diff --git a/docs/content/docs/reference/cua-driver/permission-modes.mdx b/docs/content/docs/reference/cua-driver/permission-modes.mdx
index 276052018e..9f2c3aff5d 100644
--- a/docs/content/docs/reference/cua-driver/permission-modes.mdx
+++ b/docs/content/docs/reference/cua-driver/permission-modes.mdx
@@ -323,8 +323,10 @@ 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 semantic cursor is optional activity feedback. It initializes on the first
+cursor-bearing action even when the transport uses an implicit session. A
+publicly named session displays its sanitized label in a badge below the
+cursor. The badge uses
the session color, strips control characters, collapses whitespace, and
truncates long labels.
diff --git a/docs/content/docs/reference/cua-driver/process-model.mdx b/docs/content/docs/reference/cua-driver/process-model.mdx
index b13d2fdaef..5c7116b111 100644
--- a/docs/content/docs/reference/cua-driver/process-model.mdx
+++ b/docs/content/docs/reference/cua-driver/process-model.mdx
@@ -101,16 +101,22 @@ deliberately share one daemon across several MCP clients, start the daemon and
give every client the same explicit `cua-driver mcp --socket <endpoint>`
command. Do not rely on ambient daemon discovery.
-Session identity solves a narrower state problem. When a proxy starts, it mints a session identity and stamps forwarded calls with it. The daemon uses that identity to scope mutable state to one client lifetime. Recording ownership, per-session config overrides, and the agent-cursor overlay are all keyed by session.
+Session identity solves a narrower state problem. Each authenticated transport
+gets one private implicit lifecycle identity. The daemon uses it to scope
+mutable state to one client lifetime. Recording ownership, per-session config
+overrides, and the agent-cursor overlay are keyed by that lifecycle session.
+Callers may add a public label, but the label does not carry authority.
For same-process SDK runtimes, Cua adds a private runtime generation behind the
public session label. Two runtimes may therefore both use `research-1` without
-sharing capture scope, tombstones, cursor ownership, recording teardown,
+sharing lifecycle state, tombstones, cursor ownership, recording teardown,
browser refs, or element tokens. The private generation is never serialized
and is not a credential or same-process security boundary.
-`default` is the reserved anonymous fallback, not an isolated session label.
-Concurrent hosts should always declare an explicit session.
+Repeated unnamed calls on one transport reuse its implicit session. A
+different transport gets a different private identity. Callers need an
+explicit public session only when they want a stable human-readable label or
+explicit lifecycle control.
<VideoDemo
className="my-8"
@@ -123,7 +129,11 @@ Concurrent hosts should always declare an explicit session.
four sessions still share the same desktop.
</VideoDemo>
-Cleanup follows the proxy connection, not a final message. The proxy keeps a long-lived control connection open to the daemon. When the proxy exits, even from an ungraceful kill, the kernel closes that connection. The daemon sees EOF and removes state owned by that session. This prevents stale recordings, cursors, and temporary config overrides.
+Cleanup follows the proxy connection as well as explicit lifecycle calls. The
+proxy keeps a long-lived control connection open to the daemon. When the proxy
+exits, even from an ungraceful kill, the kernel closes that connection. The
+daemon sees EOF and runs the same cleanup hooks used by `end_session`. The
+five-minute idle TTL provides the same cleanup for abandoned live transports.
## Lifetimes and memory
diff --git a/docs/content/docs/reference/cua-driver/sdk-reference.mdx b/docs/content/docs/reference/cua-driver/sdk-reference.mdx
index cb960326a5..2e7da0f8ea 100644
--- a/docs/content/docs/reference/cua-driver/sdk-reference.mdx
+++ b/docs/content/docs/reference/cua-driver/sdk-reference.mdx
@@ -169,13 +169,29 @@ handle automatically, but applications must still await `shutdown()`.
| Python | TypeScript | Input |
| ------------------- | ----------------- | ---------------------- |
| `start_session` | `startSession` | `StartSessionInput` |
-| `get_session_state` | `getSessionState` | `GetSessionStateInput` |
-| `escalate_session` | `escalateSession` | `EscalateSessionInput` |
+| `get_session` | `getSession` | `GetSessionInput` |
+| `list_sessions` | `listSessions` | `ListSessionsInput` |
| `end_session` | `endSession` | `EndSessionInput` |
-
-`StartSessionInput.capture_scope` / `captureScope` accepts `AUTO`, `WINDOW`, or
-`DESKTOP`. Capture scope is immutable for a live session. `AUTO` requires an
-explicit escalation before desktop tools are enabled.
+| `get_session_state` | `getSessionState` | `GetSessionStateInput` (deprecated) |
+| `escalate_session` | `escalateSession` | `EscalateSessionInput` (deprecated) |
+
+`start_session` is optional. The first ordinary call creates an implicit
+session owned by the SDK transport, and later calls on that transport reuse it.
+The default idle TTL is five minutes. Shutdown, explicit end, and transport
+close run the same cleanup hooks. A call that is still in flight cannot expire,
+and only completed calls refresh the idle timer.
+
+Use `start_session` when the run needs a public label or initial cursor theme.
+`get_session` and `list_sessions` return content-free state only for sessions
+visible to that transport. The public label is a map key, never an
+authorization credential. A trusted host can inspect its wider runtime
+namespace through `list_host_sessions_json()` / `listHostSessionsJson()`; agent
+tools cannot use that operator view.
+
+`StartSessionInput.capture_scope` / `captureScope`, `get_session_state`, and
+`escalate_session` remain available for legacy capture-scope sessions during
+the compatibility window. New code selects a target on each action. There is
+no `deescalate_session` method.
## Typed desktop methods
@@ -192,6 +208,19 @@ explicit escalation before desktop tools are enabled.
| `press_key` | `pressKey` | `PressKeyInput` |
| `hotkey` | `hotkey` | `HotkeyInput` |
+`move_cursor`, `click`, `drag`, `scroll`, `type_text`, `press_key`, and
+`hotkey` accept an `ActionTarget` / `actionTarget` on each call:
+
+```text
+window: { kind: "window", pid, window_id }
+desktop: { kind: "desktop", display_id: "primary" }
+```
+
+The desktop target uses screen coordinates and foreground delivery. The window
+target uses coordinates from that window's screenshot and keeps the existing
+background or foreground delivery ladder. Legacy flat `scope`, `pid`, and
+`window_id` fields remain accepted but cannot be combined with `target`.
+
## Typed cursor methods
| Python | TypeScript | Input |
@@ -201,8 +230,10 @@ explicit escalation before desktop tools are enabled.
| `set_agent_cursor_theme` | `setAgentCursorTheme` | `SetAgentCursorThemeInput` |
| `get_agent_cursor_state` | `getAgentCursorState` | `GetAgentCursorStateInput` |
-Every cursor operation is bound to a declared session. `cua.default` is the
-only built-in theme. A trusted local operator may validate, compile, and install
+Cursor-bearing actions create or wake the transport's implicit session even
+when the caller does not supply a public session. Cursor configuration methods
+still take a public session label. `cua.default` is the only built-in theme. A
+trusted local operator may validate, compile, and install
a custom theme with `cua-driver cursor-theme`; agent-facing tools may select an
installed theme ID but cannot install source or compiled theme data. See
[Agent cursor themes](/how-to-guides/driver/personalize-cursor) for the
diff --git a/docs/content/docs/reference/cua-driver/telemetry.mdx b/docs/content/docs/reference/cua-driver/telemetry.mdx
index 3f44ddbe08..81c132013e 100644
--- a/docs/content/docs/reference/cua-driver/telemetry.mdx
+++ b/docs/content/docs/reference/cua-driver/telemetry.mdx
@@ -120,15 +120,36 @@ These values are self-reported and normalized through allowlists. Unknown values
## Cua agent sessions
-A Cua agent session is a non-empty caller-declared `session` value. The value `default`, internal connection identities, and reserved fallback keys do not create agent-session events.
-
-The start event is emitted for a successful `start_session` declaration or the first known tool call that carries an explicit session. Repeated calls in the same live episode do not emit another start. Reusing an ID after explicit end or idle eviction creates a new episode with `revived=true`.
-
-The end event is emitted for `end_session` and idle eviction. It contains aggregate counters and booleans. When the platform has a cursor entry for that session, it also includes bounded cursor categories: enabled state, built-in/default/custom icon class, automatic/custom color source, label presence, motion customization, and an active-cursor count bucket. `cursor_outcome_observed=false` distinguishes sessions with no readable cursor entry from a disabled or default cursor. Cua Driver uses the caller session string only as a process-local map key. The string, a hash of it, and a replacement join token are absent from telemetry payloads.
-
-Both session events retain the episode's declared `capture_scope` (`window`, `desktop`, or `auto`) and its closed `client_kind` (`cli`, `direct`, `mcp`, `python_sdk`, or `typescript_sdk`). The Python and TypeScript package roots select their category automatically; applications cannot attach a free-form client label. `execution_mode` independently distinguishes `embedded` from `standalone` hosts.
-
-For `capture_scope=auto`, the end event sets `auto_escalated_to_desktop=true` only after a successful `escalate_session`. Its reason is limited to `ax_tree_pixel_mismatch`, `background_delivery_failed`, `foreground_ineffective`, `no_window_target`, or `other`; sessions without a successful auto escalation use `not_applicable`. Free-form escalation detail is never observed or sent.
+A Cua agent session is one lifecycle episode owned by a trusted transport.
+It may have an optional public `session` label, but telemetry never sends that
+label or the runtime's private transport identity.
+
+The start event is emitted for a successful `start_session` or the first
+admitted session-requiring call on a transport. Its `declaration` is
+`start_session` or `implicit_first_action`. Repeated calls in the same live
+episode do not emit another start. Explicitly reviving an ended public label
+creates a new episode with `revived=true`.
+
+The end event is emitted for explicit end, idle expiry, transport cleanup, and
+revocation. It contains aggregate counters and booleans. When the platform has
+a cursor entry, the event includes bounded cursor categories: enabled state,
+built-in/default/custom icon class, automatic/custom color source, label
+presence, motion customization, and an active-cursor count bucket.
+`cursor_outcome_observed=false` distinguishes a missing cursor entry from a
+disabled or default cursor.
+
+Both session events carry the closed `client_kind` (`cli`, `direct`, `mcp`,
+`python_sdk`, or `typescript_sdk`). The Python and TypeScript package roots
+select their category automatically; applications cannot attach a free-form
+client label. `execution_mode` independently distinguishes `embedded` from
+`standalone` hosts. The end event adds `used_window_modality` and
+`used_desktop_modality`, which are content-free booleans derived from admitted
+calls.
+
+`capture_scope`, `auto_escalated_to_desktop`, and `escalation_reason` remain
+bounded compatibility fields for legacy capture-scope sessions. New per-call
+targets do not mutate session capture state. Free-form escalation detail is
+never observed or sent.
Computer-action success covers fixed pointer and keyboard capabilities, app launch and kill, window activation, state-changing `page` operations, and successful browser navigation, click, type, pointer, file-assignment, download, or dialog-resolution calls. A structured browser refusal does not count as a completed computer action. `get_browser_state` and `browser_dialog` inspection are reads for this classifier, and `browser_prepare` is tracked as browser use rather than a computer action because preparation may either reuse an endpoint or produce an approved visible side effect.
diff --git a/libs/cua-driver/contract/README.md b/libs/cua-driver/contract/README.md
index 06715af7ed..e3e37b319f 100644
--- a/libs/cua-driver/contract/README.md
+++ b/libs/cua-driver/contract/README.md
@@ -18,19 +18,25 @@ surface through their runtime's existing MCP client.
The typed slice covers the cross-platform session lifecycle tools:
- `start_session`
-- `escalate_session`
-- `get_session_state`
+- `get_session`
+- `list_sessions`
- `end_session`
+Ordinary calls do not need `start_session`. The runtime creates one implicit
+session for the authenticated transport lease and reuses it until transport
+close, explicit end, or five minutes of inactivity. `escalate_session` and
+`get_session_state` remain deprecated compatibility tools for legacy
+capture-scope sessions. There is no `deescalate_session` tool.
+
It also covers the portable whole-desktop loop:
- `get_desktop_state`
- `get_screen_size`
- `get_cursor_position`
-- `move_cursor` with the required `scope="desktop"`
+- `move_cursor` with an exact per-call window or desktop `target`
- `set_window_frame` for exact, read-back-verified top-level window geometry
- `invoke_menu` for an exact native application-menu path resolved live at each hop
-- `click` with the required `scope="desktop"`
+- `click` with an exact per-call window or desktop `target`
- `drag` and `scroll` in native desktop coordinates
- `type_text`, `press_key`, and `hotkey` against the foreground application
- `clipboard_read` for available types and opt-in plain-text readback
@@ -61,7 +67,11 @@ The checked-observation slice is also shared by MCP and both generated SDKs:
harness to interpret. Cua Driver does not OCR or assign task meaning to it.
Session contracts are marked `canonical_runtime`: the same typed Rust input,
-output, and metadata declaration builds the live MCP tool. Desktop contracts
+output, and metadata declaration builds the live MCP tool. The preferred action
+target is a tagged union: `{kind:"window", pid, window_id}` or
+`{kind:"desktop", display_id:"primary"}`. Legacy flat `scope`, `pid`, and
+`window_id` fields remain accepted during the compatibility window but cannot
+be mixed with `target`. Desktop contracts
are marked `portable_subset`: their typed Rust inputs are a deliberately
narrower projection of the richer macOS, Linux, and Windows runtime schemas.
Each platform's desktop branch deserializes that projection before acting,
@@ -89,7 +99,7 @@ Compatibility is tracked separately at each boundary:
| Field | Current | Meaning |
| --- | --- | --- |
-| `contract_version` | `0.6.0` | Generated manifest and typed SDK shape |
+| `contract_version` | `0.7.0` | Generated manifest and typed SDK shape |
| `tools_list_schema_version` | `1` | cua-driver `tools/list` extension shape |
| `capability_version` | `1` | Additive capability-token vocabulary |
| `mcp_protocol_version` | `2025-06-18` | MCP initialization protocol served to agent runtimes |
diff --git a/libs/cua-driver/contract/manifest.json b/libs/cua-driver/contract/manifest.json
index 389cae4b73..de33a718c4 100644
--- a/libs/cua-driver/contract/manifest.json
+++ b/libs/cua-driver/contract/manifest.json
@@ -1,7 +1,7 @@
{
"generated_notice": "Generated by cua-contract-gen; do not edit by hand.",
"experimental": true,
- "contract_version": "0.6.0",
+ "contract_version": "0.7.0",
"tools_list_schema_version": "1",
"capability_version": "1",
"mcp_protocol_version": "2025-06-18",
@@ -47,12 +47,67 @@
"type": "integer"
},
"scope": {
- "const": "desktop"
+ "const": "desktop",
+ "description": "Deprecated flat desktop target retained for wire compatibility."
},
"session": {
"description": "Optional session id.",
"type": "string"
},
+ "target": {
+ "anyOf": [
+ {
+ "description": "Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.",
+ "oneOf": [
+ {
+ "additionalProperties": true,
+ "properties": {
+ "kind": {
+ "const": "window",
+ "type": "string"
+ },
+ "pid": {
+ "format": "uint32",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "window_id": {
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "kind",
+ "pid",
+ "window_id"
+ ],
+ "type": "object"
+ },
+ {
+ "additionalProperties": true,
+ "properties": {
+ "display_id": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "desktop",
+ "type": "string"
+ }
+ },
+ "required": [
+ "kind",
+ "display_id"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"x": {
"type": "number"
},
@@ -62,8 +117,7 @@
},
"required": [
"x",
- "y",
- "scope"
+ "y"
],
"type": "object"
},
@@ -389,7 +443,8 @@
"type": "array"
},
"scope": {
- "const": "desktop"
+ "const": "desktop",
+ "description": "Deprecated flat desktop target retained for wire compatibility."
},
"session": {
"description": "Optional session id.",
@@ -400,6 +455,60 @@
"minimum": 1,
"type": "integer"
},
+ "target": {
+ "anyOf": [
+ {
+ "description": "Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.",
+ "oneOf": [
+ {
+ "additionalProperties": true,
+ "properties": {
+ "kind": {
+ "const": "window",
+ "type": "string"
+ },
+ "pid": {
+ "format": "uint32",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "window_id": {
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "kind",
+ "pid",
+ "window_id"
+ ],
+ "type": "object"
+ },
+ {
+ "additionalProperties": true,
+ "properties": {
+ "display_id": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "desktop",
+ "type": "string"
+ }
+ },
+ "required": [
+ "kind",
+ "display_id"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"to_x": {
"type": "number"
},
@@ -411,8 +520,7 @@
"from_x",
"from_y",
"to_x",
- "to_y",
- "scope"
+ "to_y"
],
"type": "object"
},
@@ -533,7 +641,7 @@
},
{
"name": "end_session",
- "description": "End a session declared with `start_session`: removes its agent cursor, stops any recording it owns, and clears its per-session config. Call this when a run finishes so its cursor doesn't linger (otherwise the idle-TTL reclaims it after a period of inactivity). Idempotent.",
+ "description": "End one visible lifecycle session and run its cursor, recording, configuration, and other cleanup hooks exactly once. Omit `session` to end the authenticated transport's implicit session. Idempotent.",
"platforms": [
"macos",
"windows",
@@ -556,13 +664,11 @@
"additionalProperties": true,
"properties": {
"session": {
- "description": "The session id to end.",
+ "description": "Optional public label to end. When omitted, end the caller's attached\nimplicit session.",
"type": "string"
}
},
- "required": [
- "session"
- ],
+ "required": [],
"type": "object"
},
"success_output_schema": {
@@ -584,7 +690,7 @@
},
{
"name": "escalate_session",
- "description": "Unlock the desktop phase of an auto capture-scope session after the window action ladder has been exhausted and verified. Escalation is permanent for that session and disables window-scoped tools. To recover window scope, call end_session, then start_session with a new session id.",
+ "description": "Deprecated compatibility tool for legacy capture-scope sessions. New callers select window or desktop modality on each action. No deescalate_session tool exists.",
"platforms": [
"macos",
"windows",
@@ -1110,15 +1216,15 @@
}
},
{
- "name": "get_session_state",
- "description": "Read the live session's capture policy and effective scope.",
+ "name": "get_session",
+ "description": "Read content-free lifecycle, cursor, recording, and idle status for one session visible to this authenticated transport. Omit `session` to inspect its implicit session.",
"platforms": [
"macos",
"windows",
"linux"
],
"capabilities": [
- "session.capture_scope.read"
+ "session.lifecycle.read"
],
"annotations": {
"read_only": true,
@@ -1134,13 +1240,117 @@
"additionalProperties": true,
"properties": {
"session": {
+ "description": "Optional public label. When omitted, inspect the caller's attached\nimplicit session.",
+ "type": "string"
+ }
+ },
+ "required": [],
+ "type": "object"
+ },
+ "success_output_schema": {
+ "additionalProperties": true,
+ "properties": {
+ "client_kind": {
+ "enum": [
+ "cli",
+ "direct",
+ "mcp",
+ "python_sdk",
+ "typescript_sdk"
+ ],
+ "type": "string"
+ },
+ "cursor_visible": {
+ "type": "boolean"
+ },
+ "expires_in_seconds": {
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "idle_seconds": {
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "implicit": {
+ "type": "boolean"
+ },
+ "recording_active": {
+ "type": "boolean"
+ },
+ "session": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "state": {
+ "enum": [
+ "active",
+ "ending"
+ ],
+ "type": "string"
+ },
+ "transport": {
+ "enum": [
+ "cli",
+ "daemon",
+ "mcp_stdio",
+ "mcp_http"
+ ],
"type": "string"
}
},
"required": [
- "session"
+ "session",
+ "implicit",
+ "state",
+ "client_kind",
+ "transport",
+ "cursor_visible",
+ "recording_active",
+ "idle_seconds",
+ "expires_in_seconds"
],
"type": "object"
+ }
+ },
+ {
+ "name": "get_session_state",
+ "description": "Deprecated compatibility alias that reads a live legacy session's capture policy. Use get_session for lifecycle state.",
+ "platforms": [
+ "macos",
+ "windows",
+ "linux"
+ ],
+ "capabilities": [
+ "session.capture_scope.read"
+ ],
+ "annotations": {
+ "read_only": true,
+ "destructive": false,
+ "idempotent": true,
+ "open_world": false
+ },
+ "schema_mode": "canonical_runtime",
+ "cursor_semantics": {
+ "action": "system"
+ },
+ "input_schema": {
+ "additionalProperties": true,
+ "properties": {
+ "session": {
+ "description": "Optional public label. When omitted, inspect the caller's attached\nimplicit session.",
+ "type": "string"
+ }
+ },
+ "required": [],
+ "type": "object"
},
"success_output_schema": {
"additionalProperties": true,
@@ -1237,16 +1447,70 @@
"type": "array"
},
"scope": {
- "const": "desktop"
+ "const": "desktop",
+ "description": "Deprecated flat desktop target retained for wire compatibility."
},
"session": {
"description": "Optional session id.",
"type": "string"
+ },
+ "target": {
+ "anyOf": [
+ {
+ "description": "Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.",
+ "oneOf": [
+ {
+ "additionalProperties": true,
+ "properties": {
+ "kind": {
+ "const": "window",
+ "type": "string"
+ },
+ "pid": {
+ "format": "uint32",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "window_id": {
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "kind",
+ "pid",
+ "window_id"
+ ],
+ "type": "object"
+ },
+ {
+ "additionalProperties": true,
+ "properties": {
+ "display_id": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "desktop",
+ "type": "string"
+ }
+ },
+ "required": [
+ "kind",
+ "display_id"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ]
}
},
"required": [
- "keys",
- "scope"
+ "keys"
],
"type": "object"
},
@@ -1536,6 +1800,142 @@
"type": "object"
}
},
+ {
+ "name": "list_sessions",
+ "description": "List content-free lifecycle summaries attached to this authenticated transport lease. It does not enumerate other callers' sessions.",
+ "platforms": [
+ "macos",
+ "windows",
+ "linux"
+ ],
+ "capabilities": [
+ "session.lifecycle.list"
+ ],
+ "annotations": {
+ "read_only": true,
+ "destructive": false,
+ "idempotent": true,
+ "open_world": false
+ },
+ "schema_mode": "canonical_runtime",
+ "cursor_semantics": {
+ "action": "system"
+ },
+ "input_schema": {
+ "additionalProperties": true,
+ "properties": {
+ "cursor": {
+ "description": "Opaque continuation cursor returned by a previous call.",
+ "type": "string"
+ },
+ "limit": {
+ "description": "Maximum number of content-free summaries to return (default 50, max\n100). Ordinary agent transports are scoped to their own lease.",
+ "format": "uint32",
+ "minimum": 0,
+ "type": [
+ "integer",
+ "null"
+ ]
+ }
+ },
+ "required": [],
+ "type": "object"
+ },
+ "success_output_schema": {
+ "additionalProperties": true,
+ "properties": {
+ "next_cursor": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "sessions": {
+ "items": {
+ "properties": {
+ "client_kind": {
+ "enum": [
+ "cli",
+ "direct",
+ "mcp",
+ "python_sdk",
+ "typescript_sdk"
+ ],
+ "type": "string"
+ },
+ "cursor_visible": {
+ "type": "boolean"
+ },
+ "expires_in_seconds": {
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "idle_seconds": {
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "implicit": {
+ "type": "boolean"
+ },
+ "recording_active": {
+ "type": "boolean"
+ },
+ "session": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "state": {
+ "enum": [
+ "active",
+ "ending"
+ ],
+ "type": "string"
+ },
+ "transport": {
+ "enum": [
+ "cli",
+ "daemon",
+ "mcp_stdio",
+ "mcp_http"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "session",
+ "implicit",
+ "state",
+ "client_kind",
+ "transport",
+ "cursor_visible",
+ "recording_active",
+ "idle_seconds",
+ "expires_in_seconds"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "sessions",
+ "next_cursor"
+ ],
+ "type": "object"
+ }
+ },
{
"name": "move_cursor",
"description": "Move the real OS pointer in get_desktop_state coordinates.",
@@ -1562,12 +1962,68 @@
"additionalProperties": false,
"properties": {
"scope": {
- "const": "desktop"
+ "const": "desktop",
+ "description": "Deprecated flat desktop target retained for wire compatibility."
},
"session": {
"description": "Optional session id.",
"type": "string"
},
+ "target": {
+ "anyOf": [
+ {
+ "description": "Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.",
+ "oneOf": [
+ {
+ "additionalProperties": true,
+ "properties": {
+ "kind": {
+ "const": "window",
+ "type": "string"
+ },
+ "pid": {
+ "format": "uint32",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "window_id": {
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "kind",
+ "pid",
+ "window_id"
+ ],
+ "type": "object"
+ },
+ {
+ "additionalProperties": true,
+ "properties": {
+ "display_id": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "desktop",
+ "type": "string"
+ }
+ },
+ "required": [
+ "kind",
+ "display_id"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Preferred per-call target. New callers should set this field."
+ },
"x": {
"type": "number"
},
@@ -1577,8 +2033,7 @@
},
"required": [
"x",
- "y",
- "scope"
+ "y"
],
"type": "object"
},
@@ -1732,16 +2187,70 @@
"type": "array"
},
"scope": {
- "const": "desktop"
+ "const": "desktop",
+ "description": "Deprecated flat desktop target retained for wire compatibility."
},
"session": {
"description": "Optional session id.",
"type": "string"
+ },
+ "target": {
+ "anyOf": [
+ {
+ "description": "Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.",
+ "oneOf": [
+ {
+ "additionalProperties": true,
+ "properties": {
+ "kind": {
+ "const": "window",
+ "type": "string"
+ },
+ "pid": {
+ "format": "uint32",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "window_id": {
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "kind",
+ "pid",
+ "window_id"
+ ],
+ "type": "object"
+ },
+ {
+ "additionalProperties": true,
+ "properties": {
+ "display_id": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "desktop",
+ "type": "string"
+ }
+ },
+ "required": [
+ "kind",
+ "display_id"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ]
}
},
"required": [
- "key",
- "scope"
+ "key"
],
"type": "object"
},
@@ -1907,12 +2416,67 @@
"type": "string"
},
"scope": {
- "const": "desktop"
+ "const": "desktop",
+ "description": "Deprecated flat desktop target retained for wire compatibility."
},
"session": {
"description": "Optional session id.",
"type": "string"
},
+ "target": {
+ "anyOf": [
+ {
+ "description": "Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.",
+ "oneOf": [
+ {
+ "additionalProperties": true,
+ "properties": {
+ "kind": {
+ "const": "window",
+ "type": "string"
+ },
+ "pid": {
+ "format": "uint32",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "window_id": {
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "kind",
+ "pid",
+ "window_id"
+ ],
+ "type": "object"
+ },
+ {
+ "additionalProperties": true,
+ "properties": {
+ "display_id": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "desktop",
+ "type": "string"
+ }
+ },
+ "required": [
+ "kind",
+ "display_id"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"x": {
"type": "number"
},
@@ -1923,8 +2487,7 @@
"required": [
"x",
"y",
- "direction",
- "scope"
+ "direction"
],
"type": "object"
},
@@ -2529,7 +3092,7 @@
},
{
"name": "start_session",
- "description": "Declare a session — a named, color-coded identity for THIS agent run. Pass a stable `session` id and choose capture_scope=auto|window|desktop; the agent cursor, capture policy, per-session config, and recording all key on it, and it follows the run across any apps/windows. The cursor's color is derived from the id, so distinct runs are visually distinct. A cursor is shown only for a declared session — call this (or pass `session` on your first action) to opt in. Idempotent: re-calling with the same id just refreshes its idle-TTL. End it with `end_session` (or let the idle-TTL reclaim it). Concurrent runs/subagents each pass their own `session` to get their own cursor.",
+ "description": "Optionally name and start a lifecycle session for this agent run. When `session` is omitted, create or return the authenticated transport lease's implicit session. Ordinary actions create that implicit session automatically, so this tool is optional. `capture_scope` is deprecated compatibility input; new callers select window or desktop modality per action. Idempotent.",
"platforms": [
"macos",
"windows",
@@ -2553,8 +3116,7 @@
"additionalProperties": true,
"properties": {
"capture_scope": {
- "default": "auto",
- "description": "Per-session perception/action modality. auto starts window-only and requires explicit escalation before desktop tools; escalation permanently switches that session to desktop scope. To recover window scope, call end_session, then start_session with a new session id. window and desktop are strict. Immutable for the live session.",
+ "description": "Deprecated compatibility policy. New callers select window or desktop\nmodality on each action instead of storing it on the session.",
"enum": [
"auto",
"window",
@@ -2587,13 +3149,11 @@
]
},
"session": {
- "description": "Stable session id for this run (e.g. \"research-run-1\").",
+ "description": "Optional stable public label for this run (e.g. \"research-run-1\").\nWhen omitted, the authenticated transport lease's implicit session is\ncreated or returned.",
"type": "string"
}
},
- "required": [
- "session"
- ],
+ "required": [],
"type": "object"
},
"success_output_schema": {
@@ -2694,19 +3254,73 @@
"additionalProperties": false,
"properties": {
"scope": {
- "const": "desktop"
+ "const": "desktop",
+ "description": "Deprecated flat desktop target retained for wire compatibility."
},
"session": {
"description": "Optional session id.",
"type": "string"
},
+ "target": {
+ "anyOf": [
+ {
+ "description": "Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.",
+ "oneOf": [
+ {
+ "additionalProperties": true,
+ "properties": {
+ "kind": {
+ "const": "window",
+ "type": "string"
+ },
+ "pid": {
+ "format": "uint32",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "window_id": {
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "required": [
+ "kind",
+ "pid",
+ "window_id"
+ ],
+ "type": "object"
+ },
+ {
+ "additionalProperties": true,
+ "properties": {
+ "display_id": {
+ "type": "string"
+ },
+ "kind": {
+ "const": "desktop",
+ "type": "string"
+ }
+ },
+ "required": [
+ "kind",
+ "display_id"
+ ],
+ "type": "object"
+ }
+ ]
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"text": {
"type": "string"
}
},
"required": [
- "text",
- "scope"
+ "text"
],
"type": "object"
},
@@ -2974,7 +3588,7 @@
"type": "integer"
},
"session": {
- "description": "Optional session id for capture-scope and authorization continuity.",
+ "description": "Optional public session label for lifecycle continuity. It never selects\ncapture modality or authorization.",
"type": "string"
},
"stable_samples": {
diff --git a/libs/cua-driver/docs/action-icon-catalog.md b/libs/cua-driver/docs/action-icon-catalog.md
index 3d868fff1a..7d381e66e0 100644
--- a/libs/cua-driver/docs/action-icon-catalog.md
+++ b/libs/cua-driver/docs/action-icon-catalog.md
@@ -170,10 +170,12 @@ distinct resolved action IDs.
| Public tool | Resolved action keys |
| -------------------------- | ----------------------------------------------------- |
-| `start_session` | `session.start.{auto\|window\|desktop}` |
-| `escalate_session` | `session.escalate.desktop` |
-| `get_session_state` | `session.inspect` |
+| `start_session` | `session.start.{implicit\|named}` |
+| `get_session` | `session.inspect.one` |
+| `list_sessions` | `session.inspect.list` |
| `end_session` | `session.end` |
+| `escalate_session` | `session.legacy.escalate.desktop` |
+| `get_session_state` | `session.legacy.inspect_capture` |
| `start_recording` | `recording.start.trajectory`, `recording.start.video` |
| `stop_recording` | `recording.stop` |
| `get_recording_state` | `recording.inspect` |
@@ -215,7 +217,7 @@ public tool names.
| 16 | `get_screen_size` | Inspection | All | Screen dimensions |
| 17 | `get_desktop_state` | Inspection | All | Desktop capture |
| 18 | `get_cursor_position` | Inspection | All | Cursor location |
-| 19 | `move_cursor` | Pointer/overlay input | All | Agent-cursor move in window scope; real-pointer move in desktop scope |
+| 19 | `move_cursor` | Pointer/overlay input | All | Agent-cursor or real-pointer move selected by the per-call target |
| 20 | `set_agent_cursor_enabled` | Agent cursor | All | Show/hide cursor |
| 21 | `set_agent_cursor_motion` | Agent cursor | All | Motion configuration |
| 22 | `set_agent_cursor_theme` | Agent cursor | All | Select an installed visual theme |
@@ -241,16 +243,18 @@ public tool names.
| 42 | `get_recording_state` | Recording | All | Recording inspect |
| 43 | `replay_trajectory` | Recording | All | Replay |
| 44 | `install_ffmpeg` | Maintenance | Windows/Linux; no-op when unnecessary | Plan/install dependency |
-| 45 | `start_session` | Session lifecycle | All | Start session plus capture scope |
-| 46 | `escalate_session` | Session lifecycle | All | Escalate to desktop |
-| 47 | `get_session_state` | Session lifecycle | All | Session inspect |
+| 45 | `start_session` | Session lifecycle | All | Optional implicit or named lifecycle start |
+| 46 | `get_session` | Session lifecycle | All | Inspect one visible lifecycle session |
+| 47 | `list_sessions` | Session lifecycle | All | List transport-visible lifecycle sessions |
| 48 | `end_session` | Session lifecycle | All | End session |
-| 49 | `check_for_update` | Maintenance | All | Update check |
-| 50 | `debug_window_info` | Diagnostic | Windows only | Window diagnostic |
-| 51 | `mouse_button_down` | Low-level pointer | Linux only | Hold button |
-| 52 | `mouse_drag` | Low-level pointer | Linux only | Move held pointer |
-| 53 | `mouse_button_up` | Low-level pointer | Linux only | Release button |
-| 54 | `parallel_mouse_drag` | Multi-pointer | Linux only | Concurrent drags |
+| 49 | `escalate_session` | Legacy session compatibility | All | Deprecated capture-scope escalation |
+| 50 | `get_session_state` | Legacy session compatibility | All | Deprecated capture-scope inspect |
+| 51 | `check_for_update` | Maintenance | All | Update check |
+| 52 | `debug_window_info` | Diagnostic | Windows only | Window diagnostic |
+| 53 | `mouse_button_down` | Low-level pointer | Linux only | Hold button |
+| 54 | `mouse_drag` | Low-level pointer | Linux only | Move held pointer |
+| 55 | `mouse_button_up` | Low-level pointer | Linux only | Release button |
+| 56 | `parallel_mouse_drag` | Multi-pointer | Linux only | Concurrent drags |
## Linux low-level pointer action keys
diff --git a/libs/cua-driver/docs/test-matrix.md b/libs/cua-driver/docs/test-matrix.md
index f14bad2839..f406ef8666 100644
--- a/libs/cua-driver/docs/test-matrix.md
+++ b/libs/cua-driver/docs/test-matrix.md
@@ -45,7 +45,7 @@ These run without the repo-local GUI applications:
| --- | --- | --- |
| Core driver logic | `rust/crates/*/src/**` | Protocol values, sessions, schemas, image helpers, input helpers, configuration, telemetry, CLI behavior |
| MCP and CLI boundary | `rust/crates/cua-driver/tests/protocol_*` | Handshake, tool registration, tool calls, media, sessions, and errors |
-| Session capture scope | `session_capture_scope_test.rs` plus core `capture_scope` tests | Per-session isolation, immutable live policy, explicit auto escalation, end/revive race safety, transport-mirror refusal, and retired persistent key |
+| Lifecycle sessions and target migration | Core `session`, `session_tools`, `action_target`, and compatibility `capture_scope` tests plus `session_capture_scope_test.rs` | One implicit session per transport, five-minute idle policy, in-flight and exact-once cleanup, owner-scoped inspection and revival, per-call target validation, and legacy capture-scope compatibility |
| Tool-contract gate | `schema_consistency_test.rs` | Shared tool schema parity and reviewed risk metadata across OS backends |
| Configuration transport | `transport_config_persistence_test.rs` | CLI and MCP configuration persistence |
| Token and protocol surfaces | `protocol_element_token_test.rs`, related tests | JSON-RPC-visible contract behavior |
@@ -109,7 +109,7 @@ Windows native harnesses are repo-local applications built from source:
| WPF | `harness_wpf_test.rs` | UIA controls, text, keys, pointer actions, scroll, drag, popups, menus, modal windows |
| WinUI3 | `harness_winui3_test.rs` | XAML controls, text, checkbox/radio, slider, combo, popup |
| WebView2 | `harness_web_test.rs` | Window discovery, CDP page access, JavaScript, DOM click path |
-| Desktop scope | `desktop_scope_windows_test.rs` | Concurrent strict window/desktop sessions, full-display capture, screen-absolute click/scroll, and strict rejection |
+| Desktop target | `desktop_scope_windows_test.rs` | Per-call window/desktop modality, full-display capture, screen-absolute click/scroll, and strict rejection |
| Desktop invariants | Testkit `DesktopObserver` plus typed launch/capture/cursor owners | Cross-cutting focus, z-order, minimized-launch, screenshot, cursor, and desktop checks |
Native controls use AX/UIA state as their oracle. Pointer actions also use PX
@@ -123,7 +123,7 @@ background delivery and attach desktop-side-effect oracles.
| AppKit | `harness_appkit_test.rs` | AX tree/capture, AX value/text, AX scroll, PX clicks, and foreground slider drag across the proven delivery modes; background drag is an exact refusal |
| SwiftUI | `harness_swiftui_test.rs` | AX tree/capture, background click/value, and foreground popover-trigger state |
| WKWebView | `cross_platform_behavior_test.rs` | Dedicated native host running the full 40-cell shared web catalog |
-| Desktop scope | `desktop_scope_macos_test.rs` | Concurrent strict window/desktop sessions, screen-absolute action delivery, and strict rejection |
+| Desktop target | `desktop_scope_macos_test.rs` | Per-call window/desktop modality, screen-absolute action delivery, and strict rejection |
| Installed-app launch/focus | `installed_app_launch_macos_test.rs` | Real Calculator/TextEdit launch and focus behavior in the canonical logged-in lane |
| Installed-app text | `installed_app_textedit_macos_test.rs` | Real TextEdit AX background write and verification in the canonical logged-in lane |
@@ -143,7 +143,7 @@ transient-panel AX discovery gap.
| Electron | `cross_platform_behavior_test.rs` | X11 and hosted Sway | Shared web action matrix |
| Tauri | `cross_platform_behavior_test.rs` | X11 and hosted Sway | Shared web action matrix |
| GTK3 | `harness_gtk3_test.rs` | X11/AT-SPI and Wayland/AT-SPI where configured | Native GTK controls and input |
-| Desktop scope | `desktop_scope_linux_test.rs` | X11/Wayland | Concurrent strict window/desktop sessions, screen-absolute action delivery, and strict rejection |
+| Desktop target | `desktop_scope_linux_test.rs` | X11/Wayland | Per-call window/desktop modality, screen-absolute action delivery, and strict rejection |
Nix provides the Linux build and desktop environment. X11 and Wayland are
separate matrix dimensions because their capture and input contracts differ.
diff --git a/libs/cua-driver/python/README.md b/libs/cua-driver/python/README.md
index 643bbf6b6e..23e098c893 100644
--- a/libs/cua-driver/python/README.md
+++ b/libs/cua-driver/python/README.md
@@ -38,7 +38,6 @@ in the importing process and does not require the executable or daemon.
import asyncio
from cua_driver import (
- CaptureScope,
CuaDriver,
CursorReducedMotion,
EndSessionInput,
@@ -50,7 +49,7 @@ from cua_driver import (
async def main() -> None:
driver = CuaDriver.create()
await driver.start_session(
- StartSessionInput(session="demo", capture_scope=CaptureScope.DESKTOP)
+ StartSessionInput(session="demo", capture_scope=None, cursor_theme=None)
)
try:
await driver.set_agent_cursor_theme(
@@ -77,7 +76,13 @@ text, images, verification/error metadata, and `structured_json` / `raw_json`
for platform-extensible results. Session lifecycle calls return dedicated
generated records.
-The agent cursor is session-owned. Its default theme and custom dotLottie
+`start_session` is optional for ordinary calls. The runtime creates one
+implicit session for this SDK transport and reuses it until shutdown, explicit
+end, or five minutes of inactivity. Use a named session when application code
+needs to configure or inspect that run explicitly.
+
+The agent cursor is session-owned and initializes on the first cursor-bearing
+action, including `move_cursor`. 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
diff --git a/libs/cua-driver/python/src/cua_driver/_native.py b/libs/cua-driver/python/src/cua_driver/_native.py
index 54f92889ef..84027c7c99 100644
--- a/libs/cua-driver/python/src/cua_driver/_native.py
+++ b/libs/cua-driver/python/src/cua_driver/_native.py
@@ -540,6 +540,8 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_get_screen_size() != 55616:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_get_session() != 17834:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_get_session_state() != 49966:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_hotkey() != 53333:
@@ -548,6 +550,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_cuadriver_is_available() != 42961:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_list_host_sessions_json() != 13193:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_list_sessions() != 40131:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json() != 33039:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_metadata() != 55026:
@@ -602,12 +608,16 @@ 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_get_screen_size() != 9763:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session() != 54666:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session_state() != 55370:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_hotkey() != 12820:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_invoke_menu() != 2742:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_list_sessions() != 32840:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor() != 35768:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_press_key() != 36768:
@@ -1165,6 +1175,11 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_get_screen_size.argtypes =
cua_driver._native_contract._UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_get_screen_size.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_get_session.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_get_session.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_get_session_state.argtypes = (
ctypes.c_uint64,
cua_driver._native_contract._UniffiRustBuffer,
@@ -1185,6 +1200,15 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_is_available.argtypes = (
ctypes.POINTER(_UniffiRustCallStatus),
)
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_is_available.restype = ctypes.c_int8
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_list_host_sessions_json.argtypes = (
+ ctypes.c_uint64,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_list_host_sessions_json.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_list_sessions.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_list_sessions.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_list_tools_json.argtypes = (
ctypes.c_uint64,
)
@@ -1318,6 +1342,11 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_screen_size.argt
cua_driver._native_contract._UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_screen_size.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_session.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_session.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_session_state.argtypes = (
ctypes.c_uint64,
cua_driver._native_contract._UniffiRustBuffer,
@@ -1333,6 +1362,11 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_invoke_menu.argtypes
cua_driver._native_contract._UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_invoke_menu.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_list_sessions.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_list_sessions.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_move_cursor.argtypes = (
ctypes.c_uint64,
cua_driver._native_contract._UniffiRustBuffer,
@@ -1525,6 +1559,9 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_get_desktop_state.res
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_get_screen_size.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_get_screen_size.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_get_session.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_get_session.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_get_session_state.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_get_session_state.restype = ctypes.c_uint16
@@ -1537,6 +1574,12 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_invoke_menu.restype =
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_is_available.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_is_available.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_list_host_sessions_json.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_list_host_sessions_json.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_list_sessions.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_list_sessions.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json.restype = ctypes.c_uint16
@@ -1618,6 +1661,9 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_desktop_st
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_screen_size.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_screen_size.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session_state.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session_state.restype = ctypes.c_uint16
@@ -1627,6 +1673,9 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_hotkey.restype
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_invoke_menu.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_invoke_menu.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_list_sessions.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_list_sessions.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor.restype = ctypes.c_uint16
@@ -4152,6 +4201,14 @@ class _UniffiFfiConverterTypeSdkClientKind(_UniffiConverterRustBuffer):
+
+
+
+
+
+
+
+
@@ -4192,6 +4249,8 @@ class CuaDriverProtocol(typing.Protocol):
raise NotImplementedError
async def get_screen_size(self, input: cua_driver._native_contract.GetScreenSizeInput) -> ToolResult:
raise NotImplementedError
+ async def get_session(self, input: cua_driver._native_contract.GetSessionInput) -> cua_driver._native_contract.SessionOutput:
+ raise NotImplementedError
async def get_session_state(self, input: cua_driver._native_contract.GetSessionStateInput) -> cua_driver._native_contract.SessionStateOutput:
raise NotImplementedError
async def hotkey(self, input: cua_driver._native_contract.HotkeyInput) -> ToolResult:
@@ -4200,6 +4259,15 @@ class CuaDriverProtocol(typing.Protocol):
raise NotImplementedError
def is_available(self, ) -> bool:
raise NotImplementedError
+ async def list_host_sessions_json(self, ) -> str:
+ """
+ Content-free lifecycle summaries for the trusted host's runtime or
+ host-lease namespace. This is deliberately separate from the
+ agent-facing `list_sessions` tool, whose view is transport scoped.
+"""
+ raise NotImplementedError
+ async def list_sessions(self, input: cua_driver._native_contract.ListSessionsInput) -> cua_driver._native_contract.ListSessionsOutput:
+ raise NotImplementedError
async def list_tools_json(self, ) -> str:
"""
Canonical tool inventory for MCP and other protocol adapters.
@@ -4788,6 +4856,23 @@ class CuaDriver(CuaDriverProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def get_session(self, input: cua_driver._native_contract.GetSessionInput) -> cua_driver._native_contract.SessionOutput:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeGetSessionInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeGetSessionInput.lower(input),
+ )
+ _uniffi_lift_return = cua_driver._native_contract._UniffiFfiConverterTypeSessionOutput.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_get_session(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def get_session_state(self, input: cua_driver._native_contract.GetSessionStateInput) -> cua_driver._native_contract.SessionStateOutput:
cua_driver._native_contract._UniffiFfiConverterTypeGetSessionStateInput.check_lower(input)
@@ -4851,6 +4936,42 @@ class CuaDriver(CuaDriverProtocol):
*_uniffi_lowered_args,
)
return _uniffi_lift_return(_uniffi_ffi_result)
+ async def list_host_sessions_json(self, ) -> str:
+ """
+ Content-free lifecycle summaries for the trusted host's runtime or
+ host-lease namespace. This is deliberately separate from the
+ agent-facing `list_sessions` tool, whose view is transport scoped.
+"""
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterString.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_list_host_sessions_json(*_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 list_sessions(self, input: cua_driver._native_contract.ListSessionsInput) -> cua_driver._native_contract.ListSessionsOutput:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeListSessionsInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeListSessionsInput.lower(input),
+ )
+ _uniffi_lift_return = cua_driver._native_contract._UniffiFfiConverterTypeListSessionsOutput.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_list_sessions(*_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 list_tools_json(self, ) -> str:
"""
Canonical tool inventory for MCP and other protocol adapters.
@@ -5161,12 +5282,16 @@ class CuaDriverSessionProtocol(typing.Protocol):
raise NotImplementedError
async def get_screen_size(self, input: cua_driver._native_contract.GetScreenSizeInput) -> ToolResult:
raise NotImplementedError
+ async def get_session(self, input: cua_driver._native_contract.GetSessionInput) -> cua_driver._native_contract.SessionOutput:
+ raise NotImplementedError
async def get_session_state(self, input: cua_driver._native_contract.GetSessionStateInput) -> cua_driver._native_contract.SessionStateOutput:
raise NotImplementedError
async def hotkey(self, input: cua_driver._native_contract.HotkeyInput) -> ToolResult:
raise NotImplementedError
async def invoke_menu(self, input: cua_driver._native_contract.InvokeMenuInput) -> ToolResult:
raise NotImplementedError
+ async def list_sessions(self, input: cua_driver._native_contract.ListSessionsInput) -> cua_driver._native_contract.ListSessionsOutput:
+ raise NotImplementedError
async def move_cursor(self, input: cua_driver._native_contract.MoveCursorInput) -> ToolResult:
raise NotImplementedError
async def press_key(self, input: cua_driver._native_contract.PressKeyInput) -> ToolResult:
@@ -5420,6 +5545,23 @@ class CuaDriverSession(CuaDriverSessionProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def get_session(self, input: cua_driver._native_contract.GetSessionInput) -> cua_driver._native_contract.SessionOutput:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeGetSessionInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeGetSessionInput.lower(input),
+ )
+ _uniffi_lift_return = cua_driver._native_contract._UniffiFfiConverterTypeSessionOutput.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_get_session(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def get_session_state(self, input: cua_driver._native_contract.GetSessionStateInput) -> cua_driver._native_contract.SessionStateOutput:
cua_driver._native_contract._UniffiFfiConverterTypeGetSessionStateInput.check_lower(input)
@@ -5471,6 +5613,23 @@ class CuaDriverSession(CuaDriverSessionProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def list_sessions(self, input: cua_driver._native_contract.ListSessionsInput) -> cua_driver._native_contract.ListSessionsOutput:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeListSessionsInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeListSessionsInput.lower(input),
+ )
+ _uniffi_lift_return = cua_driver._native_contract._UniffiFfiConverterTypeListSessionsOutput.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_list_sessions(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
async def move_cursor(self, input: cua_driver._native_contract.MoveCursorInput) -> ToolResult:
cua_driver._native_contract._UniffiFfiConverterTypeMoveCursorInput.check_lower(input)
diff --git a/libs/cua-driver/python/src/cua_driver/_native_contract.py b/libs/cua-driver/python/src/cua_driver/_native_contract.py
index 2a2c4c3d0f..61a69eb96c 100644
--- a/libs/cua-driver/python/src/cua_driver/_native_contract.py
+++ b/libs/cua-driver/python/src/cua_driver/_native_contract.py
@@ -1486,37 +1486,18 @@ class _UniffiFfiConverterTypeBoundsExpectation(_UniffiConverterRustBuffer):
_UniffiFfiConverterFloat64.write(value.height, buf)
_UniffiFfiConverterOptionalFloat64.write(value.tolerance_px, buf)
+class _UniffiFfiConverterUInt64(_UniffiConverterPrimitiveInt):
+ CLASS_NAME = "u64"
+ VALUE_MIN = 0
+ VALUE_MAX = 2**64
-
-
-
-
-class DesktopScope(enum.Enum):
-
- DESKTOP = 0
-
-
-
-class _UniffiFfiConverterTypeDesktopScope(_UniffiConverterRustBuffer):
@staticmethod
def read(buf):
- variant = buf.read_i32()
- if variant == 1:
- return DesktopScope.DESKTOP
- raise InternalError("Raw enum value doesn't match any cases")
-
- @staticmethod
- def check_lower(value):
- if value == DesktopScope.DESKTOP:
- return
- raise ValueError(value)
+ return buf.read_u64()
@staticmethod
def write(value, buf):
- if value == DesktopScope.DESKTOP:
- buf.write_i32(1)
-
-
+ buf.write_u64(value)
class _UniffiFfiConverterString:
@staticmethod
@@ -1550,6 +1531,219 @@ class _UniffiFfiConverterString:
builder.write(value.encode("utf-8"))
return builder.finalize()
+
+
+
+
+
+class ActionTarget:
+ """
+ Exact capture/input target selected independently for each action.
+
+ `display_id="primary"` is the portable desktop target in this release.
+ Platforms that cannot address another display reject it explicitly rather
+ than silently changing coordinate spaces.
+"""
+ def __init__(self):
+ raise RuntimeError("ActionTarget cannot be instantiated directly")
+
+ # Each enum variant is a nested class of the enum itself.
+ @dataclass
+ class WINDOW:
+
+ def __init__(self, pid:int, window_id:int):
+ self.pid = pid
+
+
+ self.window_id = window_id
+
+
+ pass
+
+
+
+
+
+ def __str__(self):
+ return "ActionTarget.WINDOW(pid={}, window_id={})".format(self.pid, self.window_id)
+ def __eq__(self, other):
+ if not isinstance(other, ActionTarget):
+ return NotImplemented
+ if not other.is_WINDOW():
+ return False
+ if self.pid != other.pid:
+ return False
+ if self.window_id != other.window_id:
+ return False
+ return True
+
+ @dataclass
+ class DESKTOP:
+
+ def __init__(self, display_id:str):
+ self.display_id = display_id
+
+
+ pass
+
+
+
+
+
+ def __str__(self):
+ return "ActionTarget.DESKTOP(display_id={})".format(self.display_id)
+ def __eq__(self, other):
+ if not isinstance(other, ActionTarget):
+ return NotImplemented
+ if not other.is_DESKTOP():
+ return False
+ if self.display_id != other.display_id:
+ return False
+ return True
+
+
+
+ # For each variant, we have `is_NAME` and `is_name` methods for easily checking
+ # whether an instance is that variant.
+ def is_WINDOW(self) -> bool:
+ return isinstance(self, ActionTarget.WINDOW)
+ def is_window(self) -> bool:
+ return isinstance(self, ActionTarget.WINDOW)
+ def is_DESKTOP(self) -> bool:
+ return isinstance(self, ActionTarget.DESKTOP)
+ def is_desktop(self) -> bool:
+ return isinstance(self, ActionTarget.DESKTOP)
+
+
+# Now, a little trick - we make each nested variant class be a subclass of the main
+# enum class, so that method calls and instance checks etc will work intuitively.
+# We might be able to do this a little more neatly with a metaclass, but this'll do.
+ActionTarget.WINDOW = type("ActionTarget.WINDOW", (ActionTarget.WINDOW, ActionTarget,), {}) # type: ignore
+ActionTarget.DESKTOP = type("ActionTarget.DESKTOP", (ActionTarget.DESKTOP, ActionTarget,), {}) # type: ignore
+
+
+
+
+class _UniffiFfiConverterTypeActionTarget(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return ActionTarget.WINDOW(
+ _UniffiFfiConverterUInt32.read(buf),
+ _UniffiFfiConverterUInt64.read(buf),
+ )
+ if variant == 2:
+ return ActionTarget.DESKTOP(
+ _UniffiFfiConverterString.read(buf),
+ )
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if value.is_WINDOW():
+ _UniffiFfiConverterUInt32.check_lower(value.pid)
+ _UniffiFfiConverterUInt64.check_lower(value.window_id)
+ return
+ if value.is_DESKTOP():
+ _UniffiFfiConverterString.check_lower(value.display_id)
+ return
+ raise ValueError(value)
+
+ @staticmethod
+ def write(value, buf):
+ if value.is_WINDOW():
+ buf.write_i32(1)
+ _UniffiFfiConverterUInt32.write(value.pid, buf)
+ _UniffiFfiConverterUInt64.write(value.window_id, buf)
+ if value.is_DESKTOP():
+ buf.write_i32(2)
+ _UniffiFfiConverterString.write(value.display_id, buf)
+
+
+
+class _UniffiFfiConverterOptionalTypeActionTarget(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeActionTarget.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeActionTarget.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeActionTarget.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+
+
+
+
+
+class DesktopScope(enum.Enum):
+
+ DESKTOP = 0
+
+
+
+class _UniffiFfiConverterTypeDesktopScope(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return DesktopScope.DESKTOP
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if value == DesktopScope.DESKTOP:
+ return
+ raise ValueError(value)
+
+ @staticmethod
+ def write(value, buf):
+ if value == DesktopScope.DESKTOP:
+ buf.write_i32(1)
+
+
+
+class _UniffiFfiConverterOptionalTypeDesktopScope(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeDesktopScope.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeDesktopScope.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeDesktopScope.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
class _UniffiFfiConverterOptionalString(_UniffiConverterRustBuffer):
@classmethod
def check_lower(cls, value):
@@ -1650,9 +1844,10 @@ class _UniffiFfiConverterOptionalTypeClickButton(_UniffiConverterRustBuffer):
@dataclass
class ClickInput:
- def __init__(self, *, x:float, y:float, scope:DesktopScope, session:typing.Optional[str], button:typing.Optional[ClickButton], count:typing.Optional[int]):
+ def __init__(self, *, x:float, y:float, target:typing.Optional[ActionTarget], scope:typing.Optional[DesktopScope], session:typing.Optional[str], button:typing.Optional[ClickButton], count:typing.Optional[int]):
self.x = x
self.y = y
+ self.target = target
self.scope = scope
self.session = session
self.button = button
@@ -1662,12 +1857,14 @@ class ClickInput:
def __str__(self):
- return "ClickInput(x={}, y={}, scope={}, session={}, button={}, count={})".format(self.x, self.y, self.scope, self.session, self.button, self.count)
+ return "ClickInput(x={}, y={}, target={}, scope={}, session={}, button={}, count={})".format(self.x, self.y, self.target, self.scope, self.session, self.button, self.count)
def __eq__(self, other):
if self.x != other.x:
return False
if self.y != other.y:
return False
+ if self.target != other.target:
+ return False
if self.scope != other.scope:
return False
if self.session != other.session:
@@ -1684,7 +1881,8 @@ class _UniffiFfiConverterTypeClickInput(_UniffiConverterRustBuffer):
return ClickInput(
x=_UniffiFfiConverterFloat64.read(buf),
y=_UniffiFfiConverterFloat64.read(buf),
- scope=_UniffiFfiConverterTypeDesktopScope.read(buf),
+ target=_UniffiFfiConverterOptionalTypeActionTarget.read(buf),
+ scope=_UniffiFfiConverterOptionalTypeDesktopScope.read(buf),
session=_UniffiFfiConverterOptionalString.read(buf),
button=_UniffiFfiConverterOptionalTypeClickButton.read(buf),
count=_UniffiFfiConverterOptionalUInt32.read(buf),
@@ -1694,7 +1892,8 @@ class _UniffiFfiConverterTypeClickInput(_UniffiConverterRustBuffer):
def check_lower(value):
_UniffiFfiConverterFloat64.check_lower(value.x)
_UniffiFfiConverterFloat64.check_lower(value.y)
- _UniffiFfiConverterTypeDesktopScope.check_lower(value.scope)
+ _UniffiFfiConverterOptionalTypeActionTarget.check_lower(value.target)
+ _UniffiFfiConverterOptionalTypeDesktopScope.check_lower(value.scope)
_UniffiFfiConverterOptionalString.check_lower(value.session)
_UniffiFfiConverterOptionalTypeClickButton.check_lower(value.button)
_UniffiFfiConverterOptionalUInt32.check_lower(value.count)
@@ -1703,7 +1902,8 @@ class _UniffiFfiConverterTypeClickInput(_UniffiConverterRustBuffer):
def write(value, buf):
_UniffiFfiConverterFloat64.write(value.x, buf)
_UniffiFfiConverterFloat64.write(value.y, buf)
- _UniffiFfiConverterTypeDesktopScope.write(value.scope, buf)
+ _UniffiFfiConverterOptionalTypeActionTarget.write(value.target, buf)
+ _UniffiFfiConverterOptionalTypeDesktopScope.write(value.scope, buf)
_UniffiFfiConverterOptionalString.write(value.session, buf)
_UniffiFfiConverterOptionalTypeClickButton.write(value.button, buf)
_UniffiFfiConverterOptionalUInt32.write(value.count, buf)
@@ -2316,19 +2516,6 @@ class _UniffiFfiConverterTypeCursorAction(_UniffiConverterRustBuffer):
-class _UniffiFfiConverterUInt64(_UniffiConverterPrimitiveInt):
- CLASS_NAME = "u64"
- VALUE_MIN = 0
- VALUE_MAX = 2**64
-
- @staticmethod
- def read(buf):
- return buf.read_u64()
-
- @staticmethod
- def write(value, buf):
- buf.write_u64(value)
-
@dataclass
class CursorVisualOutput:
def __init__(self, *, requested_action:CursorAction, resolved_action:CursorAction, modifiers:typing.List[str], phase:str, frame:int, preempted_count:int):
@@ -2441,11 +2628,12 @@ class _UniffiFfiConverterOptionalSequenceString(_UniffiConverterRustBuffer):
@dataclass
class DragInput:
- def __init__(self, *, from_x:float, from_y:float, to_x:float, to_y:float, scope:DesktopScope, session:typing.Optional[str], duration_ms:typing.Optional[int], steps:typing.Optional[int], button:typing.Optional[ClickButton], modifier:typing.Optional[typing.List[str]]):
+ def __init__(self, *, from_x:float, from_y:float, to_x:float, to_y:float, target:typing.Optional[ActionTarget], scope:typing.Optional[DesktopScope], session:typing.Optional[str], duration_ms:typing.Optional[int], steps:typing.Optional[int], button:typing.Optional[ClickButton], modifier:typing.Optional[typing.List[str]]):
self.from_x = from_x
self.from_y = from_y
self.to_x = to_x
self.to_y = to_y
+ self.target = target
self.scope = scope
self.session = session
self.duration_ms = duration_ms
@@ -2457,7 +2645,7 @@ class DragInput:
def __str__(self):
- return "DragInput(from_x={}, from_y={}, to_x={}, to_y={}, scope={}, session={}, duration_ms={}, steps={}, button={}, modifier={})".format(self.from_x, self.from_y, self.to_x, self.to_y, self.scope, self.session, self.duration_ms, self.steps, self.button, self.modifier)
+ return "DragInput(from_x={}, from_y={}, to_x={}, to_y={}, target={}, scope={}, session={}, duration_ms={}, steps={}, button={}, modifier={})".format(self.from_x, self.from_y, self.to_x, self.to_y, self.target, self.scope, self.session, self.duration_ms, self.steps, self.button, self.modifier)
def __eq__(self, other):
if self.from_x != other.from_x:
return False
@@ -2467,6 +2655,8 @@ class DragInput:
return False
if self.to_y != other.to_y:
return False
+ if self.target != other.target:
+ return False
if self.scope != other.scope:
return False
if self.session != other.session:
@@ -2489,7 +2679,8 @@ class _UniffiFfiConverterTypeDragInput(_UniffiConverterRustBuffer):
from_y=_UniffiFfiConverterFloat64.read(buf),
to_x=_UniffiFfiConverterFloat64.read(buf),
to_y=_UniffiFfiConverterFloat64.read(buf),
- scope=_UniffiFfiConverterTypeDesktopScope.read(buf),
+ target=_UniffiFfiConverterOptionalTypeActionTarget.read(buf),
+ scope=_UniffiFfiConverterOptionalTypeDesktopScope.read(buf),
session=_UniffiFfiConverterOptionalString.read(buf),
duration_ms=_UniffiFfiConverterOptionalUInt64.read(buf),
steps=_UniffiFfiConverterOptionalUInt64.read(buf),
@@ -2503,7 +2694,8 @@ class _UniffiFfiConverterTypeDragInput(_UniffiConverterRustBuffer):
_UniffiFfiConverterFloat64.check_lower(value.from_y)
_UniffiFfiConverterFloat64.check_lower(value.to_x)
_UniffiFfiConverterFloat64.check_lower(value.to_y)
- _UniffiFfiConverterTypeDesktopScope.check_lower(value.scope)
+ _UniffiFfiConverterOptionalTypeActionTarget.check_lower(value.target)
+ _UniffiFfiConverterOptionalTypeDesktopScope.check_lower(value.scope)
_UniffiFfiConverterOptionalString.check_lower(value.session)
_UniffiFfiConverterOptionalUInt64.check_lower(value.duration_ms)
_UniffiFfiConverterOptionalUInt64.check_lower(value.steps)
@@ -2516,7 +2708,8 @@ class _UniffiFfiConverterTypeDragInput(_UniffiConverterRustBuffer):
_UniffiFfiConverterFloat64.write(value.from_y, buf)
_UniffiFfiConverterFloat64.write(value.to_x, buf)
_UniffiFfiConverterFloat64.write(value.to_y, buf)
- _UniffiFfiConverterTypeDesktopScope.write(value.scope, buf)
+ _UniffiFfiConverterOptionalTypeActionTarget.write(value.target, buf)
+ _UniffiFfiConverterOptionalTypeDesktopScope.write(value.scope, buf)
_UniffiFfiConverterOptionalString.write(value.session, buf)
_UniffiFfiConverterOptionalUInt64.write(value.duration_ms, buf)
_UniffiFfiConverterOptionalUInt64.write(value.steps, buf)
@@ -2640,7 +2833,7 @@ class _UniffiFfiConverterTypeElementPredicate(_UniffiConverterRustBuffer):
@dataclass
class EndSessionInput:
- def __init__(self, *, session:str):
+ def __init__(self, *, session:typing.Optional[str]):
self.session = session
@@ -2657,16 +2850,16 @@ class _UniffiFfiConverterTypeEndSessionInput(_UniffiConverterRustBuffer):
@staticmethod
def read(buf):
return EndSessionInput(
- session=_UniffiFfiConverterString.read(buf),
+ session=_UniffiFfiConverterOptionalString.read(buf),
)
@staticmethod
def check_lower(value):
- _UniffiFfiConverterString.check_lower(value.session)
+ _UniffiFfiConverterOptionalString.check_lower(value.session)
@staticmethod
def write(value, buf):
- _UniffiFfiConverterString.write(value.session, buf)
+ _UniffiFfiConverterOptionalString.write(value.session, buf)
@dataclass
class EndSessionOutput:
@@ -3024,9 +3217,39 @@ class _UniffiFfiConverterTypeGetScreenSizeInput(_UniffiConverterRustBuffer):
def write(value, buf):
_UniffiFfiConverterOptionalString.write(value.session, buf)
+@dataclass
+class GetSessionInput:
+ def __init__(self, *, session:typing.Optional[str]):
+ self.session = session
+
+
+
+
+ def __str__(self):
+ return "GetSessionInput(session={})".format(self.session)
+ def __eq__(self, other):
+ if self.session != other.session:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeGetSessionInput(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return GetSessionInput(
+ session=_UniffiFfiConverterOptionalString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalString.check_lower(value.session)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalString.write(value.session, buf)
+
@dataclass
class GetSessionStateInput:
- def __init__(self, *, session:str):
+ def __init__(self, *, session:typing.Optional[str]):
self.session = session
@@ -3043,21 +3266,22 @@ class _UniffiFfiConverterTypeGetSessionStateInput(_UniffiConverterRustBuffer):
@staticmethod
def read(buf):
return GetSessionStateInput(
- session=_UniffiFfiConverterString.read(buf),
+ session=_UniffiFfiConverterOptionalString.read(buf),
)
@staticmethod
def check_lower(value):
- _UniffiFfiConverterString.check_lower(value.session)
+ _UniffiFfiConverterOptionalString.check_lower(value.session)
@staticmethod
def write(value, buf):
- _UniffiFfiConverterString.write(value.session, buf)
+ _UniffiFfiConverterOptionalString.write(value.session, buf)
@dataclass
class HotkeyInput:
- def __init__(self, *, keys:typing.List[str], scope:DesktopScope, session:typing.Optional[str]):
+ def __init__(self, *, keys:typing.List[str], target:typing.Optional[ActionTarget], scope:typing.Optional[DesktopScope], session:typing.Optional[str]):
self.keys = keys
+ self.target = target
self.scope = scope
self.session = session
@@ -3065,10 +3289,12 @@ class HotkeyInput:
def __str__(self):
- return "HotkeyInput(keys={}, scope={}, session={})".format(self.keys, self.scope, self.session)
+ return "HotkeyInput(keys={}, target={}, scope={}, session={})".format(self.keys, self.target, self.scope, self.session)
def __eq__(self, other):
if self.keys != other.keys:
return False
+ if self.target != other.target:
+ return False
if self.scope != other.scope:
return False
if self.session != other.session:
@@ -3080,20 +3306,23 @@ class _UniffiFfiConverterTypeHotkeyInput(_UniffiConverterRustBuffer):
def read(buf):
return HotkeyInput(
keys=_UniffiFfiConverterSequenceString.read(buf),
- scope=_UniffiFfiConverterTypeDesktopScope.read(buf),
+ target=_UniffiFfiConverterOptionalTypeActionTarget.read(buf),
+ scope=_UniffiFfiConverterOptionalTypeDesktopScope.read(buf),
session=_UniffiFfiConverterOptionalString.read(buf),
)
@staticmethod
def check_lower(value):
_UniffiFfiConverterSequenceString.check_lower(value.keys)
- _UniffiFfiConverterTypeDesktopScope.check_lower(value.scope)
+ _UniffiFfiConverterOptionalTypeActionTarget.check_lower(value.target)
+ _UniffiFfiConverterOptionalTypeDesktopScope.check_lower(value.scope)
_UniffiFfiConverterOptionalString.check_lower(value.session)
@staticmethod
def write(value, buf):
_UniffiFfiConverterSequenceString.write(value.keys, buf)
- _UniffiFfiConverterTypeDesktopScope.write(value.scope, buf)
+ _UniffiFfiConverterOptionalTypeActionTarget.write(value.target, buf)
+ _UniffiFfiConverterOptionalTypeDesktopScope.write(value.scope, buf)
_UniffiFfiConverterOptionalString.write(value.session, buf)
@dataclass
@@ -3149,11 +3378,348 @@ class _UniffiFfiConverterTypeInvokeMenuInput(_UniffiConverterRustBuffer):
_UniffiFfiConverterSequenceString.write(value.path, buf)
_UniffiFfiConverterOptionalString.write(value.session, buf)
+@dataclass
+class ListSessionsInput:
+ def __init__(self, *, limit:typing.Optional[int], cursor:typing.Optional[str]):
+ self.limit = limit
+ self.cursor = cursor
+
+
+
+
+ def __str__(self):
+ return "ListSessionsInput(limit={}, cursor={})".format(self.limit, self.cursor)
+ def __eq__(self, other):
+ if self.limit != other.limit:
+ return False
+ if self.cursor != other.cursor:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeListSessionsInput(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return ListSessionsInput(
+ limit=_UniffiFfiConverterOptionalUInt32.read(buf),
+ cursor=_UniffiFfiConverterOptionalString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalUInt32.check_lower(value.limit)
+ _UniffiFfiConverterOptionalString.check_lower(value.cursor)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalUInt32.write(value.limit, buf)
+ _UniffiFfiConverterOptionalString.write(value.cursor, buf)
+
+
+
+
+
+
+class SessionLifecycleState(enum.Enum):
+
+ ACTIVE = 0
+
+ ENDING = 1
+
+
+
+class _UniffiFfiConverterTypeSessionLifecycleState(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return SessionLifecycleState.ACTIVE
+ if variant == 2:
+ return SessionLifecycleState.ENDING
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if value == SessionLifecycleState.ACTIVE:
+ return
+ if value == SessionLifecycleState.ENDING:
+ return
+ raise ValueError(value)
+
+ @staticmethod
+ def write(value, buf):
+ if value == SessionLifecycleState.ACTIVE:
+ buf.write_i32(1)
+ if value == SessionLifecycleState.ENDING:
+ buf.write_i32(2)
+
+
+
+
+
+
+
+
+class SessionClientKindOutput(enum.Enum):
+
+ CLI = 0
+
+ DIRECT = 1
+
+ MCP = 2
+
+ PYTHON_SDK = 3
+
+ TYPESCRIPT_SDK = 4
+
+
+
+class _UniffiFfiConverterTypeSessionClientKindOutput(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return SessionClientKindOutput.CLI
+ if variant == 2:
+ return SessionClientKindOutput.DIRECT
+ if variant == 3:
+ return SessionClientKindOutput.MCP
+ if variant == 4:
+ return SessionClientKindOutput.PYTHON_SDK
+ if variant == 5:
+ return SessionClientKindOutput.TYPESCRIPT_SDK
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if value == SessionClientKindOutput.CLI:
+ return
+ if value == SessionClientKindOutput.DIRECT:
+ return
+ if value == SessionClientKindOutput.MCP:
+ return
+ if value == SessionClientKindOutput.PYTHON_SDK:
+ return
+ if value == SessionClientKindOutput.TYPESCRIPT_SDK:
+ return
+ raise ValueError(value)
+
+ @staticmethod
+ def write(value, buf):
+ if value == SessionClientKindOutput.CLI:
+ buf.write_i32(1)
+ if value == SessionClientKindOutput.DIRECT:
+ buf.write_i32(2)
+ if value == SessionClientKindOutput.MCP:
+ buf.write_i32(3)
+ if value == SessionClientKindOutput.PYTHON_SDK:
+ buf.write_i32(4)
+ if value == SessionClientKindOutput.TYPESCRIPT_SDK:
+ buf.write_i32(5)
+
+
+
+
+
+
+
+
+class SessionTransportOutput(enum.Enum):
+
+ CLI = 0
+
+ DAEMON = 1
+
+ MCP_STDIO = 2
+
+ MCP_HTTP = 3
+
+
+
+class _UniffiFfiConverterTypeSessionTransportOutput(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return SessionTransportOutput.CLI
+ if variant == 2:
+ return SessionTransportOutput.DAEMON
+ if variant == 3:
+ return SessionTransportOutput.MCP_STDIO
+ if variant == 4:
+ return SessionTransportOutput.MCP_HTTP
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if value == SessionTransportOutput.CLI:
+ return
+ if value == SessionTransportOutput.DAEMON:
+ return
+ if value == SessionTransportOutput.MCP_STDIO:
+ return
+ if value == SessionTransportOutput.MCP_HTTP:
+ return
+ raise ValueError(value)
+
+ @staticmethod
+ def write(value, buf):
+ if value == SessionTransportOutput.CLI:
+ buf.write_i32(1)
+ if value == SessionTransportOutput.DAEMON:
+ buf.write_i32(2)
+ if value == SessionTransportOutput.MCP_STDIO:
+ buf.write_i32(3)
+ if value == SessionTransportOutput.MCP_HTTP:
+ buf.write_i32(4)
+
+
+
+@dataclass
+class SessionOutput:
+ """
+ Content-free lifecycle state safe for an ordinary agent transport.
+"""
+ def __init__(self, *, session:typing.Optional[str], implicit:bool, state:SessionLifecycleState, client_kind:SessionClientKindOutput, transport:SessionTransportOutput, cursor_visible:bool, recording_active:bool, idle_seconds:int, expires_in_seconds:int):
+ self.session = session
+ self.implicit = implicit
+ self.state = state
+ self.client_kind = client_kind
+ self.transport = transport
+ self.cursor_visible = cursor_visible
+ self.recording_active = recording_active
+ self.idle_seconds = idle_seconds
+ self.expires_in_seconds = expires_in_seconds
+
+
+
+
+ def __str__(self):
+ return "SessionOutput(session={}, implicit={}, state={}, client_kind={}, transport={}, cursor_visible={}, recording_active={}, idle_seconds={}, expires_in_seconds={})".format(self.session, self.implicit, self.state, self.client_kind, self.transport, self.cursor_visible, self.recording_active, self.idle_seconds, self.expires_in_seconds)
+ def __eq__(self, other):
+ if self.session != other.session:
+ return False
+ if self.implicit != other.implicit:
+ return False
+ if self.state != other.state:
+ return False
+ if self.client_kind != other.client_kind:
+ return False
+ if self.transport != other.transport:
+ return False
+ if self.cursor_visible != other.cursor_visible:
+ return False
+ if self.recording_active != other.recording_active:
+ return False
+ if self.idle_seconds != other.idle_seconds:
+ return False
+ if self.expires_in_seconds != other.expires_in_seconds:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeSessionOutput(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return SessionOutput(
+ session=_UniffiFfiConverterOptionalString.read(buf),
+ implicit=_UniffiFfiConverterBoolean.read(buf),
+ state=_UniffiFfiConverterTypeSessionLifecycleState.read(buf),
+ client_kind=_UniffiFfiConverterTypeSessionClientKindOutput.read(buf),
+ transport=_UniffiFfiConverterTypeSessionTransportOutput.read(buf),
+ cursor_visible=_UniffiFfiConverterBoolean.read(buf),
+ recording_active=_UniffiFfiConverterBoolean.read(buf),
+ idle_seconds=_UniffiFfiConverterUInt64.read(buf),
+ expires_in_seconds=_UniffiFfiConverterUInt64.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalString.check_lower(value.session)
+ _UniffiFfiConverterBoolean.check_lower(value.implicit)
+ _UniffiFfiConverterTypeSessionLifecycleState.check_lower(value.state)
+ _UniffiFfiConverterTypeSessionClientKindOutput.check_lower(value.client_kind)
+ _UniffiFfiConverterTypeSessionTransportOutput.check_lower(value.transport)
+ _UniffiFfiConverterBoolean.check_lower(value.cursor_visible)
+ _UniffiFfiConverterBoolean.check_lower(value.recording_active)
+ _UniffiFfiConverterUInt64.check_lower(value.idle_seconds)
+ _UniffiFfiConverterUInt64.check_lower(value.expires_in_seconds)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalString.write(value.session, buf)
+ _UniffiFfiConverterBoolean.write(value.implicit, buf)
+ _UniffiFfiConverterTypeSessionLifecycleState.write(value.state, buf)
+ _UniffiFfiConverterTypeSessionClientKindOutput.write(value.client_kind, buf)
+ _UniffiFfiConverterTypeSessionTransportOutput.write(value.transport, buf)
+ _UniffiFfiConverterBoolean.write(value.cursor_visible, buf)
+ _UniffiFfiConverterBoolean.write(value.recording_active, buf)
+ _UniffiFfiConverterUInt64.write(value.idle_seconds, buf)
+ _UniffiFfiConverterUInt64.write(value.expires_in_seconds, buf)
+
+class _UniffiFfiConverterSequenceTypeSessionOutput(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypeSessionOutput.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypeSessionOutput.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypeSessionOutput.read(buf) for i in range(count)
+ ]
+
+@dataclass
+class ListSessionsOutput:
+ def __init__(self, *, sessions:typing.List[SessionOutput], next_cursor:typing.Optional[str]):
+ self.sessions = sessions
+ self.next_cursor = next_cursor
+
+
+
+
+ def __str__(self):
+ return "ListSessionsOutput(sessions={}, next_cursor={})".format(self.sessions, self.next_cursor)
+ def __eq__(self, other):
+ if self.sessions != other.sessions:
+ return False
+ if self.next_cursor != other.next_cursor:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeListSessionsOutput(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return ListSessionsOutput(
+ sessions=_UniffiFfiConverterSequenceTypeSessionOutput.read(buf),
+ next_cursor=_UniffiFfiConverterOptionalString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterSequenceTypeSessionOutput.check_lower(value.sessions)
+ _UniffiFfiConverterOptionalString.check_lower(value.next_cursor)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterSequenceTypeSessionOutput.write(value.sessions, buf)
+ _UniffiFfiConverterOptionalString.write(value.next_cursor, buf)
+
@dataclass
class MoveCursorInput:
- def __init__(self, *, x:float, y:float, scope:DesktopScope, session:typing.Optional[str]):
+ def __init__(self, *, x:float, y:float, target:typing.Optional[ActionTarget], scope:typing.Optional[DesktopScope], session:typing.Optional[str]):
self.x = x
self.y = y
+ self.target = target
self.scope = scope
self.session = session
@@ -3161,12 +3727,14 @@ class MoveCursorInput:
def __str__(self):
- return "MoveCursorInput(x={}, y={}, scope={}, session={})".format(self.x, self.y, self.scope, self.session)
+ return "MoveCursorInput(x={}, y={}, target={}, scope={}, session={})".format(self.x, self.y, self.target, self.scope, self.session)
def __eq__(self, other):
if self.x != other.x:
return False
if self.y != other.y:
return False
+ if self.target != other.target:
+ return False
if self.scope != other.scope:
return False
if self.session != other.session:
@@ -3179,7 +3747,8 @@ class _UniffiFfiConverterTypeMoveCursorInput(_UniffiConverterRustBuffer):
return MoveCursorInput(
x=_UniffiFfiConverterFloat64.read(buf),
y=_UniffiFfiConverterFloat64.read(buf),
- scope=_UniffiFfiConverterTypeDesktopScope.read(buf),
+ target=_UniffiFfiConverterOptionalTypeActionTarget.read(buf),
+ scope=_UniffiFfiConverterOptionalTypeDesktopScope.read(buf),
session=_UniffiFfiConverterOptionalString.read(buf),
)
@@ -3187,14 +3756,16 @@ class _UniffiFfiConverterTypeMoveCursorInput(_UniffiConverterRustBuffer):
def check_lower(value):
_UniffiFfiConverterFloat64.check_lower(value.x)
_UniffiFfiConverterFloat64.check_lower(value.y)
- _UniffiFfiConverterTypeDesktopScope.check_lower(value.scope)
+ _UniffiFfiConverterOptionalTypeActionTarget.check_lower(value.target)
+ _UniffiFfiConverterOptionalTypeDesktopScope.check_lower(value.scope)
_UniffiFfiConverterOptionalString.check_lower(value.session)
@staticmethod
def write(value, buf):
_UniffiFfiConverterFloat64.write(value.x, buf)
_UniffiFfiConverterFloat64.write(value.y, buf)
- _UniffiFfiConverterTypeDesktopScope.write(value.scope, buf)
+ _UniffiFfiConverterOptionalTypeActionTarget.write(value.target, buf)
+ _UniffiFfiConverterOptionalTypeDesktopScope.write(value.scope, buf)
_UniffiFfiConverterOptionalString.write(value.session, buf)
@@ -3400,8 +3971,9 @@ class _UniffiFfiConverterTypePredicateOutcome(_UniffiConverterRustBuffer):
@dataclass
class PressKeyInput:
- def __init__(self, *, key:str, scope:DesktopScope, session:typing.Optional[str], modifiers:typing.Optional[typing.List[str]]):
+ def __init__(self, *, key:str, target:typing.Optional[ActionTarget], scope:typing.Optional[DesktopScope], session:typing.Optional[str], modifiers:typing.Optional[typing.List[str]]):
self.key = key
+ self.target = target
self.scope = scope
self.session = session
self.modifiers = modifiers
@@ -3410,10 +3982,12 @@ class PressKeyInput:
def __str__(self):
- return "PressKeyInput(key={}, scope={}, session={}, modifiers={})".format(self.key, self.scope, self.session, self.modifiers)
+ return "PressKeyInput(key={}, target={}, scope={}, session={}, modifiers={})".format(self.key, self.target, self.scope, self.session, self.modifiers)
def __eq__(self, other):
if self.key != other.key:
return False
+ if self.target != other.target:
+ return False
if self.scope != other.scope:
return False
if self.session != other.session:
@@ -3427,7 +4001,8 @@ class _UniffiFfiConverterTypePressKeyInput(_UniffiConverterRustBuffer):
def read(buf):
return PressKeyInput(
key=_UniffiFfiConverterString.read(buf),
- scope=_UniffiFfiConverterTypeDesktopScope.read(buf),
+ target=_UniffiFfiConverterOptionalTypeActionTarget.read(buf),
+ scope=_UniffiFfiConverterOptionalTypeDesktopScope.read(buf),
session=_UniffiFfiConverterOptionalString.read(buf),
modifiers=_UniffiFfiConverterOptionalSequenceString.read(buf),
)
@@ -3435,14 +4010,16 @@ class _UniffiFfiConverterTypePressKeyInput(_UniffiConverterRustBuffer):
@staticmethod
def check_lower(value):
_UniffiFfiConverterString.check_lower(value.key)
- _UniffiFfiConverterTypeDesktopScope.check_lower(value.scope)
+ _UniffiFfiConverterOptionalTypeActionTarget.check_lower(value.target)
+ _UniffiFfiConverterOptionalTypeDesktopScope.check_lower(value.scope)
_UniffiFfiConverterOptionalString.check_lower(value.session)
_UniffiFfiConverterOptionalSequenceString.check_lower(value.modifiers)
@staticmethod
def write(value, buf):
_UniffiFfiConverterString.write(value.key, buf)
- _UniffiFfiConverterTypeDesktopScope.write(value.scope, buf)
+ _UniffiFfiConverterOptionalTypeActionTarget.write(value.target, buf)
+ _UniffiFfiConverterOptionalTypeDesktopScope.write(value.scope, buf)
_UniffiFfiConverterOptionalString.write(value.session, buf)
_UniffiFfiConverterOptionalSequenceString.write(value.modifiers, buf)
@@ -3569,10 +4146,11 @@ class _UniffiFfiConverterOptionalTypeScrollBy(_UniffiConverterRustBuffer):
@dataclass
class ScrollInput:
- def __init__(self, *, x:float, y:float, direction:ScrollDirection, scope:DesktopScope, session:typing.Optional[str], by:typing.Optional[ScrollBy], amount:typing.Optional[int]):
+ def __init__(self, *, x:float, y:float, direction:ScrollDirection, target:typing.Optional[ActionTarget], scope:typing.Optional[DesktopScope], session:typing.Optional[str], by:typing.Optional[ScrollBy], amount:typing.Optional[int]):
self.x = x
self.y = y
self.direction = direction
+ self.target = target
self.scope = scope
self.session = session
self.by = by
@@ -3582,7 +4160,7 @@ class ScrollInput:
def __str__(self):
- return "ScrollInput(x={}, y={}, direction={}, scope={}, session={}, by={}, amount={})".format(self.x, self.y, self.direction, self.scope, self.session, self.by, self.amount)
+ return "ScrollInput(x={}, y={}, direction={}, target={}, scope={}, session={}, by={}, amount={})".format(self.x, self.y, self.direction, self.target, self.scope, self.session, self.by, self.amount)
def __eq__(self, other):
if self.x != other.x:
return False
@@ -3590,6 +4168,8 @@ class ScrollInput:
return False
if self.direction != other.direction:
return False
+ if self.target != other.target:
+ return False
if self.scope != other.scope:
return False
if self.session != other.session:
@@ -3607,7 +4187,8 @@ class _UniffiFfiConverterTypeScrollInput(_UniffiConverterRustBuffer):
x=_UniffiFfiConverterFloat64.read(buf),
y=_UniffiFfiConverterFloat64.read(buf),
direction=_UniffiFfiConverterTypeScrollDirection.read(buf),
- scope=_UniffiFfiConverterTypeDesktopScope.read(buf),
+ target=_UniffiFfiConverterOptionalTypeActionTarget.read(buf),
+ scope=_UniffiFfiConverterOptionalTypeDesktopScope.read(buf),
session=_UniffiFfiConverterOptionalString.read(buf),
by=_UniffiFfiConverterOptionalTypeScrollBy.read(buf),
amount=_UniffiFfiConverterOptionalUInt64.read(buf),
@@ -3618,7 +4199,8 @@ class _UniffiFfiConverterTypeScrollInput(_UniffiConverterRustBuffer):
_UniffiFfiConverterFloat64.check_lower(value.x)
_UniffiFfiConverterFloat64.check_lower(value.y)
_UniffiFfiConverterTypeScrollDirection.check_lower(value.direction)
- _UniffiFfiConverterTypeDesktopScope.check_lower(value.scope)
+ _UniffiFfiConverterOptionalTypeActionTarget.check_lower(value.target)
+ _UniffiFfiConverterOptionalTypeDesktopScope.check_lower(value.scope)
_UniffiFfiConverterOptionalString.check_lower(value.session)
_UniffiFfiConverterOptionalTypeScrollBy.check_lower(value.by)
_UniffiFfiConverterOptionalUInt64.check_lower(value.amount)
@@ -3628,7 +4210,8 @@ class _UniffiFfiConverterTypeScrollInput(_UniffiConverterRustBuffer):
_UniffiFfiConverterFloat64.write(value.x, buf)
_UniffiFfiConverterFloat64.write(value.y, buf)
_UniffiFfiConverterTypeScrollDirection.write(value.direction, buf)
- _UniffiFfiConverterTypeDesktopScope.write(value.scope, buf)
+ _UniffiFfiConverterOptionalTypeActionTarget.write(value.target, buf)
+ _UniffiFfiConverterOptionalTypeDesktopScope.write(value.scope, buf)
_UniffiFfiConverterOptionalString.write(value.session, buf)
_UniffiFfiConverterOptionalTypeScrollBy.write(value.by, buf)
_UniffiFfiConverterOptionalUInt64.write(value.amount, buf)
@@ -4197,7 +4780,7 @@ class _UniffiFfiConverterOptionalTypeCursorThemeSelection(_UniffiConverterRustBu
@dataclass
class StartSessionInput:
- def __init__(self, *, session:str, capture_scope:typing.Optional[CaptureScope], cursor_theme:typing.Optional[CursorThemeSelection]):
+ def __init__(self, *, session:typing.Optional[str], capture_scope:typing.Optional[CaptureScope], cursor_theme:typing.Optional[CursorThemeSelection]):
self.session = session
self.capture_scope = capture_scope
self.cursor_theme = cursor_theme
@@ -4220,20 +4803,20 @@ class _UniffiFfiConverterTypeStartSessionInput(_UniffiConverterRustBuffer):
@staticmethod
def read(buf):
return StartSessionInput(
- session=_UniffiFfiConverterString.read(buf),
+ session=_UniffiFfiConverterOptionalString.read(buf),
capture_scope=_UniffiFfiConverterOptionalTypeCaptureScope.read(buf),
cursor_theme=_UniffiFfiConverterOptionalTypeCursorThemeSelection.read(buf),
)
@staticmethod
def check_lower(value):
- _UniffiFfiConverterString.check_lower(value.session)
+ _UniffiFfiConverterOptionalString.check_lower(value.session)
_UniffiFfiConverterOptionalTypeCaptureScope.check_lower(value.capture_scope)
_UniffiFfiConverterOptionalTypeCursorThemeSelection.check_lower(value.cursor_theme)
@staticmethod
def write(value, buf):
- _UniffiFfiConverterString.write(value.session, buf)
+ _UniffiFfiConverterOptionalString.write(value.session, buf)
_UniffiFfiConverterOptionalTypeCaptureScope.write(value.capture_scope, buf)
_UniffiFfiConverterOptionalTypeCursorThemeSelection.write(value.cursor_theme, buf)
@@ -4431,8 +5014,9 @@ class _UniffiFfiConverterTypeStatePredicate(_UniffiConverterRustBuffer):
@dataclass
class TypeTextInput:
- def __init__(self, *, text:str, scope:DesktopScope, session:typing.Optional[str]):
+ def __init__(self, *, text:str, target:typing.Optional[ActionTarget], scope:typing.Optional[DesktopScope], session:typing.Optional[str]):
self.text = text
+ self.target = target
self.scope = scope
self.session = session
@@ -4440,10 +5024,12 @@ class TypeTextInput:
def __str__(self):
- return "TypeTextInput(text={}, scope={}, session={})".format(self.text, self.scope, self.session)
+ return "TypeTextInput(text={}, target={}, scope={}, session={})".format(self.text, self.target, self.scope, self.session)
def __eq__(self, other):
if self.text != other.text:
return False
+ if self.target != other.target:
+ return False
if self.scope != other.scope:
return False
if self.session != other.session:
@@ -4455,20 +5041,23 @@ class _UniffiFfiConverterTypeTypeTextInput(_UniffiConverterRustBuffer):
def read(buf):
return TypeTextInput(
text=_UniffiFfiConverterString.read(buf),
- scope=_UniffiFfiConverterTypeDesktopScope.read(buf),
+ target=_UniffiFfiConverterOptionalTypeActionTarget.read(buf),
+ scope=_UniffiFfiConverterOptionalTypeDesktopScope.read(buf),
session=_UniffiFfiConverterOptionalString.read(buf),
)
@staticmethod
def check_lower(value):
_UniffiFfiConverterString.check_lower(value.text)
- _UniffiFfiConverterTypeDesktopScope.check_lower(value.scope)
+ _UniffiFfiConverterOptionalTypeActionTarget.check_lower(value.target)
+ _UniffiFfiConverterOptionalTypeDesktopScope.check_lower(value.scope)
_UniffiFfiConverterOptionalString.check_lower(value.session)
@staticmethod
def write(value, buf):
_UniffiFfiConverterString.write(value.text, buf)
- _UniffiFfiConverterTypeDesktopScope.write(value.scope, buf)
+ _UniffiFfiConverterOptionalTypeActionTarget.write(value.target, buf)
+ _UniffiFfiConverterOptionalTypeDesktopScope.write(value.scope, buf)
_UniffiFfiConverterOptionalString.write(value.session, buf)
class _UniffiFfiConverterInt64(_UniffiConverterPrimitiveInt):
@@ -4719,11 +5308,15 @@ __all__ = [
"ActionEvidenceKind",
"ActionEffect",
"ActionRoute",
+ "ActionTarget",
"DesktopScope",
"ClickButton",
"CursorReducedMotion",
"CursorAction",
"EscalationReason",
+ "SessionLifecycleState",
+ "SessionClientKindOutput",
+ "SessionTransportOutput",
"VerificationStatus",
"UnknownReason",
"ScrollDirection",
@@ -4757,9 +5350,13 @@ __all__ = [
"GetCursorPositionInput",
"GetDesktopStateInput",
"GetScreenSizeInput",
+ "GetSessionInput",
"GetSessionStateInput",
"HotkeyInput",
"InvokeMenuInput",
+ "ListSessionsInput",
+ "SessionOutput",
+ "ListSessionsOutput",
"MoveCursorInput",
"PredicateOutcome",
"PressKeyInput",
diff --git a/libs/cua-driver/python/tests/test_uniffi_loader.py b/libs/cua-driver/python/tests/test_uniffi_loader.py
index 7bb925be58..6441166b5f 100644
--- a/libs/cua-driver/python/tests/test_uniffi_loader.py
+++ b/libs/cua-driver/python/tests/test_uniffi_loader.py
@@ -58,7 +58,7 @@ while True:
if request["method"] == "metadata":
result = {
"driver_version": "0.10.0",
- "contract_version": "0.6.0",
+ "contract_version": "0.7.0",
"tools_list_schema_version": "1",
"capability_version": "1",
"mcp_protocol_version": "2025-06-18",
@@ -142,7 +142,7 @@ except FileNotFoundError:
if request["method"] == "metadata":
result = {
"driver_version": "0.12.6",
- "contract_version": "0.6.0",
+ "contract_version": "0.7.0",
"tools_list_schema_version": "1",
"capability_version": "1",
"mcp_protocol_version": "2025-06-18",
@@ -186,6 +186,8 @@ except FileNotFoundError:
expected_methods = {
"start_session",
"escalate_session",
+ "get_session",
+ "list_sessions",
"get_session_state",
"end_session",
"get_desktop_state",
@@ -224,6 +226,7 @@ except FileNotFoundError:
ClickInput(
x=12.0,
y=34.0,
+ target=None,
scope=DesktopScope.DESKTOP,
session="python-run",
button=ClickButton.LEFT,
diff --git a/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md b/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
index 37d3bce1e1..8bb789d3dc 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/EMBEDDING.md
@@ -194,8 +194,9 @@ daemon child.
completion is unknown.
- The Rust owner holds a parent-liveness pipe, so host death closes the daemon;
orderly shutdown should still await `stop()`.
-- Capture scope belongs to each session. One embedded daemon can concurrently
- serve `auto`, strict `window`, and strict `desktop` sessions.
+- Capture modality belongs to each observation or action target, not to the
+ lifecycle session. One embedded daemon can concurrently serve exact window
+ and desktop calls without changing session state.
- Permission changes require destroying clients, restarting the daemon, and
reconnecting. A connection from the old generation is never reusable.
diff --git a/libs/cua-driver/rust/Skills/cua-driver/LINUX.md b/libs/cua-driver/rust/Skills/cua-driver/LINUX.md
index 8a9c9d4808..686a5b5dde 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/LINUX.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/LINUX.md
@@ -127,11 +127,13 @@ CI so the three surfaces can't drift. Linux-relevant notes:
Linux builds rejected it via `additionalProperties:false` (it was
effectively macOS-only); it is now uniformly schema-accepted — Linux
glides a per-session cursor on X11 where the overlay is available.
-- **Windowless screen-absolute actions** pass `scope:"desktop"` with no
- pid/window_id, uniformly with macOS and Windows. The session must have
- effective desktop scope (`start_session(..., capture_scope:"desktop")`, or
- an explicitly escalated `auto` session). Strict window sessions receive
- `desktop_scope_disabled`; no persistent config is read or written.
+- **Windowless screen-absolute actions** use
+ `target:{"kind":"desktop","display_id":"primary"}`, uniformly with macOS
+ and Windows. Exact window actions use
+ `target:{"kind":"window","pid":PID,"window_id":WINDOW_ID}`. Legacy flat
+ `scope`, `pid`, and `window_id` fields remain compatibility inputs, but do
+ not combine them with `target`; capture modality no longer changes lifecycle
+ session state.
## Native application menus
diff --git a/libs/cua-driver/rust/Skills/cua-driver/MACOS.md b/libs/cua-driver/rust/Skills/cua-driver/MACOS.md
index da2f332218..2e4424190d 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/MACOS.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/MACOS.md
@@ -324,11 +324,12 @@ _Cross-platform parameter contract_):
- **`session` always worked on macOS;** the cross-platform change is that
Windows/Linux stopped _rejecting_ it. No macOS-side change to how you
pass it.
-- **`scope`** (`window` / `desktop`) selects the action form uniformly on all
- platforms. Pass `scope:"desktop"` with no pid/window_id for screen-absolute
- pointer actions or foreground keyboard actions. The session's immutable
- `capture_scope` policy must permit that form; set it with `start_session`,
- never persistent config.
+- **`target`** selects the action coordinate space uniformly on all platforms.
+ Use `target:{"kind":"desktop","display_id":"primary"}` for
+ screen-absolute pointer actions or foreground keyboard actions, and
+ `target:{"kind":"window","pid":PID,"window_id":WINDOW_ID}` for exact
+ window coordinates. Legacy flat `scope`, `pid`, and `window_id` fields remain
+ compatibility inputs, but do not combine them with `target`.
### Canvases, viewports, games (Blender, Unity, GHOST, Qt, wxWidgets)
diff --git a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md b/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
index 61a43023b9..cb8960b8fd 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
@@ -142,8 +142,8 @@ in the background.
## The no-foreground principle (window phase)
-In a strict `window` session, and during the initial window phase of an
-`auto` session, **the user's frontmost app MUST NOT change.** Every platform
+During window-targeted background actions, **the user's frontmost app MUST NOT
+change.** Every platform
has its own list of forbidden commands:
- macOS: any `open` invocation, any `osascript` that mutates GUI
@@ -157,11 +157,11 @@ If you reach for a command that says "activate", "foreground",
"raise", or "make key", stop and translate to the cua-driver tool
that does the same intent without focus-stealing.
-A strict `desktop` session is an explicit user choice to operate the visible
-desktop and therefore uses foreground/system input. An `auto` session may enter
-that phase only after the complete window ladder below has been attempted and
-verified, followed by `escalate_session`. Never infer desktop permission from a
-failed action or a proxy/transport session id.
+A desktop target is an explicit per-call choice to operate the visible desktop
+and therefore uses foreground/system input. Use it only after the narrower
+window ladder has been attempted and verified. Permission policy must still
+admit the display resource. Never infer desktop permission from a failed action
+or a public session label.
## GUI transport defaults — prefer cua-driver over GUI shell shims
@@ -232,7 +232,7 @@ cua-driver stop
```
For Chromium page content, keep the same native window selection but switch to
-the browser capability loop: `start_session`, bind `(pid, window_id)` with
+the browser capability loop: use one lifecycle session, bind `(pid, window_id)` with
`get_browser_state`, snapshot the returned tab, then use `browser_click`,
`browser_type`, or `browser_navigate`. Read `BROWSER.md` before using this
route. Browser target ids, tab ids, and refs are session-scoped and stale refs
@@ -240,8 +240,9 @@ must be replaced by a fresh snapshot.
## Agent cursor overlay
-Visual cursor overlay for demos and screen recordings. It is enabled by
-default for declared sessions; anonymous actions remain cursor-less. Toggle with
+Visual cursor overlay for demos and screen recordings. It initializes on the
+first cursor-bearing action, including `move_cursor`, and follows the
+transport's implicit or named lifecycle session. Toggle a named cursor with
`set_agent_cursor_enabled` to hide or re-show it. The embedded
`cua.default` theme uses a session-colored pointer over a larger,
cursor-shaped glow in the same session color. The glow fades to transparent
@@ -347,7 +348,8 @@ An optional escalation is a harness instruction, never an automatic retry:
- `pixel`: refresh visual state and choose an exact pixel target;
- `foreground`: explicitly select foreground delivery if session policy allows;
- `page`: bind the native window to a supported browser page route;
-- `session`: prepare or explicitly widen the session only when policy permits.
+- `session`: a legacy compatibility signal from an older capture-scope daemon;
+ current callers choose a desktop target on the specific action instead.
Branch on the closed reason vocabulary:
`route_unavailable`, `delivery_failed`, `effect_unconfirmed`,
@@ -357,38 +359,31 @@ After any action, keep using `verify_state` or a fresh state snapshot for the
actual task postcondition. The multimodal harness owns visual reading and the
decision to stop, retry, or advance the ladder.
-## Choose capture scope when the session starts
+## Choose the target on each action
-`capture_scope` is a per-session policy, not persistent configuration. Declare
-it with `start_session`; it is immutable until that session ends. Concurrent
-sessions may choose different policies safely.
+A session owns lifecycle, cursor, recording, cleanup, and telemetry state. It
+does not store the current capture modality. Select an exact target on each
+action:
-- `auto` (default): begins with effective scope `window`. Desktop perception
- and actions are locked until the window ladder is exhausted, each attempted
- action is verified, and the caller explicitly invokes `escalate_session`.
- Escalation is permanent for that session, and window-scoped tools remain
- disabled. To recover window scope, call `end_session`, then call
- `start_session` with a new session id.
-- `window`: strict window-only perception and actions. Desktop tools are always
- rejected with `desktop_scope_disabled`.
-- `desktop`: strict full-desktop perception and foreground/system actions.
- Window-scoped perception and actions are rejected with
- `window_scope_disabled`.
-
-```bash
-cua-driver start_session '{"session":"research-1","capture_scope":"auto"}'
-cua-driver get_session_state '{"session":"research-1"}'
+```jsonc
+{"target":{"kind":"window","pid":844,"window_id":10725}}
+{"target":{"kind":"desktop","display_id":"primary"}}
```
-Do not use `config set capture_scope` or `set_config`; that key is retired and
-stale values on disk are ignored. Always pass the public `session` field on
-state and action calls. Reserved fields such as `_session_id` are transport
-metadata and cannot create or change policy.
+The window target uses window-local coordinates and the background/foreground
+delivery ladder. The desktop target uses screen coordinates and foreground
+delivery. A desktop action does not disable window tools for later calls.
-During a mixed-version rollout, require `tools/list` to advertise
-`session.capture_scope` (and `session.capture_scope.escalate` for `auto`). If an
-older daemon does not advertise them, fail closed and ask for an upgrade; never
-fall back to the retired global config key.
+`start_session` is optional. The first admitted stateful call creates one
+implicit session for the authenticated transport, and later unnamed calls on
+that transport reuse it. The default idle TTL is five minutes. Use a public
+session label only when you need explicit naming or lifecycle control.
+
+Do not use `config set capture_scope` or `set_config`; that key is retired and
+stale values on disk are ignored. `start_session.capture_scope`,
+`get_session_state`, and `escalate_session` are deprecated compatibility
+surfaces. There is no `deescalate_session`. Reserved fields such as
+`_session_id` are transport metadata and cannot create authority.
### Why window selection is the caller's job now
@@ -573,15 +568,12 @@ if resp.escalation.target == "foreground"
# unfocused window there; see LINUX.md
verify again
-# Route 5 — desktop fallback (auto sessions only, explicit and one-way)
+# Route 5 — per-call desktop fallback
# Reach this only after semantic, AX, window-pixel, and foreground-window
# delivery have all been exhausted and verified ineffective.
-escalate_session(session,
- reason="foreground_ineffective", # or another advertised reason
- detail="bounded non-sensitive summary")
-get_desktop_state(session) # full primary display
-desktop_action(session, scope="desktop", ...) # no pid/window_id
-get_desktop_state(session) # verify in the same coordinate frame
+get_desktop_state() # full primary display
+desktop_action(target={kind:"desktop", display_id:"primary"}, ...)
+get_desktop_state() # verify in the same coordinate frame
```
The two ideas to hold onto: (1) the AX tree **lies** on canvas / web /
@@ -612,44 +604,40 @@ last resort.
## The canonical loop
```
-start_session(session, capture_scope="auto") # once per run; policy is immutable
+# start_session(session) is optional; ordinary calls create an implicit session
launch_app(target)
→ pick window_id from the returned `windows` array
(or call list_windows(pid) separately)
→ get_window_state(pid, window_id)
- → [act] # every action also takes (pid, window_id) + your `session`
+ → [act] # pass target={kind:"window", pid, window_id}
→ verify_state(pid, window_id, expect) # structured check; optional image
-end_session(session) # when the run finishes
+end_session(session?) # optional explicit cleanup
```
-For strict desktop sessions, replace the window portion with
-`get_desktop_state(session) → action(session, scope="desktop", ...) →
-get_desktop_state(session)`. Desktop actions use screen-absolute coordinates
-from that exact full-display image and omit `pid`/`window_id`. The global
-`get_screen_size` and `get_cursor_position` helpers are desktop-scoped too.
+For screen-absolute work, replace the window portion with
+`get_desktop_state() → action(target={kind:"desktop",display_id:"primary"}, ...)
+→ get_desktop_state()`. Desktop actions use coordinates from that exact
+full-display image.
`launch_app` now returns a `windows` array alongside the pid, so the
common case collapses to two calls (`launch_app` → `get_window_state`)
without a separate `list_windows` hop.
-**Declare a session.** A session is _your run's_ identity — a stable id
-you choose (`"research-1"`), declared with `start_session` and passed as
-`session` on every action. It owns your agent cursor and capture policy (a
-distinct colour and one immutable policy per id), follows the run across any
-apps/windows, and is the same whether
-you drive over MCP, the CLI, or the socket. Declaring the session creates the
-cursor; anonymous actions remain cursor-less.
-End with `end_session` (or the idle-TTL reclaims it).
-
-**Concurrent runs/subagents:** each run may independently choose `auto`,
-`window`, or `desktop`; one session's escalation never changes another. Also,
+**Name a session only when useful.** An unnamed transport still gets one private
+lifecycle identity and visible agent cursor. A public label such as
+`"research-1"` makes explicit inspection and cleanup easier, but it is not a
+credential. End with `end_session` when useful; transport close or the
+five-minute idle TTL also reclaims it.
+
+**Concurrent runs/subagents:** each transport gets its own implicit session.
+Also,
`launch_app` is idempotent — two runs that
launch the same app get the **same** instance (and on single-instance apps
like Calculator, the same window), so they clobber each other. Give each run
-its **own `session`** (→ its own cursor) AND pass
+its **own connection** (for independent lifecycle/cursor ownership) AND pass
`creates_new_application_instance: true` to `launch_app` (→ its own window).
-The element cache is keyed on `(pid, window_id)` and the cursor on `session`,
-so distinct instances + distinct sessions keep the runs fully separated.
+The element cache is keyed on `(pid, window_id)` and the cursor on the private
+lifecycle session, so distinct instances and transports keep the runs isolated.
**Parallelism vs. ordering.** Distinct sessions give distinct _cursors_, not
distinct _connections_. Subagents that share one `cua-driver mcp` (stdio)
diff --git a/libs/cua-driver/rust/Skills/cua-driver/WINDOWS.md b/libs/cua-driver/rust/Skills/cua-driver/WINDOWS.md
index 226d3ea456..e0526c7c91 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/WINDOWS.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/WINDOWS.md
@@ -417,15 +417,13 @@ When a cua-driver call surprises you, diagnose cua-driver first:
is unresponsive. `list_windows` falls back to Win32-only output instead
of hanging; run `cua-driver doctor` and retry after the provider
recovers.
-- **`get_desktop_state` returns `desktop_scope_disabled`?** That's
- intended: full-display capture is a **desktop-scope** operation, gated
- by the caller-declared session policy. To verify a specific window use
- `get_window_state(pid, window_id)` (works backgrounded). Use
- `get_desktop_state` only in a strict desktop session or after explicitly
- escalating an `auto` session once the window ladder is exhausted. Desktop
- actions pass `scope:"desktop"` with no pid/window_id. Don't reach for
- `get_desktop_state` as a casual screenshot — it's the capture surface for
- desktop-scope coordinate loops, not window inspection.
+- **Need full-display capture?** Use `get_desktop_state` only for a desktop
+ coordinate loop. To verify a specific window, use
+ `get_window_state(pid, window_id)` instead; it works while backgrounded.
+ Desktop actions use
+ `target:{"kind":"desktop","display_id":"primary"}`. Don't reach for
+ `get_desktop_state` as a casual screenshot—it is the desktop capture
+ surface, not window inspection.
- **`Calc display stuck at 0 after my clicks`?** Almost always
means UWP and you're on the PostMessage path. UWP processes
pointer input via `Windows.UI.Input`, NOT through HWND message
diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/compatibility.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/compatibility.rs
index 44f7aeba05..2471f3a178 100644
--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/compatibility.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/compatibility.rs
@@ -43,6 +43,14 @@ pub fn schema_subset_violations(portable: &Value, live: &Value) -> Vec<String> {
}
fn compare_schema(path: &str, portable: &Value, live: &Value, violations: &mut Vec<String>) {
+ // Exact schema equality is itself a proof of subset compatibility, even
+ // when the shared schema contains a construct (for example a generated
+ // tagged-union `anyOf`) that this intentionally small implication engine
+ // does not otherwise interpret.
+ if portable == live {
+ return;
+ }
+
let Some(portable_object) = portable.as_object() else {
violations.push(format!("{path}: portable schema must be an object"));
return;
@@ -370,6 +378,17 @@ mod tests {
assert!(violations[0].contains("unsupported portable schema keyword `pattern`"));
}
+ #[test]
+ fn identical_unknown_schema_is_a_proven_subset() {
+ let schema = json!({
+ "anyOf": [
+ { "type": "string" },
+ { "type": "null" }
+ ]
+ });
+ assert!(schema_subset_violations(&schema, &schema).is_empty());
+ }
+
#[test]
fn additional_property_domain_must_be_accepted_live() {
let portable = json!({ "type": "object" });
diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/inputs.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/inputs.rs
index 4cd11eeb1c..cbf03afa61 100644
--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/inputs.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/inputs.rs
@@ -118,8 +118,7 @@ fn escalation_detail_schema(_: &mut SchemaGenerator) -> Schema {
fn capture_scope_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({
"type": "string",
- "enum": ["auto", "window", "desktop"],
- "default": "auto"
+ "enum": ["auto", "window", "desktop"]
})
}
@@ -198,6 +197,35 @@ pub enum DesktopScope {
Desktop,
}
+fn desktop_scope_schema(generator: &mut SchemaGenerator) -> Schema {
+ DesktopScope::json_schema(generator)
+}
+
+/// Exact capture/input target selected independently for each action.
+///
+/// `display_id="primary"` is the portable desktop target in this release.
+/// Platforms that cannot address another display reject it explicitly rather
+/// than silently changing coordinate spaces.
+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Enum)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum ActionTarget {
+ Window { pid: u32, window_id: u64 },
+ Desktop { display_id: String },
+}
+
+pub fn action_target_schema() -> Value {
+ let settings = schemars::generate::SchemaSettings::draft2020_12().with(|settings| {
+ settings.meta_schema = None;
+ settings.inline_subschemas = true;
+ });
+ let schema = settings
+ .into_generator()
+ .into_root_schema_for::<ActionTarget>();
+ let mut value = serde_json::to_value(schema).expect("action target schema serializes");
+ normalize_schema(&mut value);
+ value
+}
+
impl JsonSchema for DesktopScope {
fn schema_name() -> std::borrow::Cow<'static, str> {
"DesktopScope".into()
@@ -264,9 +292,14 @@ impl ScrollBy {
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, uniffi::Record)]
pub struct StartSessionInput {
- /// Stable session id for this run (e.g. "research-run-1").
- pub session: String,
- /// Per-session perception/action modality. auto starts window-only and requires explicit escalation before desktop tools; escalation permanently switches that session to desktop scope. To recover window scope, call end_session, then start_session with a new session id. window and desktop are strict. Immutable for the live session.
+ /// Optional stable public label for this run (e.g. "research-run-1").
+ /// When omitted, the authenticated transport lease's implicit session is
+ /// created or returned.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "string_schema")]
+ pub session: Option<String>,
+ /// Deprecated compatibility policy. New callers select window or desktop
+ /// modality on each action instead of storing it on the session.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(schema_with = "capture_scope_schema")]
pub capture_scope: Option<CaptureScope>,
@@ -296,17 +329,53 @@ impl ToolInput for EscalateSessionInput {
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, uniffi::Record)]
pub struct GetSessionStateInput {
- pub session: String,
+ /// Optional public label. When omitted, inspect the caller's attached
+ /// implicit session.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "string_schema")]
+ pub session: Option<String>,
}
impl ToolInput for GetSessionStateInput {
const TOOL_NAME: &'static str = "get_session_state";
}
+#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, uniffi::Record)]
+pub struct GetSessionInput {
+ /// Optional public label. When omitted, inspect the caller's attached
+ /// implicit session.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "string_schema")]
+ pub session: Option<String>,
+}
+
+impl ToolInput for GetSessionInput {
+ const TOOL_NAME: &'static str = "get_session";
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, uniffi::Record)]
+pub struct ListSessionsInput {
+ /// Maximum number of content-free summaries to return (default 50, max
+ /// 100). Ordinary agent transports are scoped to their own lease.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub limit: Option<u32>,
+ /// Opaque continuation cursor returned by a previous call.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "string_schema")]
+ pub cursor: Option<String>,
+}
+
+impl ToolInput for ListSessionsInput {
+ const TOOL_NAME: &'static str = "list_sessions";
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, uniffi::Record)]
pub struct EndSessionInput {
- /// The session id to end.
- pub session: String,
+ /// Optional public label to end. When omitted, end the caller's attached
+ /// implicit session.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "string_schema")]
+ pub session: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, uniffi::Record)]
@@ -417,7 +486,13 @@ pub struct MoveCursorInput {
pub x: f64,
#[schemars(schema_with = "number_schema")]
pub y: f64,
- pub scope: DesktopScope,
+ /// Preferred per-call target. New callers should set this field.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub target: Option<ActionTarget>,
+ /// Deprecated flat desktop target retained for wire compatibility.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "desktop_scope_schema")]
+ pub scope: Option<DesktopScope>,
/// Optional session id.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(schema_with = "string_schema")]
@@ -482,7 +557,12 @@ pub struct ClickInput {
pub x: f64,
#[schemars(schema_with = "number_schema")]
pub y: f64,
- pub scope: DesktopScope,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub target: Option<ActionTarget>,
+ /// Deprecated flat desktop target retained for wire compatibility.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "desktop_scope_schema")]
+ pub scope: Option<DesktopScope>,
/// Optional session id.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(schema_with = "string_schema")]
@@ -510,7 +590,12 @@ pub struct DragInput {
pub to_x: f64,
#[schemars(schema_with = "number_schema")]
pub to_y: f64,
- pub scope: DesktopScope,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub target: Option<ActionTarget>,
+ /// Deprecated flat desktop target retained for wire compatibility.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "desktop_scope_schema")]
+ pub scope: Option<DesktopScope>,
/// Optional session id.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(schema_with = "string_schema")]
@@ -541,7 +626,12 @@ pub struct ScrollInput {
#[schemars(schema_with = "number_schema")]
pub y: f64,
pub direction: ScrollDirection,
- pub scope: DesktopScope,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub target: Option<ActionTarget>,
+ /// Deprecated flat desktop target retained for wire compatibility.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "desktop_scope_schema")]
+ pub scope: Option<DesktopScope>,
/// Optional session id.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(schema_with = "string_schema")]
@@ -562,7 +652,12 @@ impl ToolInput for ScrollInput {
#[serde(deny_unknown_fields)]
pub struct TypeTextInput {
pub text: String,
- pub scope: DesktopScope,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub target: Option<ActionTarget>,
+ /// Deprecated flat desktop target retained for wire compatibility.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "desktop_scope_schema")]
+ pub scope: Option<DesktopScope>,
/// Optional session id.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(schema_with = "string_schema")]
@@ -619,7 +714,12 @@ impl ToolInput for ClipboardWriteInput {
#[serde(deny_unknown_fields)]
pub struct PressKeyInput {
pub key: String,
- pub scope: DesktopScope,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub target: Option<ActionTarget>,
+ /// Deprecated flat desktop target retained for wire compatibility.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "desktop_scope_schema")]
+ pub scope: Option<DesktopScope>,
/// Optional session id.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(schema_with = "string_schema")]
@@ -638,7 +738,12 @@ impl ToolInput for PressKeyInput {
pub struct HotkeyInput {
#[schemars(length(min = 2))]
pub keys: Vec<String>,
- pub scope: DesktopScope,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub target: Option<ActionTarget>,
+ /// Deprecated flat desktop target retained for wire compatibility.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "desktop_scope_schema")]
+ pub scope: Option<DesktopScope>,
/// Optional session id.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(schema_with = "string_schema")]
@@ -660,8 +765,9 @@ mod tests {
let schema = ClickInput::input_schema();
assert_eq!(schema["type"], "object");
assert_eq!(schema["additionalProperties"], false);
- assert_eq!(schema["required"], json!(["x", "y", "scope"]));
- assert_eq!(schema["properties"]["scope"], json!({ "const": "desktop" }));
+ assert_eq!(schema["required"], json!(["x", "y"]));
+ assert_eq!(schema["properties"]["scope"]["const"], "desktop");
+ assert!(schema["properties"]["target"]["anyOf"].is_array());
assert_eq!(
schema["properties"]["button"],
json!({ "type": "string", "enum": ["left", "right", "middle"] })
@@ -673,11 +779,13 @@ mod tests {
}
#[test]
- fn generated_session_schema_preserves_default_and_open_input() {
+ fn generated_session_schema_makes_name_and_legacy_capture_optional() {
let schema = StartSessionInput::input_schema();
assert_eq!(schema["additionalProperties"], true);
- assert_eq!(schema["required"], json!(["session"]));
- assert_eq!(schema["properties"]["capture_scope"]["default"], "auto");
+ assert_eq!(schema["required"], json!([]));
+ assert!(schema["properties"]["capture_scope"]
+ .get("default")
+ .is_none());
assert_eq!(
schema["properties"]["capture_scope"]["enum"],
json!(["auto", "window", "desktop"])
@@ -689,7 +797,6 @@ mod tests {
let error = serde_json::from_value::<ClickInput>(json!({
"x": 1,
"y": 2,
- "scope": "desktop",
"pid": 3
}))
.expect_err("portable input must reject runtime-only fields");
diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs
index 60558739aa..45cd526f73 100644
--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs
@@ -27,11 +27,12 @@ pub use cursor::{
CursorSemantics, CursorTarget, CursorThemeSelection,
};
pub use inputs::{
- CaptureScope, ClickButton, ClickInput, ClipboardReadInput, ClipboardWriteInput, DesktopScope,
- DragInput, EndSessionInput, EscalateSessionInput, EscalationReason, GetAgentCursorStateInput,
- GetCursorPositionInput, GetDesktopStateInput, GetScreenSizeInput, GetSessionStateInput,
- HotkeyInput, InvokeMenuInput, MoveCursorInput, PressKeyInput, ScrollBy, ScrollDirection,
- ScrollInput, SetAgentCursorEnabledInput, SetAgentCursorMotionInput, SetAgentCursorThemeInput,
+ action_target_schema, ActionTarget, CaptureScope, ClickButton, ClickInput, ClipboardReadInput,
+ ClipboardWriteInput, DesktopScope, DragInput, EndSessionInput, EscalateSessionInput,
+ EscalationReason, GetAgentCursorStateInput, GetCursorPositionInput, GetDesktopStateInput,
+ GetScreenSizeInput, GetSessionInput, GetSessionStateInput, HotkeyInput, InvokeMenuInput,
+ ListSessionsInput, MoveCursorInput, PressKeyInput, ScrollBy, ScrollDirection, ScrollInput,
+ SetAgentCursorEnabledInput, SetAgentCursorMotionInput, SetAgentCursorThemeInput,
SetWindowFrameInput, StartSessionInput, ToolInput, TypeTextInput,
};
pub use outputs::{
@@ -40,9 +41,10 @@ pub use outputs::{
ActionEvidenceKind, ActionResult, ActionResultValidationError, ActionRoute,
ClipboardReadOutput, ClipboardWriteOutput, CursorMotionOutput, CursorPointOutput,
CursorPositionOutput, CursorThemeOutput, CursorVisualOutput, DesktopStateOutput,
- EffectiveScope, EndSessionOutput, GetAgentCursorStateOutput, ScreenSizeOutput,
- SessionStateOutput, SetAgentCursorEnabledOutput, SetAgentCursorMotionOutput,
- SetAgentCursorThemeOutput, StartSessionOutput, ToolOutput,
+ EffectiveScope, EndSessionOutput, GetAgentCursorStateOutput, ListSessionsOutput,
+ ScreenSizeOutput, SessionClientKindOutput, SessionLifecycleState, SessionOutput,
+ SessionStateOutput, SessionTransportOutput, SetAgentCursorEnabledOutput,
+ SetAgentCursorMotionOutput, SetAgentCursorThemeOutput, StartSessionOutput, ToolOutput,
};
pub use verification::{
BoundsExpectation, ElementPredicate, ElementSelector, PredicateOutcome, StatePredicate,
@@ -57,7 +59,7 @@ pub const TOOLS_LIST_SCHEMA_VERSION: &str = "1";
pub const CAPABILITY_VERSION: &str = "1";
/// Shape version for the checked-in generated client contract.
-pub const CONTRACT_VERSION: &str = "0.6.0";
+pub const CONTRACT_VERSION: &str = "0.7.0";
/// MCP protocol version used by current cua-driver clients.
pub const MCP_PROTOCOL_VERSION: &str = "2025-06-18";
@@ -294,7 +296,7 @@ mod tests {
let mut sorted = names.clone();
sorted.sort_unstable();
assert_eq!(names, sorted);
- assert_eq!(manifest.contract_version, "0.6.0");
+ assert_eq!(manifest.contract_version, "0.7.0");
assert!(manifest.experimental);
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/outputs.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/outputs.rs
index 05d2d8e682..849ed0b0b6 100644
--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/outputs.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/outputs.rs
@@ -119,6 +119,59 @@ pub struct SessionStateOutput {
impl ToolOutput for SessionStateOutput {}
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Enum)]
+#[serde(rename_all = "snake_case")]
+pub enum SessionLifecycleState {
+ Active,
+ Ending,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Enum)]
+#[serde(rename_all = "snake_case")]
+pub enum SessionClientKindOutput {
+ Cli,
+ Direct,
+ Mcp,
+ PythonSdk,
+ TypescriptSdk,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Enum)]
+#[serde(rename_all = "snake_case")]
+pub enum SessionTransportOutput {
+ Cli,
+ Daemon,
+ McpStdio,
+ McpHttp,
+}
+
+/// Content-free lifecycle state safe for an ordinary agent transport.
+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Record)]
+pub struct SessionOutput {
+ /// Sanitized public label, or null for an unnamed implicit session.
+ #[schemars(required, schema_with = "nullable_string_schema")]
+ pub session: Option<String>,
+ pub implicit: bool,
+ pub state: SessionLifecycleState,
+ pub client_kind: SessionClientKindOutput,
+ pub transport: SessionTransportOutput,
+ pub cursor_visible: bool,
+ pub recording_active: bool,
+ pub idle_seconds: u64,
+ pub expires_in_seconds: u64,
+}
+
+impl ToolOutput for SessionOutput {}
+
+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Record)]
+pub struct ListSessionsOutput {
+ pub sessions: Vec<SessionOutput>,
+ #[schemars(required, schema_with = "nullable_string_schema")]
+ pub next_cursor: Option<String>,
+}
+
+impl ToolOutput for ListSessionsOutput {}
+
/// Successful structured result returned by `start_session`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Record)]
pub struct StartSessionOutput {
diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/session.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/session.rs
index 739d81a150..0790ec1822 100644
--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/session.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/session.rs
@@ -3,14 +3,15 @@
use crate::{
CursorAction, CursorSemantics, EndSessionInput, EndSessionOutput, EscalateSessionInput,
- GetSessionStateInput, Platform, SchemaMode, SessionStateOutput, StartSessionInput,
- StartSessionOutput, ToolAnnotations, ToolContract, ToolInput, ToolOutput,
+ GetSessionInput, GetSessionStateInput, ListSessionsInput, ListSessionsOutput, Platform,
+ SchemaMode, SessionOutput, SessionStateOutput, StartSessionInput, StartSessionOutput,
+ ToolAnnotations, ToolContract, ToolInput, ToolOutput,
};
const ALL_PLATFORMS: [Platform; 3] = [Platform::Macos, Platform::Windows, Platform::Linux];
pub fn contracts() -> Vec<ToolContract> {
- vec![start(), escalate(), get_state(), end()]
+ vec![start(), escalate(), get(), list(), get_state(), end()]
}
fn contract<I: ToolInput, O: ToolOutput>(
@@ -38,7 +39,7 @@ fn contract<I: ToolInput, O: ToolOutput>(
fn start() -> ToolContract {
contract::<StartSessionInput, StartSessionOutput>(
"start_session",
- "Declare a session — a named, color-coded identity for THIS agent run. Pass a stable `session` id and choose capture_scope=auto|window|desktop; the agent cursor, capture policy, per-session config, and recording all key on it, and it follows the run across any apps/windows. The cursor's color is derived from the id, so distinct runs are visually distinct. A cursor is shown only for a declared session — call this (or pass `session` on your first action) to opt in. Idempotent: re-calling with the same id just refreshes its idle-TTL. End it with `end_session` (or let the idle-TTL reclaim it). Concurrent runs/subagents each pass their own `session` to get their own cursor.",
+ "Optionally name and start a lifecycle session for this agent run. When `session` is omitted, create or return the authenticated transport lease's implicit session. Ordinary actions create that implicit session automatically, so this tool is optional. `capture_scope` is deprecated compatibility input; new callers select window or desktop modality per action. Idempotent.",
&["session.lifecycle.start", "session.capture_scope"],
ToolAnnotations {
read_only: false,
@@ -52,7 +53,7 @@ fn start() -> ToolContract {
fn escalate() -> ToolContract {
contract::<EscalateSessionInput, SessionStateOutput>(
"escalate_session",
- "Unlock the desktop phase of an auto capture-scope session after the window action ladder has been exhausted and verified. Escalation is permanent for that session and disables window-scoped tools. To recover window scope, call end_session, then start_session with a new session id.",
+ "Deprecated compatibility tool for legacy capture-scope sessions. New callers select window or desktop modality on each action. No deescalate_session tool exists.",
&["session.capture_scope.escalate"],
ToolAnnotations {
read_only: false,
@@ -66,7 +67,7 @@ fn escalate() -> ToolContract {
fn get_state() -> ToolContract {
contract::<GetSessionStateInput, SessionStateOutput>(
"get_session_state",
- "Read the live session's capture policy and effective scope.",
+ "Deprecated compatibility alias that reads a live legacy session's capture policy. Use get_session for lifecycle state.",
&["session.capture_scope.read"],
ToolAnnotations {
read_only: true,
@@ -77,10 +78,38 @@ fn get_state() -> ToolContract {
)
}
+fn get() -> ToolContract {
+ contract::<GetSessionInput, SessionOutput>(
+ "get_session",
+ "Read content-free lifecycle, cursor, recording, and idle status for one session visible to this authenticated transport. Omit `session` to inspect its implicit session.",
+ &["session.lifecycle.read"],
+ ToolAnnotations {
+ read_only: true,
+ destructive: false,
+ idempotent: true,
+ open_world: false,
+ },
+ )
+}
+
+fn list() -> ToolContract {
+ contract::<ListSessionsInput, ListSessionsOutput>(
+ "list_sessions",
+ "List content-free lifecycle summaries attached to this authenticated transport lease. It does not enumerate other callers' sessions.",
+ &["session.lifecycle.list"],
+ ToolAnnotations {
+ read_only: true,
+ destructive: false,
+ idempotent: true,
+ open_world: false,
+ },
+ )
+}
+
fn end() -> ToolContract {
contract::<EndSessionInput, EndSessionOutput>(
"end_session",
- "End a session declared with `start_session`: removes its agent cursor, stops any recording it owns, and clears its per-session config. Call this when a run finishes so its cursor doesn't linger (otherwise the idle-TTL reclaims it after a period of inactivity). Idempotent.",
+ "End one visible lifecycle session and run its cursor, recording, configuration, and other cleanup hooks exactly once. Omit `session` to end the authenticated transport's implicit session. Idempotent.",
&["session.lifecycle.end"],
ToolAnnotations {
read_only: false,
diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/verification.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/verification.rs
index bab727b38b..aa13ab34f0 100644
--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/verification.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/verification.rs
@@ -156,7 +156,8 @@ pub struct VerifyStateInput {
/// One to eight predicates, combined with logical AND.
#[schemars(length(min = 1, max = 8))]
pub expect: Vec<StatePredicate>,
- /// Optional session id for capture-scope and authorization continuity.
+ /// Optional public session label for lifecycle continuity. It never selects
+ /// capture modality or authorization.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(schema_with = "string_schema")]
pub session: Option<String>,
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/action_target.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/action_target.rs
new file mode 100644
index 0000000000..24c80c3785
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/action_target.rs
@@ -0,0 +1,146 @@
+//! Per-call target normalization for lifecycle-independent capture modality.
+
+use crate::protocol::ToolResult;
+use serde_json::{json, Value};
+
+const TARGETED_TOOLS: &[&str] = &[
+ "move_cursor",
+ "click",
+ "drag",
+ "scroll",
+ "type_text",
+ "press_key",
+ "hotkey",
+];
+
+pub fn supports_typed_target(tool_name: &str) -> bool {
+ TARGETED_TOOLS.contains(&tool_name)
+}
+
+fn invalid_target(message: impl Into<String>) -> ToolResult {
+ ToolResult::error(message.into()).with_structured(json!({
+ "code": "invalid_action_target",
+ }))
+}
+
+/// Normalize the generated tagged union into the legacy flat fields consumed
+/// by the current thin platform adapters. This runs once at the canonical
+/// dispatch boundary before authorization, so policy/resource checks and the
+/// platform worker see the same exact target.
+pub fn normalize_action_target(tool_name: &str, args: &mut Value) -> Result<(), ToolResult> {
+ let Some(object) = args.as_object_mut() else {
+ return Ok(());
+ };
+ let Some(target) = object.remove("target") else {
+ if object.get("scope").and_then(Value::as_str) == Some("desktop")
+ && (object.contains_key("pid") || object.contains_key("window_id"))
+ {
+ return Err(invalid_target(
+ "desktop scope cannot be combined with pid or window_id",
+ ));
+ }
+ return Ok(());
+ };
+ if !supports_typed_target(tool_name) {
+ return Err(invalid_target(format!(
+ "{tool_name} does not accept a per-call target"
+ )));
+ }
+ if object.contains_key("scope")
+ || object.contains_key("pid")
+ || object.contains_key("window_id")
+ {
+ return Err(invalid_target(
+ "target cannot be combined with legacy scope, pid, or window_id fields",
+ ));
+ }
+ let Some(target) = target.as_object() else {
+ return Err(invalid_target("target must be an object"));
+ };
+ match target.get("kind").and_then(Value::as_str) {
+ Some("window") => {
+ let pid = target
+ .get("pid")
+ .and_then(Value::as_u64)
+ .filter(|pid| *pid > 0 && *pid <= u32::MAX as u64)
+ .ok_or_else(|| invalid_target("window target requires a positive 32-bit pid"))?;
+ let window_id = target
+ .get("window_id")
+ .and_then(Value::as_u64)
+ .filter(|window_id| *window_id > 0)
+ .ok_or_else(|| invalid_target("window target requires a positive window_id"))?;
+ if target.len() != 3 {
+ return Err(invalid_target(
+ "window target accepts only kind, pid, and window_id",
+ ));
+ }
+ object.insert("scope".into(), Value::String("window".into()));
+ object.insert("pid".into(), Value::Number(pid.into()));
+ object.insert("window_id".into(), Value::Number(window_id.into()));
+ }
+ Some("desktop") => {
+ let display_id = target
+ .get("display_id")
+ .and_then(Value::as_str)
+ .filter(|display_id| !display_id.is_empty())
+ .ok_or_else(|| invalid_target("desktop target requires display_id"))?;
+ if target.len() != 2 {
+ return Err(invalid_target(
+ "desktop target accepts only kind and display_id",
+ ));
+ }
+ if display_id != "primary" {
+ return Err(invalid_target(
+ "this release supports only display_id='primary'",
+ ));
+ }
+ object.insert("scope".into(), Value::String("desktop".into()));
+ }
+ Some(_) => return Err(invalid_target("target.kind must be window or desktop")),
+ None => return Err(invalid_target("target.kind is required")),
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn exact_targets_normalize_to_one_unambiguous_legacy_shape() {
+ let mut window = json!({
+ "x": 1,
+ "y": 2,
+ "target": {"kind": "window", "pid": 7, "window_id": 9}
+ });
+ normalize_action_target("click", &mut window).unwrap();
+ assert_eq!(window["scope"], "window");
+ assert_eq!(window["pid"], 7);
+ assert_eq!(window["window_id"], 9);
+ assert!(window.get("target").is_none());
+
+ let mut desktop = json!({
+ "x": 1,
+ "y": 2,
+ "target": {"kind": "desktop", "display_id": "primary"}
+ });
+ normalize_action_target("click", &mut desktop).unwrap();
+ assert_eq!(desktop["scope"], "desktop");
+ assert!(desktop.get("pid").is_none());
+ }
+
+ #[test]
+ fn ambiguous_or_unsupported_targets_fail_closed() {
+ for mut args in [
+ json!({
+ "scope": "desktop",
+ "target": {"kind": "desktop", "display_id": "primary"}
+ }),
+ json!({"scope": "desktop", "pid": 7}),
+ json!({"target": {"kind": "desktop", "display_id": "secondary"}}),
+ json!({"target": {"kind": "window", "pid": 7, "window_id": 0}}),
+ ] {
+ assert!(normalize_action_target("click", &mut args).is_err());
+ }
+ }
+}
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 ef5437ac6f..591bd9a516 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
@@ -822,6 +822,8 @@ pub fn advertised_risk_for(tool: &str) -> RiskAssessment {
"get_screen_size"
| "get_cursor_position"
| "get_config"
+ | "get_session"
+ | "list_sessions"
| "get_session_state"
| "get_agent_cursor_state"
| "get_recording_state"
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 6933c5b637..44f5b1ab8b 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
@@ -90,7 +90,7 @@ fn schema_ref() -> Value {
fn schema_session() -> Value {
json!({
"type": "string",
- "description": "Stable caller-declared session id. Browser targets, tabs, and refs are scoped to this session."
+ "description": "Optional public session label. Browser targets, tabs, and refs use the authenticated transport's implicit lifecycle session when omitted."
})
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs
index 19d8d1c0b7..1769dee61c 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs
@@ -238,13 +238,18 @@ impl ScopeViolation {
}
}
-/// Enforce the modality for a public session. A first non-lifecycle action
-/// implicitly starts that session in `auto`, matching the existing cursor and
-/// recording lifecycle behavior.
+/// Enforce modality only for a session that explicitly opted into the
+/// deprecated capture-scope compatibility contract. Lifecycle-only explicit
+/// and implicit sessions select modality per call and carry no capture state.
pub fn enforce_tool(tool_name: &str, args: &Value) -> Result<(), ScopeViolation> {
if matches!(
tool_name,
- "start_session" | "end_session" | "escalate_session" | "get_session_state"
+ "start_session"
+ | "end_session"
+ | "escalate_session"
+ | "get_session"
+ | "list_sessions"
+ | "get_session_state"
) {
return Ok(());
}
@@ -255,11 +260,9 @@ pub fn enforce_tool(tool_name: &str, args: &Value) -> Result<(), ScopeViolation>
else {
return Ok(());
};
- let (state, _) = bind_session(session, None).map_err(|_| ScopeViolation {
- code: "session_ended",
- message: format!("session '{session}' has ended"),
- state: SessionCaptureScope::new(CaptureScopePolicy::Auto),
- })?;
+ let Some(state) = get_session(session) else {
+ return Ok(());
+ };
match (state.effective_scope(), tool_scope(tool_name, args)) {
(_, ToolScope::Unscoped)
| (EffectiveCaptureScope::Window, ToolScope::Window)
@@ -537,7 +540,7 @@ mod tests {
}
#[test]
- fn end_racing_escalation_never_resurrects_scope_state() {
+ fn end_racing_escalation_never_resurrects_legacy_scope_state() {
use std::sync::{Arc, Barrier};
let session = fresh("end-escalate-race");
@@ -565,11 +568,9 @@ mod tests {
assert!(crate::session::is_session_ended(&session));
assert!(get_session(&session).is_none());
- assert_eq!(
- enforce_tool("get_window_state", &json!({"session": session}))
- .unwrap_err()
- .code,
- "session_ended"
+ assert!(
+ enforce_tool("get_window_state", &json!({"session": session})).is_ok(),
+ "the compatibility helper must not recreate cleared capture state; the canonical lifecycle gate rejects the ended session"
);
assert!(crate::session::revive_session(&session));
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
index fca981562b..71a0cc7c6b 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
@@ -46,6 +46,7 @@ pub fn parent_liveness_stdin_enabled() -> bool {
}
pub mod action_record;
+pub mod action_target;
pub mod authorization;
pub mod background_input;
pub mod browser;
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 3aaae6ac81..830720d046 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
@@ -27,7 +27,36 @@ use std::time::{Duration, Instant};
use cua_driver_contract::{CaptureScope, EscalationReason};
-type SessionEndHook = Arc<dyn Fn(&str) + Send + Sync>;
+pub const DEFAULT_SESSION_IDLE_TTL: Duration = Duration::from_secs(5 * 60);
+
+type SessionEndHook = Arc<dyn Fn(&str) -> Result<(), String> + Send + Sync>;
+type SessionReviveHook = Arc<dyn Fn(&str) + Send + Sync>;
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SessionCleanupFailure {
+ pub hook: String,
+ pub error: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SessionCleanupReport {
+ pub complete: bool,
+ pub in_progress: bool,
+ pub failures: Vec<SessionCleanupFailure>,
+}
+
+#[derive(Clone)]
+struct RegisteredSessionEndHook {
+ name: String,
+ callback: SessionEndHook,
+}
+
+struct SessionCleanupProgress {
+ hooks: Vec<(u64, RegisteredSessionEndHook)>,
+ completed: HashSet<u64>,
+ failures: Vec<SessionCleanupFailure>,
+ running: bool,
+}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionDeclaration {
@@ -43,6 +72,12 @@ pub enum SessionEndReason {
Unknown,
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CaptureModality {
+ Window,
+ Desktop,
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionTransport {
Cli,
@@ -63,6 +98,18 @@ pub enum SessionClientKind {
TypescriptSdk,
}
+pub fn infer_transport_metadata(owner: &str) -> (SessionTransport, SessionClientKind) {
+ if owner.contains(":http-") {
+ (SessionTransport::McpHttp, SessionClientKind::Mcp)
+ } else if owner.contains(":mcp-") {
+ (SessionTransport::McpStdio, SessionClientKind::Mcp)
+ } else if owner.contains(":cli-") {
+ (SessionTransport::Cli, SessionClientKind::Cli)
+ } else {
+ (SessionTransport::Daemon, SessionClientKind::Direct)
+ }
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SessionStartObservation {
pub declaration: SessionDeclaration,
@@ -91,6 +138,9 @@ pub enum CursorThemeCategory {
pub struct CursorOutcomeObservation {
pub observed: bool,
pub enabled: bool,
+ /// True only when the platform render state currently reports visible
+ /// pixels for this exact session cursor.
+ pub visible: bool,
pub theme: CursorThemeCategory,
pub motion_customized: bool,
pub active_cursor_count: usize,
@@ -101,6 +151,7 @@ pub struct CursorOutcomeObservation {
pub fn bounded_cursor_outcome(
observed: bool,
enabled: bool,
+ visible: bool,
theme_id: Option<&str>,
motion_customized: bool,
active_cursor_count: usize,
@@ -116,6 +167,7 @@ pub fn bounded_cursor_outcome(
CursorOutcomeObservation {
observed,
enabled: observed && enabled,
+ visible: observed && enabled && visible,
theme,
motion_customized: observed && motion_customized,
active_cursor_count,
@@ -135,6 +187,7 @@ pub trait SessionObserver: Send + Sync + 'static {
session_id: &str,
transport: SessionTransport,
computer_action: bool,
+ capture_modality: Option<CaptureModality>,
escalation_reason: Option<EscalationReason>,
outcome: &crate::server::ToolCompletionObservation,
);
@@ -150,6 +203,10 @@ static SESSION_OBSERVER: OnceLock<Arc<dyn SessionObserver>> = OnceLock::new();
type CursorOutcomeReader = Arc<dyn Fn(&str) -> CursorOutcomeObservation + Send + Sync>;
static CURSOR_OUTCOME_READERS: OnceLock<Mutex<HashMap<u64, CursorOutcomeReader>>> = OnceLock::new();
static NEXT_CURSOR_OUTCOME_READER_ID: AtomicU64 = AtomicU64::new(1);
+type RecordingStateReader = Arc<dyn Fn(&str) -> bool + Send + Sync>;
+static RECORDING_STATE_READERS: OnceLock<Mutex<HashMap<u64, RecordingStateReader>>> =
+ OnceLock::new();
+static NEXT_RECORDING_STATE_READER_ID: AtomicU64 = AtomicU64::new(1);
pub fn set_session_observer(observer: Arc<dyn SessionObserver>) -> bool {
SESSION_OBSERVER.set(observer).is_ok()
@@ -191,6 +248,55 @@ impl Drop for CursorOutcomeReaderRegistration {
}
}
+pub fn register_scoped_recording_state_reader(
+ reader: RecordingStateReader,
+) -> RecordingStateReaderRegistration {
+ let id = NEXT_RECORDING_STATE_READER_ID.fetch_add(1, Ordering::Relaxed);
+ RECORDING_STATE_READERS
+ .get_or_init(|| Mutex::new(HashMap::new()))
+ .lock()
+ .unwrap()
+ .insert(id, reader);
+ RecordingStateReaderRegistration { id }
+}
+
+pub struct RecordingStateReaderRegistration {
+ id: u64,
+}
+
+impl Drop for RecordingStateReaderRegistration {
+ fn drop(&mut self) {
+ if let Some(readers) = RECORDING_STATE_READERS.get() {
+ readers.lock().unwrap().remove(&self.id);
+ }
+ }
+}
+
+pub fn cursor_visible(session_id: &str) -> bool {
+ CURSOR_OUTCOME_READERS
+ .get()
+ .map(|readers| {
+ readers.lock().unwrap().values().any(|reader| {
+ let outcome = reader(session_id);
+ outcome.visible
+ })
+ })
+ .unwrap_or(false)
+}
+
+pub fn recording_active(session_id: &str) -> bool {
+ RECORDING_STATE_READERS
+ .get()
+ .map(|readers| {
+ readers
+ .lock()
+ .unwrap()
+ .values()
+ .any(|reader| reader(session_id))
+ })
+ .unwrap_or(false)
+}
+
/// Private per-call context. The raw caller session id never crosses into a
/// serialized observation; it is retained only until the bounded completion
/// callback updates the process-local aggregate.
@@ -198,6 +304,7 @@ pub struct SessionToolContext {
session_id: String,
transport: SessionTransport,
computer_action: bool,
+ capture_modality: Option<CaptureModality>,
escalation_reason: Option<EscalationReason>,
}
@@ -208,6 +315,7 @@ impl SessionToolContext {
&self.session_id,
self.transport,
self.computer_action,
+ self.capture_modality,
self.escalation_reason,
outcome,
);
@@ -215,18 +323,476 @@ impl SessionToolContext {
}
}
-static SESSION_END_HOOKS: OnceLock<Mutex<HashMap<u64, SessionEndHook>>> = OnceLock::new();
+static SESSION_END_HOOKS: OnceLock<Mutex<HashMap<u64, RegisteredSessionEndHook>>> = OnceLock::new();
static NEXT_SESSION_END_HOOK_ID: AtomicU64 = AtomicU64::new(1);
-
-/// Last-activity timestamp per live session id. A session is "touched" every
-/// time a tool call carries its explicit `session` id (see the daemon boundary
-/// in `serve.rs`). The idle-TTL sweep ([`evict_idle`]) ends sessions that
-/// haven't been touched within the TTL — this is the cleanup path that replaces
-/// connection-EOF reaping now that a session is a caller-declared identity, not
-/// a per-MCP-connection one. `"default"` and empty ids are never tracked (they
-/// are the anonymous, cursor-less fallback).
+static SESSION_CLEANUP_PROGRESS: OnceLock<Mutex<HashMap<String, SessionCleanupProgress>>> =
+ OnceLock::new();
+static SESSION_REVIVE_HOOKS: OnceLock<Mutex<HashMap<u64, SessionReviveHook>>> = OnceLock::new();
+static NEXT_SESSION_REVIVE_HOOK_ID: AtomicU64 = AtomicU64::new(1);
+
+/// Last-activity timestamp per live lifecycle session. Only an admitted,
+/// session-requiring call that reaches dispatch refreshes this timestamp.
+/// Transport close remains an immediate cleanup path; idle eviction is the
+/// crash and inactivity fallback. `"default"` and empty ids are never tracked.
static SESSION_ACTIVITY: OnceLock<Mutex<HashMap<String, Instant>>> = OnceLock::new();
+#[derive(Debug, Clone)]
+struct LifecycleRecord {
+ public_label: Option<String>,
+ implicit: bool,
+ owner_transport: String,
+ transport: SessionTransport,
+ client_kind: SessionClientKind,
+ started_at: Instant,
+ /// Trusted host override. Ordinary sessions use the runtime sweep's
+ /// default TTL so tests and process-level configuration can still supply
+ /// that fallback.
+ idle_ttl: Option<Duration>,
+ in_flight: usize,
+ pending_end: Option<SessionEndReason>,
+}
+
+static LIFECYCLE_RECORDS: OnceLock<Mutex<HashMap<String, LifecycleRecord>>> = OnceLock::new();
+
+fn lifecycle_records() -> &'static Mutex<HashMap<String, LifecycleRecord>> {
+ LIFECYCLE_RECORDS.get_or_init(|| Mutex::new(HashMap::new()))
+}
+
+#[derive(Debug, Clone)]
+pub struct LifecycleSessionSnapshot {
+ pub runtime_id: String,
+ pub public_label: Option<String>,
+ pub implicit: bool,
+ pub transport: SessionTransport,
+ pub client_kind: SessionClientKind,
+ pub owner_transport: String,
+ pub ending: bool,
+ pub started_for: Duration,
+ pub idle: Duration,
+ pub expires_in: Duration,
+}
+
+/// RAII protection for one admitted session-requiring dispatch. Idle eviction
+/// cannot end the session while this guard is alive. Dropping it refreshes the
+/// idle clock at platform-dispatch completion and completes any end that raced
+/// the call.
+pub struct SessionDispatchGuard {
+ session_id: String,
+}
+
+impl Drop for SessionDispatchGuard {
+ fn drop(&mut self) {
+ let pending = {
+ let mut records = lifecycle_records().lock().unwrap();
+ let Some(record) = records.get_mut(&self.session_id) else {
+ return;
+ };
+ record.in_flight = record.in_flight.saturating_sub(1);
+ activity()
+ .lock()
+ .unwrap()
+ .insert(self.session_id.clone(), Instant::now());
+ (record.in_flight == 0)
+ .then(|| record.pending_end.take())
+ .flatten()
+ };
+ if let Some(reason) = pending {
+ finish_session_end(&self.session_id, reason);
+ }
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn begin_session_dispatch(
+ session_id: &str,
+ public_label: Option<&str>,
+ owner_transport: &str,
+ implicit: bool,
+ transport: SessionTransport,
+ client_kind: SessionClientKind,
+) -> Result<SessionDispatchGuard, &'static str> {
+ begin_session_dispatch_inner(
+ session_id,
+ public_label,
+ owner_transport,
+ implicit,
+ transport,
+ client_kind,
+ None,
+ )
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn begin_session_dispatch_with_ttl(
+ session_id: &str,
+ public_label: Option<&str>,
+ owner_transport: &str,
+ implicit: bool,
+ transport: SessionTransport,
+ client_kind: SessionClientKind,
+ idle_ttl: Duration,
+) -> Result<SessionDispatchGuard, &'static str> {
+ begin_session_dispatch_inner(
+ session_id,
+ public_label,
+ owner_transport,
+ implicit,
+ transport,
+ client_kind,
+ Some(idle_ttl),
+ )
+}
+
+#[allow(clippy::too_many_arguments)]
+fn begin_session_dispatch_inner(
+ session_id: &str,
+ public_label: Option<&str>,
+ owner_transport: &str,
+ implicit: bool,
+ transport: SessionTransport,
+ client_kind: SessionClientKind,
+ idle_ttl: Option<Duration>,
+) -> Result<SessionDispatchGuard, &'static str> {
+ if !is_trackable(session_id) {
+ return Err("session has ended");
+ }
+ let now = Instant::now();
+ {
+ // Keep tombstone admission and live-record insertion in one critical
+ // section. Otherwise an end could land between the old pre-check and
+ // insertion, leaving a tombstoned record that was silently recreated
+ // by a racing first action.
+ let ended = ended_sessions().lock().unwrap();
+ if ended.contains_key(session_id) {
+ return Err("session has ended");
+ }
+ let mut records = lifecycle_records().lock().unwrap();
+ let record = records
+ .entry(session_id.to_owned())
+ .or_insert_with(|| LifecycleRecord {
+ public_label: public_label.map(str::to_owned),
+ implicit,
+ owner_transport: owner_transport.to_owned(),
+ transport,
+ client_kind,
+ started_at: now,
+ idle_ttl,
+ in_flight: 0,
+ pending_end: None,
+ });
+ if record.owner_transport != owner_transport {
+ return Err("session is not available to this transport");
+ }
+ if record.pending_end.is_some() {
+ return Err("session is ending");
+ }
+ if idle_ttl.is_some() {
+ record.idle_ttl = idle_ttl;
+ }
+ record.in_flight += 1;
+ }
+ activity()
+ .lock()
+ .unwrap()
+ .insert(session_id.to_owned(), now);
+ Ok(SessionDispatchGuard {
+ session_id: session_id.to_owned(),
+ })
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn activate_session(
+ session_id: &str,
+ public_label: Option<&str>,
+ owner_transport: &str,
+ implicit: bool,
+ transport: SessionTransport,
+ client_kind: SessionClientKind,
+) -> Result<(), &'static str> {
+ activate_session_inner(
+ session_id,
+ public_label,
+ owner_transport,
+ implicit,
+ transport,
+ client_kind,
+ None,
+ )
+}
+
+#[allow(clippy::too_many_arguments)]
+pub fn activate_session_with_ttl(
+ session_id: &str,
+ public_label: Option<&str>,
+ owner_transport: &str,
+ implicit: bool,
+ transport: SessionTransport,
+ client_kind: SessionClientKind,
+ idle_ttl: Duration,
+) -> Result<(), &'static str> {
+ activate_session_inner(
+ session_id,
+ public_label,
+ owner_transport,
+ implicit,
+ transport,
+ client_kind,
+ Some(idle_ttl),
+ )
+}
+
+#[allow(clippy::too_many_arguments)]
+fn activate_session_inner(
+ session_id: &str,
+ public_label: Option<&str>,
+ owner_transport: &str,
+ implicit: bool,
+ transport: SessionTransport,
+ client_kind: SessionClientKind,
+ idle_ttl: Option<Duration>,
+) -> Result<(), &'static str> {
+ let now = Instant::now();
+ {
+ let mut records = lifecycle_records().lock().unwrap();
+ if let Some(record) = records.get_mut(session_id) {
+ if record.owner_transport != owner_transport {
+ return Err("session is not available to this transport");
+ }
+ if record.pending_end.is_some() {
+ return Err("session is ending");
+ }
+ if idle_ttl.is_some() {
+ record.idle_ttl = idle_ttl;
+ }
+ } else {
+ records.insert(
+ session_id.to_owned(),
+ LifecycleRecord {
+ public_label: public_label.map(str::to_owned),
+ implicit,
+ owner_transport: owner_transport.to_owned(),
+ transport,
+ client_kind,
+ started_at: now,
+ idle_ttl,
+ in_flight: 0,
+ pending_end: None,
+ },
+ );
+ }
+ }
+ activity()
+ .lock()
+ .unwrap()
+ .insert(session_id.to_owned(), now);
+ Ok(())
+}
+
+/// Atomically declare a lifecycle episode for one authenticated transport.
+///
+/// Unlike calling `revive_session_for_owner` and `activate_session` in two
+/// steps, this does not leave a gap where another transport can claim a
+/// recycled public label after its tombstone is cleared. Cleanup is completed
+/// before the transition, then the tombstone removal and live owner binding
+/// happen under one lock order.
+#[allow(clippy::too_many_arguments)]
+pub fn activate_or_revive_session_for_owner(
+ session_id: &str,
+ public_label: Option<&str>,
+ owner_transport: &str,
+ implicit: bool,
+ transport: SessionTransport,
+ client_kind: SessionClientKind,
+ idle_ttl: Option<Duration>,
+) -> Result<bool, &'static str> {
+ if !is_trackable(session_id) {
+ return Err("session is not available to this transport");
+ }
+
+ let needs_cleanup = {
+ let ended = ended_sessions().lock().unwrap();
+ match ended.get(session_id) {
+ Some(Some(owner)) if owner != owner_transport => {
+ return Err("session is not available to this transport");
+ }
+ Some(None) if owner_transport != session_id => {
+ return Err("session is not available to this transport");
+ }
+ Some(_) => true,
+ None => false,
+ }
+ };
+ if needs_cleanup && !retry_session_cleanup(session_id).complete {
+ return Err("session cleanup is incomplete; retry end_session before revival");
+ }
+
+ let now = Instant::now();
+ let revived = {
+ let mut ended = ended_sessions().lock().unwrap();
+ let revived = match ended.get(session_id) {
+ Some(Some(owner)) if owner != owner_transport => {
+ return Err("session is not available to this transport");
+ }
+ Some(None) if owner_transport != session_id => {
+ return Err("session is not available to this transport");
+ }
+ Some(_) => true,
+ None => false,
+ };
+
+ let mut records = lifecycle_records().lock().unwrap();
+ if let Some(record) = records.get_mut(session_id) {
+ if record.owner_transport != owner_transport || record.pending_end.is_some() {
+ return Err("session is not available to this transport");
+ }
+ if idle_ttl.is_some() {
+ record.idle_ttl = idle_ttl;
+ }
+ } else {
+ records.insert(
+ session_id.to_owned(),
+ LifecycleRecord {
+ public_label: public_label.map(str::to_owned),
+ implicit,
+ owner_transport: owner_transport.to_owned(),
+ transport,
+ client_kind,
+ started_at: now,
+ idle_ttl,
+ in_flight: 0,
+ pending_end: None,
+ },
+ );
+ }
+ if revived {
+ ended.remove(session_id);
+ }
+ revived
+ };
+ activity()
+ .lock()
+ .unwrap()
+ .insert(session_id.to_owned(), now);
+ Ok(revived)
+}
+
+pub fn session_snapshot(
+ session_id: &str,
+ owner_transport: &str,
+ ttl: Duration,
+) -> Option<LifecycleSessionSnapshot> {
+ let record = lifecycle_records().lock().unwrap().get(session_id)?.clone();
+ if record.owner_transport != owner_transport {
+ return None;
+ }
+ let idle = session_idle_duration(session_id).unwrap_or_default();
+ let ttl = record.idle_ttl.unwrap_or(ttl);
+ Some(LifecycleSessionSnapshot {
+ runtime_id: session_id.to_owned(),
+ public_label: record.public_label.clone(),
+ implicit: record.implicit,
+ transport: record.transport,
+ client_kind: record.client_kind,
+ owner_transport: record.owner_transport.clone(),
+ ending: record.pending_end.is_some(),
+ started_for: record.started_at.elapsed(),
+ idle,
+ expires_in: ttl.saturating_sub(idle),
+ })
+}
+
+fn session_owner_matches(session_id: &str, owner_transport: &str) -> bool {
+ if lifecycle_records()
+ .lock()
+ .unwrap()
+ .get(session_id)
+ .is_some_and(|record| record.owner_transport == owner_transport)
+ {
+ return true;
+ }
+ ended_sessions()
+ .lock()
+ .unwrap()
+ .get(session_id)
+ .is_some_and(|owner| owner.as_deref() == Some(owner_transport))
+}
+
+/// End a lifecycle episode only when it belongs to the authenticated
+/// transport. Returns `false` for unknown and foreign ids alike so callers can
+/// provide one non-enumerating response.
+pub fn end_session_for_owner(session_id: &str, owner_transport: &str) -> bool {
+ if !session_owner_matches(session_id, owner_transport) {
+ return false;
+ }
+ end_session(session_id);
+ true
+}
+
+pub fn list_session_snapshots(
+ owner_transport: &str,
+ ttl: Duration,
+) -> Vec<LifecycleSessionSnapshot> {
+ let mut ids = lifecycle_records()
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|(_, record)| record.owner_transport == owner_transport)
+ .map(|(id, record)| (record.started_at, id.clone()))
+ .collect::<Vec<_>>();
+ ids.sort_by_key(|(started, id)| (*started, id.clone()));
+ ids.into_iter()
+ .filter_map(|(_, id)| session_snapshot(&id, owner_transport, ttl))
+ .collect()
+}
+
+/// Trusted local-host view scoped to one runtime generation. This is not used
+/// by agent tools; the operator adapter applies redaction before serialization.
+pub fn list_session_snapshots_with_prefix(
+ runtime_prefix: &str,
+ ttl: Duration,
+) -> Vec<LifecycleSessionSnapshot> {
+ let mut records = lifecycle_records()
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|(id, _)| id.starts_with(runtime_prefix))
+ .map(|(id, record)| (record.started_at, id.clone(), record.clone()))
+ .collect::<Vec<_>>();
+ records.sort_by_key(|(started, id, _)| (*started, id.clone()));
+ records
+ .into_iter()
+ .map(|(_, runtime_id, record)| {
+ let idle = session_idle_duration(&runtime_id).unwrap_or_default();
+ LifecycleSessionSnapshot {
+ runtime_id,
+ public_label: record.public_label,
+ implicit: record.implicit,
+ transport: record.transport,
+ client_kind: record.client_kind,
+ owner_transport: record.owner_transport,
+ ending: record.pending_end.is_some(),
+ started_for: record.started_at.elapsed(),
+ idle,
+ expires_in: record.idle_ttl.unwrap_or(ttl).saturating_sub(idle),
+ }
+ })
+ .collect()
+}
+
+pub fn end_sessions_for_owner(owner_transport: &str, reason: SessionEndReason) -> usize {
+ let ids = lifecycle_records()
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|(_, record)| record.owner_transport == owner_transport)
+ .map(|(id, _)| id.clone())
+ .collect::<Vec<_>>();
+ for id in &ids {
+ end_session_with_reason(id, reason);
+ }
+ ids.len()
+}
+
fn activity() -> &'static Mutex<HashMap<String, Instant>> {
SESSION_ACTIVITY.get_or_init(|| Mutex::new(HashMap::new()))
}
@@ -249,7 +815,7 @@ pub fn begin_tool_call(
begin_tool_call_with_state(tool_name, args, known_tool, transport, client_kind, None)
}
-/// Begin observation with a runtime-owner-provided view of public session
+/// Begin observation with a runtime-owner-provided view of session
/// state. Runtime owners use this seam because their mutable scope and
/// tombstone state is keyed by a private runtime generation, while telemetry
/// must continue to report the caller's stable public session label.
@@ -264,10 +830,11 @@ pub fn begin_tool_call_with_state(
if !known_tool {
return None;
}
- let session_id = args
- .get("session")
- .and_then(serde_json::Value::as_str)
- .filter(|id| is_trackable(id))?;
+ let session_id = ["session", "_session_id"].into_iter().find_map(|key| {
+ args.get(key)
+ .and_then(serde_json::Value::as_str)
+ .filter(|id| is_trackable(id))
+ })?;
let is_start = tool_name == "start_session";
let is_end = tool_name == "end_session";
let ended = observed_state
@@ -293,6 +860,7 @@ pub fn begin_tool_call_with_state(
.then(|| args.get("reason").cloned())
.flatten()
.and_then(|value| serde_json::from_value(value).ok());
+ let capture_modality = capture_modality_for(tool_name, args);
if !is_end {
if let Some(observer) = SESSION_OBSERVER.get() {
observer.on_session_started(
@@ -319,10 +887,47 @@ pub fn begin_tool_call_with_state(
tool_name,
crate::server::tool_operation(tool_name, Some(args)),
),
+ capture_modality,
escalation_reason,
})
}
+fn capture_modality_for(tool_name: &str, args: &serde_json::Value) -> Option<CaptureModality> {
+ if let Some(kind) = args
+ .get("target")
+ .and_then(serde_json::Value::as_object)
+ .and_then(|target| target.get("kind"))
+ .and_then(serde_json::Value::as_str)
+ {
+ return match kind {
+ "window" => Some(CaptureModality::Window),
+ "desktop" => Some(CaptureModality::Desktop),
+ _ => None,
+ };
+ }
+ if let Some(scope) = args.get("scope").and_then(serde_json::Value::as_str) {
+ return match scope {
+ "window" => Some(CaptureModality::Window),
+ "desktop" => Some(CaptureModality::Desktop),
+ _ => None,
+ };
+ }
+ if args.get("pid").is_some_and(serde_json::Value::is_number)
+ || args
+ .get("window_id")
+ .is_some_and(serde_json::Value::is_number)
+ {
+ return Some(CaptureModality::Window);
+ }
+ match tool_name {
+ "get_window_state" => Some(CaptureModality::Window),
+ "get_desktop_state" | "get_screen_size" | "get_cursor_position" => {
+ Some(CaptureModality::Desktop)
+ }
+ _ => None,
+ }
+}
+
/// Session ids that have already had their `session_end` fired. Dedupes the
/// control-connection EOF teardown (the reaper) against any stray legacy
/// `session_end` method that a mixed-version (new proxy / old proxy) rollout
@@ -330,7 +935,7 @@ pub fn begin_tool_call_with_state(
/// be idempotent because the overlay Remove + recording stop must run exactly
/// 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();
+static ENDED_SESSIONS: OnceLock<Mutex<HashMap<String, Option<String>>>> = OnceLock::new();
/// Runtime generations that have received terminal revoke-all.
///
/// This latch is intentionally independent of grants and public session
@@ -338,12 +943,20 @@ static ENDED_SESSIONS: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
/// 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>> {
+fn hooks() -> &'static Mutex<HashMap<u64, RegisteredSessionEndHook>> {
SESSION_END_HOOKS.get_or_init(|| Mutex::new(HashMap::new()))
}
-fn ended_sessions() -> &'static Mutex<HashSet<String>> {
- ENDED_SESSIONS.get_or_init(|| Mutex::new(HashSet::new()))
+fn cleanup_progress() -> &'static Mutex<HashMap<String, SessionCleanupProgress>> {
+ SESSION_CLEANUP_PROGRESS.get_or_init(|| Mutex::new(HashMap::new()))
+}
+
+fn revive_hooks() -> &'static Mutex<HashMap<u64, SessionReviveHook>> {
+ SESSION_REVIVE_HOOKS.get_or_init(|| Mutex::new(HashMap::new()))
+}
+
+fn ended_sessions() -> &'static Mutex<HashMap<String, Option<String>>> {
+ ENDED_SESSIONS.get_or_init(|| Mutex::new(HashMap::new()))
}
fn suspended_runtime_scopes() -> &'static Mutex<HashSet<String>> {
@@ -376,7 +989,7 @@ pub fn forget_suspended_runtime_scope(runtime_scope: &str) -> bool {
.remove(runtime_scope)
}
-fn public_session_label(session_id: &str) -> &str {
+pub(crate) fn public_session_label(session_id: &str) -> &str {
let Some(rest) = session_id.strip_prefix("__cua_runtime_") else {
return session_id;
};
@@ -405,9 +1018,27 @@ pub fn register_session_end_hook(hook: impl Fn(&str) + Send + Sync + 'static) {
/// platform and browser hooks.
pub fn register_scoped_session_end_hook(
hook: impl Fn(&str) + Send + Sync + 'static,
+) -> SessionEndHookRegistration {
+ register_scoped_fallible_session_end_hook("session_state", move |session_id| {
+ hook(session_id);
+ Ok(())
+ })
+}
+
+/// Register a named cleanup hook whose failure is retained for bounded retry.
+/// A successful hook is never run twice for the same lifecycle episode.
+pub fn register_scoped_fallible_session_end_hook(
+ name: impl Into<String>,
+ hook: impl Fn(&str) -> Result<(), String> + Send + Sync + 'static,
) -> SessionEndHookRegistration {
let id = NEXT_SESSION_END_HOOK_ID.fetch_add(1, Ordering::Relaxed);
- hooks().lock().unwrap().insert(id, Arc::new(hook));
+ hooks().lock().unwrap().insert(
+ id,
+ RegisteredSessionEndHook {
+ name: name.into(),
+ callback: Arc::new(hook),
+ },
+ );
SessionEndHookRegistration { id }
}
@@ -421,6 +1052,70 @@ impl Drop for SessionEndHookRegistration {
}
}
+/// Register a runtime-owned callback for a successful explicit revival.
+/// Dropping the returned guard removes the callback.
+pub fn register_scoped_session_revive_hook(
+ hook: impl Fn(&str) + Send + Sync + 'static,
+) -> SessionReviveHookRegistration {
+ let id = NEXT_SESSION_REVIVE_HOOK_ID.fetch_add(1, Ordering::Relaxed);
+ revive_hooks().lock().unwrap().insert(id, Arc::new(hook));
+ SessionReviveHookRegistration { id }
+}
+
+pub struct SessionReviveHookRegistration {
+ id: u64,
+}
+
+impl Drop for SessionReviveHookRegistration {
+ fn drop(&mut self) {
+ revive_hooks().lock().unwrap().remove(&self.id);
+ }
+}
+
+/// Notify session-owned subsystems after `start_session` has successfully
+/// revived and rebound a recycled id. Unlike [`revive_session`], this does not
+/// alter core lifecycle state; it fans the completed transition out to
+/// platform-owned tombstones.
+pub fn fire_session_revive(session_id: &str) {
+ let owner = lifecycle_records()
+ .lock()
+ .unwrap()
+ .get(session_id)
+ .map(|record| record.owner_transport.clone());
+ if let Some(owner) = owner {
+ let _ = fire_session_revive_for_owner(session_id, &owner);
+ }
+}
+
+/// Notify render-side owners only while the revived episode is still live and
+/// owned by the same transport. Holding the tombstone lock across callbacks
+/// orders a racing end after revival, so its cleanup cannot be followed by a
+/// late overlay resurrection.
+pub fn fire_session_revive_for_owner(session_id: &str, owner_transport: &str) -> bool {
+ let registered = revive_hooks()
+ .lock()
+ .unwrap()
+ .values()
+ .cloned()
+ .collect::<Vec<_>>();
+ let ended = ended_sessions().lock().unwrap();
+ if ended.contains_key(session_id)
+ || !lifecycle_records()
+ .lock()
+ .unwrap()
+ .get(session_id)
+ .is_some_and(|record| {
+ record.owner_transport == owner_transport && record.pending_end.is_none()
+ })
+ {
+ return false;
+ }
+ for hook in registered {
+ hook(session_id);
+ }
+ true
+}
+
#[doc(hidden)]
pub fn session_end_hook_count() -> usize {
hooks().lock().unwrap().len()
@@ -435,26 +1130,151 @@ pub fn session_end_hook_count() -> usize {
/// later calls return `false`. The first fire still returns `true` when no
/// hooks are registered.
pub fn fire_session_end(session_id: &str) -> bool {
- // Mark-then-fan-out under a short critical section, releasing the lock
- // before running hooks (hooks may be slow / re-entrant and must not hold
- // the dedupe lock).
- {
- let mut ended = ended_sessions().lock().unwrap();
- if !ended.insert(session_id.to_owned()) {
- return false; // already ended — idempotent no-op.
- }
+ fire_session_end_for_owner(session_id, None)
+}
+
+fn fire_session_end_for_owner(session_id: &str, owner_transport: Option<&str>) -> bool {
+ let first_fire = mark_session_ended(session_id, owner_transport);
+ if first_fire {
+ initialize_session_cleanup(session_id);
}
+ let _ = retry_session_cleanup(session_id);
+ first_fire
+}
+
+/// Atomically remove a live lifecycle record and install its tombstone.
+///
+/// Hooks run after this short critical section. Keeping this transition under
+/// the same lock order as dispatch admission prevents a racing first action
+/// from recreating a record immediately before or after termination.
+fn mark_session_ended(session_id: &str, owner_transport: Option<&str>) -> bool {
+ activity().lock().unwrap().remove(session_id);
+ let mut ended = ended_sessions().lock().unwrap();
+ let record_owner = lifecycle_records()
+ .lock()
+ .unwrap()
+ .remove(session_id)
+ .map(|record| record.owner_transport);
+ if ended.contains_key(session_id) {
+ false
+ } else {
+ ended.insert(
+ session_id.to_owned(),
+ owner_transport.map(str::to_owned).or(record_owner),
+ );
+ true
+ }
+}
+
+fn initialize_session_cleanup(session_id: &str) {
crate::capture_scope::clear_session(session_id);
- let registered = hooks()
+ let mut registered = hooks()
.lock()
.unwrap()
- .values()
- .cloned()
+ .iter()
+ .map(|(id, hook)| (*id, hook.clone()))
.collect::<Vec<_>>();
- for hook in registered {
- hook(session_id);
+ registered.sort_by_key(|(id, _)| *id);
+ cleanup_progress().lock().unwrap().insert(
+ session_id.to_owned(),
+ SessionCleanupProgress {
+ hooks: registered,
+ completed: HashSet::new(),
+ failures: Vec::new(),
+ running: false,
+ },
+ );
+}
+
+/// Retry only the cleanup hooks that have not yet succeeded for this ended
+/// lifecycle episode. Panics are converted to structured failures so another
+/// explicit end can retry them instead of losing cleanup state.
+pub fn retry_session_cleanup(session_id: &str) -> SessionCleanupReport {
+ let work = {
+ let mut all = cleanup_progress().lock().unwrap();
+ let Some(progress) = all.get_mut(session_id) else {
+ return SessionCleanupReport {
+ complete: true,
+ in_progress: false,
+ failures: Vec::new(),
+ };
+ };
+ if progress.running {
+ return SessionCleanupReport {
+ complete: false,
+ in_progress: true,
+ failures: progress.failures.clone(),
+ };
+ }
+ progress.running = true;
+ progress
+ .hooks
+ .iter()
+ .filter(|(id, _)| !progress.completed.contains(id))
+ .cloned()
+ .collect::<Vec<_>>()
+ };
+
+ let mut successes = Vec::new();
+ let mut failures = Vec::new();
+ for (id, hook) in work {
+ let result =
+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (hook.callback)(session_id)));
+ match result {
+ Ok(Ok(())) => successes.push(id),
+ Ok(Err(error)) => failures.push(SessionCleanupFailure {
+ hook: hook.name,
+ error,
+ }),
+ Err(_) => failures.push(SessionCleanupFailure {
+ hook: hook.name,
+ error: "cleanup hook panicked".into(),
+ }),
+ }
+ }
+
+ let mut all = cleanup_progress().lock().unwrap();
+ let Some(progress) = all.get_mut(session_id) else {
+ return SessionCleanupReport {
+ complete: true,
+ in_progress: false,
+ failures: Vec::new(),
+ };
+ };
+ progress.completed.extend(successes);
+ progress.failures = failures;
+ progress.running = false;
+ let complete = progress.completed.len() == progress.hooks.len();
+ let failures = progress.failures.clone();
+ if complete {
+ all.remove(session_id);
+ }
+ SessionCleanupReport {
+ complete,
+ in_progress: false,
+ failures,
+ }
+}
+
+/// Inspect cleanup progress without starting another attempt.
+///
+/// Lifecycle tools use this after requesting an end so one public call runs
+/// each unfinished hook at most once. A later explicit `end_session` call is
+/// the bounded retry boundary for hooks that failed.
+pub fn session_cleanup_status(session_id: &str) -> SessionCleanupReport {
+ let all = cleanup_progress().lock().unwrap();
+ let Some(progress) = all.get(session_id) else {
+ return SessionCleanupReport {
+ complete: true,
+ in_progress: false,
+ failures: Vec::new(),
+ };
+ };
+ SessionCleanupReport {
+ complete: progress.completed.len() == progress.hooks.len(),
+ in_progress: progress.running,
+ failures: progress.failures.clone(),
}
- true
}
/// Revoke every currently tracked session. This is intentionally callable by
@@ -490,9 +1310,13 @@ pub fn revoke_sessions_with_prefix(prefix: &str) -> usize {
pub fn forget_ended_sessions_with_prefix(prefix: &str) -> usize {
let mut ended = ended_sessions().lock().unwrap();
let before = ended.len();
- ended.retain(|session| !session.starts_with(prefix));
+ ended.retain(|session, _| !session.starts_with(prefix));
let forgotten = before - ended.len();
drop(ended);
+ cleanup_progress()
+ .lock()
+ .unwrap()
+ .retain(|session, _| !session.starts_with(prefix));
crate::capture_scope::clear_sessions_with_prefix(prefix);
forgotten
}
@@ -501,7 +1325,7 @@ pub fn forget_ended_sessions_with_prefix(prefix: &str) -> usize {
/// daemon-side authority for "this session is permanently gone"; the macOS
/// overlay keeps its own render-side tombstone keyed on the same id.
pub fn is_session_ended(session_id: &str) -> bool {
- ended_sessions().lock().unwrap().contains(session_id)
+ ended_sessions().lock().unwrap().contains_key(session_id)
}
/// Revive a previously-ended session id by clearing its tombstone, so a fresh
@@ -518,7 +1342,70 @@ pub fn revive_session(session_id: &str) -> bool {
if !is_trackable(session_id) {
return false;
}
- ended_sessions().lock().unwrap().remove(session_id)
+ if !retry_session_cleanup(session_id).complete {
+ return false;
+ }
+ ended_sessions()
+ .lock()
+ .unwrap()
+ .remove(session_id)
+ .is_some()
+}
+
+/// Owner-checked revival used by the public `start_session` tool. A public
+/// label is never proof that a new transport owns a prior episode: only the
+/// transport that ended the episode may revive it without a separate trusted
+/// host resume proof.
+pub fn revive_session_for_owner(
+ session_id: &str,
+ owner_transport: &str,
+) -> Result<bool, &'static str> {
+ if !is_trackable(session_id) {
+ return Ok(false);
+ }
+
+ // Validate ownership before running any cleanup callback. A caller that
+ // merely guesses another transport's public label must not be able to
+ // trigger work for that lifecycle episode.
+ {
+ let ended = ended_sessions().lock().unwrap();
+ let Some(ended_owner) = ended.get(session_id) else {
+ return Ok(false);
+ };
+ match ended_owner.as_deref() {
+ Some(owner) if owner != owner_transport => {
+ return Err("session is not available to this transport");
+ }
+ // Legacy tombstones did not retain ownership. Allow only the
+ // direct runtime shape where the trusted owner key and lifecycle
+ // id coincide; transport-backed callers fail closed.
+ None if owner_transport != session_id => {
+ return Err("session is not available to this transport");
+ }
+ _ => {}
+ }
+ }
+
+ if !retry_session_cleanup(session_id).complete {
+ return Err("session cleanup is incomplete; retry end_session before revival");
+ }
+
+ // Recheck after cleanup because another thread may have completed the
+ // revival while callbacks were running.
+ let mut ended = ended_sessions().lock().unwrap();
+ let Some(ended_owner) = ended.get(session_id) else {
+ return Ok(false);
+ };
+ match ended_owner.as_deref() {
+ Some(owner) if owner != owner_transport => {
+ Err("session is not available to this transport")
+ }
+ None if owner_transport != session_id => Err("session is not available to this transport"),
+ _ => {
+ ended.remove(session_id);
+ Ok(true)
+ }
+ }
}
/// Record activity for an explicit runtime-private session id, resetting its
@@ -563,7 +1450,24 @@ fn end_session_with_reason(session_id: &str, reason: SessionEndReason) {
if !is_trackable(session_id) {
return;
}
- activity().lock().unwrap().remove(session_id);
+ let defer = {
+ let mut records = lifecycle_records().lock().unwrap();
+ match records.get_mut(session_id) {
+ Some(record) if record.in_flight > 0 => {
+ record.pending_end.get_or_insert(reason);
+ true
+ }
+ _ => false,
+ }
+ };
+ if defer {
+ return;
+ }
+ finish_session_end(session_id, reason);
+}
+
+fn finish_session_end(session_id: &str, reason: SessionEndReason) {
+ let first_fire = mark_session_ended(session_id, None);
let mut cursor_readers = CURSOR_OUTCOME_READERS
.get()
.map(|readers| {
@@ -587,7 +1491,11 @@ fn end_session_with_reason(session_id: &str, reason: SessionEndReason) {
}
});
let cursor = cursor.or(fallback);
- if fire_session_end(session_id) {
+ if first_fire {
+ initialize_session_cleanup(session_id);
+ }
+ let _ = retry_session_cleanup(session_id);
+ if first_fire {
if let Some(observer) = SESSION_OBSERVER.get() {
observer.on_session_ended(public_session_label(session_id), reason, cursor);
}
@@ -602,10 +1510,19 @@ fn end_session_with_reason(session_id: &str, reason: SessionEndReason) {
/// TTL are left untouched.
pub fn evict_idle(ttl: Duration) -> Vec<String> {
let now = Instant::now();
+ let lifecycle = lifecycle_records()
+ .lock()
+ .unwrap()
+ .iter()
+ .map(|(id, record)| (id.clone(), (record.in_flight, record.idle_ttl)))
+ .collect::<HashMap<_, _>>();
let stale: Vec<String> = {
let map = activity().lock().unwrap();
map.iter()
- .filter(|(_, last)| now.duration_since(**last) >= ttl)
+ .filter(|(id, last)| {
+ let (in_flight, session_ttl) = lifecycle.get(*id).copied().unwrap_or_default();
+ now.duration_since(**last) >= session_ttl.unwrap_or(ttl) && in_flight == 0
+ })
.map(|(id, _)| id.clone())
.collect()
};
@@ -619,10 +1536,21 @@ pub fn evict_idle(ttl: Duration) -> Vec<String> {
/// the trusted runtime and never accepted from a tool argument.
pub fn evict_idle_with_prefix(ttl: Duration, prefix: &str) -> Vec<String> {
let now = Instant::now();
+ let lifecycle = lifecycle_records()
+ .lock()
+ .unwrap()
+ .iter()
+ .map(|(id, record)| (id.clone(), (record.in_flight, record.idle_ttl)))
+ .collect::<HashMap<_, _>>();
let stale: Vec<String> = {
let map = activity().lock().unwrap();
map.iter()
- .filter(|(id, last)| id.starts_with(prefix) && now.duration_since(**last) >= ttl)
+ .filter(|(id, last)| {
+ let (in_flight, session_ttl) = lifecycle.get(*id).copied().unwrap_or_default();
+ id.starts_with(prefix)
+ && now.duration_since(**last) >= session_ttl.unwrap_or(ttl)
+ && in_flight == 0
+ })
.map(|(id, _)| id.clone())
.collect()
};
@@ -641,7 +1569,7 @@ pub fn active_session_count() -> usize {
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
- use std::sync::Arc;
+ use std::sync::{Arc, Barrier};
#[derive(Default)]
struct ProbeObserver {
@@ -661,6 +1589,7 @@ mod tests {
_: &str,
_: SessionTransport,
_: bool,
+ _: Option<CaptureModality>,
_: Option<EscalationReason>,
_: &crate::server::ToolCompletionObservation,
) {
@@ -761,11 +1690,11 @@ mod tests {
let sid = "test-ttl-session-DDEEFF";
touch_session(sid);
// A huge TTL leaves it alone (just touched).
- assert!(evict_idle(Duration::from_secs(3600))
+ assert!(evict_idle_with_prefix(Duration::from_secs(3600), sid)
.iter()
.all(|s| s != sid));
// A zero TTL treats any prior activity as idle → evicts it.
- let evicted = evict_idle(Duration::ZERO);
+ let evicted = evict_idle_with_prefix(Duration::ZERO, sid);
assert!(
evicted.iter().any(|s| s == sid),
"zero-TTL must evict a touched session"
@@ -778,13 +1707,14 @@ mod tests {
touch_session("default");
touch_session("");
// Neither shows up under a zero-TTL sweep (they were never inserted).
- let evicted = evict_idle(Duration::ZERO);
+ let evicted = evict_idle_with_prefix(Duration::ZERO, "test-anonymous-never-matches");
assert!(!evicted.iter().any(|s| s == "default" || s.is_empty()));
}
#[test]
fn cursor_outcomes_are_fixed_categories_without_raw_values() {
- let custom = bounded_cursor_outcome(true, true, Some("private.customer.theme"), true, 7);
+ let custom =
+ bounded_cursor_outcome(true, true, true, Some("private.customer.theme"), true, 7);
assert_eq!(custom.theme, CursorThemeCategory::Custom);
assert!(custom.motion_customized);
assert_eq!(custom.active_cursor_count, 7);
@@ -795,9 +1725,10 @@ mod tests {
"cursor outcome leaked {forbidden}: {debug}"
);
- let unknown = bounded_cursor_outcome(false, true, Some("cua.default"), true, 0);
+ let unknown = bounded_cursor_outcome(false, true, true, Some("cua.default"), true, 0);
assert_eq!(unknown.theme, CursorThemeCategory::Unknown);
assert!(!unknown.enabled);
+ assert!(!unknown.visible);
assert!(!unknown.motion_customized);
}
@@ -808,7 +1739,302 @@ mod tests {
end_session(sid);
assert!(is_session_ended(sid));
// Its TTL entry is gone, so a later sweep doesn't re-fire for it.
- assert!(!evict_idle(Duration::ZERO).iter().any(|s| s == sid));
+ assert!(!evict_idle_with_prefix(Duration::ZERO, sid)
+ .iter()
+ .any(|s| s == sid));
+ }
+
+ #[test]
+ fn lifecycle_identity_is_scoped_to_its_transport_owner() {
+ let sid = "test-owner-scope-session-A1B2C3";
+ let owner_a = "test-owner-transport-a";
+ let owner_b = "test-owner-transport-b";
+ assert!(activate_session(
+ sid,
+ Some("shared-public-label"),
+ owner_a,
+ false,
+ SessionTransport::McpHttp,
+ SessionClientKind::Mcp,
+ )
+ .is_ok());
+
+ assert!(session_snapshot(sid, owner_a, DEFAULT_SESSION_IDLE_TTL).is_some());
+ assert!(session_snapshot(sid, owner_b, DEFAULT_SESSION_IDLE_TTL).is_none());
+ assert!(activate_session(
+ sid,
+ Some("shared-public-label"),
+ owner_b,
+ false,
+ SessionTransport::McpHttp,
+ SessionClientKind::Mcp,
+ )
+ .is_err());
+ assert!(begin_session_dispatch(
+ sid,
+ Some("shared-public-label"),
+ owner_b,
+ false,
+ SessionTransport::McpHttp,
+ SessionClientKind::Mcp,
+ )
+ .is_err());
+ assert!(!end_session_for_owner(sid, owner_b));
+ assert!(!is_session_ended(sid));
+
+ assert!(end_session_for_owner(sid, owner_a));
+ assert!(is_session_ended(sid));
+ assert!(revive_session_for_owner(sid, owner_b).is_err());
+ assert!(is_session_ended(sid));
+ assert_eq!(revive_session_for_owner(sid, owner_a), Ok(true));
+ }
+
+ #[test]
+ fn atomic_start_cannot_transfer_an_ended_label_to_another_transport() {
+ let sid = "test-atomic-owner-revival-B1C2D3";
+ let owner_a = "test-atomic-owner-a";
+ let owner_b = "test-atomic-owner-b";
+ activate_session(
+ sid,
+ Some("recycled-label"),
+ owner_a,
+ false,
+ SessionTransport::McpHttp,
+ SessionClientKind::Mcp,
+ )
+ .unwrap();
+ assert!(end_session_for_owner(sid, owner_a));
+
+ assert!(activate_or_revive_session_for_owner(
+ sid,
+ Some("recycled-label"),
+ owner_b,
+ false,
+ SessionTransport::McpHttp,
+ SessionClientKind::Mcp,
+ None,
+ )
+ .is_err());
+ assert!(is_session_ended(sid));
+
+ assert_eq!(
+ activate_or_revive_session_for_owner(
+ sid,
+ Some("recycled-label"),
+ owner_a,
+ false,
+ SessionTransport::McpHttp,
+ SessionClientKind::Mcp,
+ None,
+ ),
+ Ok(true)
+ );
+ assert!(session_snapshot(sid, owner_a, DEFAULT_SESSION_IDLE_TTL).is_some());
+ assert!(session_snapshot(sid, owner_b, DEFAULT_SESSION_IDLE_TTL).is_none());
+ assert!(end_session_for_owner(sid, owner_a));
+ }
+
+ #[test]
+ fn foreign_revival_does_not_run_an_owners_pending_cleanup() {
+ let sid = "test-owner-cleanup-scope-B2C3D4";
+ let owner_a = "test-owner-cleanup-transport-a";
+ let owner_b = "test-owner-cleanup-transport-b";
+ let cleanup_calls = Arc::new(AtomicUsize::new(0));
+ let calls_for_hook = cleanup_calls.clone();
+ let _registration =
+ register_scoped_fallible_session_end_hook("owner-cleanup-test", move |ended| {
+ if ended != sid {
+ return Ok(());
+ }
+ let call = calls_for_hook.fetch_add(1, Ordering::SeqCst);
+ if call == 0 {
+ Err("retry me".into())
+ } else {
+ Ok(())
+ }
+ });
+
+ activate_session(
+ sid,
+ Some("owner-cleanup"),
+ owner_a,
+ false,
+ SessionTransport::McpHttp,
+ SessionClientKind::Mcp,
+ )
+ .unwrap();
+ assert!(end_session_for_owner(sid, owner_a));
+ assert_eq!(cleanup_calls.load(Ordering::SeqCst), 1);
+
+ assert!(revive_session_for_owner(sid, owner_b).is_err());
+ assert_eq!(
+ cleanup_calls.load(Ordering::SeqCst),
+ 1,
+ "a foreign caller must not trigger cleanup callbacks"
+ );
+
+ assert_eq!(revive_session_for_owner(sid, owner_a), Ok(true));
+ assert_eq!(cleanup_calls.load(Ordering::SeqCst), 2);
+ }
+
+ #[test]
+ fn concurrent_first_dispatches_share_one_lifecycle_record() {
+ let sid = "test-concurrent-first-session-D4E5F6";
+ let owner = "test-concurrent-first-owner";
+ let barrier = Arc::new(Barrier::new(9));
+ let mut workers = Vec::new();
+ for _ in 0..8 {
+ let barrier = barrier.clone();
+ workers.push(std::thread::spawn(move || {
+ barrier.wait();
+ let guard = begin_session_dispatch(
+ sid,
+ None,
+ owner,
+ true,
+ SessionTransport::McpStdio,
+ SessionClientKind::Mcp,
+ )
+ .expect("same owner may join its implicit lifecycle");
+ barrier.wait();
+ drop(guard);
+ }));
+ }
+ barrier.wait();
+ barrier.wait();
+ assert_eq!(
+ list_session_snapshots(owner, DEFAULT_SESSION_IDLE_TTL)
+ .into_iter()
+ .filter(|snapshot| snapshot.runtime_id == sid)
+ .count(),
+ 1
+ );
+ for worker in workers {
+ worker.join().unwrap();
+ }
+ assert!(end_session_for_owner(sid, owner));
+ }
+
+ #[test]
+ fn end_waits_for_in_flight_dispatch_and_cleanup_runs_once() {
+ let sid = "test-in-flight-end-session-F7A8B9";
+ let owner = "test-in-flight-end-owner";
+ let cleanup_calls = Arc::new(AtomicUsize::new(0));
+ let cleanup_calls_for_hook = cleanup_calls.clone();
+ let _registration = register_scoped_session_end_hook(move |ended| {
+ if ended == sid {
+ cleanup_calls_for_hook.fetch_add(1, Ordering::SeqCst);
+ }
+ });
+ let guard = begin_session_dispatch(
+ sid,
+ None,
+ owner,
+ true,
+ SessionTransport::McpStdio,
+ SessionClientKind::Mcp,
+ )
+ .unwrap();
+
+ activate_session(
+ sid,
+ None,
+ owner,
+ true,
+ SessionTransport::McpStdio,
+ SessionClientKind::Mcp,
+ )
+ .expect("idempotent start must preserve the live dispatch record");
+
+ assert!(end_session_for_owner(sid, owner));
+ let snapshot = session_snapshot(sid, owner, DEFAULT_SESSION_IDLE_TTL).unwrap();
+ assert!(snapshot.ending);
+ assert!(!is_session_ended(sid));
+ assert!(!evict_idle_with_prefix(Duration::ZERO, sid)
+ .iter()
+ .any(|id| id == sid));
+
+ drop(guard);
+ assert!(is_session_ended(sid));
+ assert_eq!(cleanup_calls.load(Ordering::SeqCst), 1);
+ assert!(end_session_for_owner(sid, owner));
+ assert_eq!(cleanup_calls.load(Ordering::SeqCst), 1);
+ }
+
+ #[test]
+ fn trusted_idle_ttl_override_controls_snapshot_and_eviction() {
+ let sid = "test-trusted-lifecycle-ttl-A9B0C1";
+ let owner = "test-trusted-lifecycle-ttl-owner";
+ activate_session_with_ttl(
+ sid,
+ Some("trusted-ttl"),
+ owner,
+ false,
+ SessionTransport::Daemon,
+ SessionClientKind::PythonSdk,
+ Duration::from_millis(1),
+ )
+ .unwrap();
+ let snapshot = session_snapshot(sid, owner, Duration::from_secs(3600)).unwrap();
+ assert!(snapshot.expires_in <= Duration::from_millis(1));
+ let operator_snapshot = list_session_snapshots_with_prefix(
+ "test-trusted-lifecycle-ttl-",
+ Duration::from_secs(3600),
+ )
+ .into_iter()
+ .find(|snapshot| snapshot.runtime_id == sid)
+ .unwrap();
+ assert!(operator_snapshot.expires_in <= Duration::from_millis(1));
+
+ std::thread::sleep(Duration::from_millis(5));
+ assert_eq!(
+ evict_idle_with_prefix(Duration::from_secs(3600), sid),
+ vec![sid.to_owned()],
+ "the trusted per-session TTL must override the runtime fallback"
+ );
+ }
+
+ #[test]
+ fn partial_cleanup_retries_only_failed_hooks_then_allows_revival() {
+ let sid = "test-partial-cleanup-retry-C8D9E0";
+ let retryable_calls = Arc::new(AtomicUsize::new(0));
+ let retryable_for_hook = retryable_calls.clone();
+ let _retryable =
+ register_scoped_fallible_session_end_hook("retryable-test-hook", move |ended| {
+ if ended != sid {
+ return Ok(());
+ }
+ let attempt = retryable_for_hook.fetch_add(1, Ordering::SeqCst);
+ if attempt == 0 {
+ Err("synthetic first-attempt failure".into())
+ } else {
+ Ok(())
+ }
+ });
+ let successful_calls = Arc::new(AtomicUsize::new(0));
+ let successful_for_hook = successful_calls.clone();
+ let _successful = register_scoped_session_end_hook(move |ended| {
+ if ended == sid {
+ successful_for_hook.fetch_add(1, Ordering::SeqCst);
+ }
+ });
+
+ touch_session(sid);
+ end_session(sid);
+ assert!(is_session_ended(sid));
+ assert_eq!(retryable_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(successful_calls.load(Ordering::SeqCst), 1);
+
+ let report = retry_session_cleanup(sid);
+ assert!(report.complete);
+ assert!(report.failures.is_empty());
+ assert_eq!(retryable_calls.load(Ordering::SeqCst), 2);
+ assert_eq!(
+ successful_calls.load(Ordering::SeqCst),
+ 1,
+ "successful cleanup hooks must not run twice"
+ );
+ assert!(revive_session(sid));
}
#[test]
@@ -857,7 +2083,7 @@ mod tests {
}
#[test]
- fn tool_context_requires_a_public_session_and_uses_fixed_action_classes() {
+ fn tool_context_accepts_trusted_implicit_session_and_uses_fixed_action_classes() {
let _ = probe_observer();
assert!(begin_tool_call(
"click",
@@ -866,7 +2092,7 @@ mod tests {
SessionTransport::McpStdio,
SessionClientKind::Mcp,
)
- .is_none());
+ .is_some());
assert!(begin_tool_call(
"click",
&serde_json::json!({"session": "default"}),
@@ -941,13 +2167,32 @@ mod tests {
escalation.escalation_reason,
Some(EscalationReason::NoWindowTarget)
);
+
+ assert_eq!(
+ capture_modality_for(
+ "click",
+ &serde_json::json!({
+ "target": {"kind": "window", "pid": 7, "window_id": 9}
+ }),
+ ),
+ Some(CaptureModality::Window)
+ );
+ assert_eq!(
+ capture_modality_for(
+ "click",
+ &serde_json::json!({
+ "target": {"kind": "desktop", "display_id": "primary"}
+ }),
+ ),
+ Some(CaptureModality::Desktop)
+ );
}
#[test]
fn observer_distinguishes_explicit_idle_revival_and_control_cleanup() {
let probe = probe_observer();
let _ = set_cursor_outcome_reader(Arc::new(|_| {
- bounded_cursor_outcome(true, true, Some("cua.default"), false, 2)
+ bounded_cursor_outcome(true, true, true, Some("cua.default"), false, 2)
}));
let explicit = "test-observer-explicit-IJ90";
begin_tool_call(
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 839e92256b..b7115c607f 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
@@ -241,6 +241,15 @@ impl EffectiveAuthorizationContext {
self.transport_session.as_deref()
}
+ /// Lifecycle idle TTL selected by a trusted delegated-session host. An
+ /// ordinary compatibility context uses the product default instead.
+ #[doc(hidden)]
+ pub fn lifecycle_idle_ttl_override(&self) -> Option<Duration> {
+ (self.source == AuthorizationContextSource::TrustedHost)
+ .then_some(self.idle_ttl)
+ .flatten()
+ }
+
#[doc(hidden)]
pub fn user_policy_sha256(&self) -> Option<&str> {
self.user_policy_sha256.as_deref()
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session_tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session_tools.rs
index 4797b83442..24aecdf7cb 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/session_tools.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session_tools.rs
@@ -1,11 +1,10 @@
//! Session lifecycle and per-session capture-scope tools.
//!
-//! A session is a **caller-declared** identity for an agent run (see
-//! [`crate::session`]). It owns the agent cursor and is the key for
-//! per-session config + recording. These tools bookend a run's lifetime
-//! explicitly, decoupled from the MCP connection: the same `session` id works
-//! identically over MCP, the CLI (`--session`), or the raw socket, and a run
-//! can span any number of apps/windows.
+//! A session is lifecycle identity for an agent run (see [`crate::session`]).
+//! It owns the agent cursor, per-run configuration, recording, cleanup, and
+//! telemetry. A trusted transport lease receives one implicit session when a
+//! session-requiring call omits a public label; explicit labels remain an
+//! optional coordination mechanism inside the same trusted namespace.
//!
//! The daemon may mirror an explicit `session` arg into reserved transport
//! fields, but lifecycle and policy tools accept only the public `session`
@@ -17,20 +16,95 @@ use crate::tool::{Tool, ToolDef};
use crate::tool_args::parse_typed_input;
use async_trait::async_trait;
use cua_driver_contract::{
- CaptureScope, EndSessionInput, EscalateSessionInput, EscalationReason, GetSessionStateInput,
- StartSessionInput,
+ CaptureScope, EndSessionInput, EscalateSessionInput, EscalationReason, GetSessionInput,
+ GetSessionStateInput, ListSessionsInput, ListSessionsOutput, SessionClientKindOutput,
+ SessionLifecycleState, SessionOutput, SessionTransportOutput, StartSessionInput,
};
use serde_json::{json, Value};
use std::sync::OnceLock;
-/// Read the public, caller-declared session id. Capture-scope policy must never
-/// bind to the daemon's reserved `_session_id` transport mirror.
+/// Resolve the runtime-private lifecycle id injected at the trusted registry
+/// boundary. An explicit public label wins; otherwise the transport lease's
+/// implicit id is used.
fn session_id_of(args: &Value) -> Option<String> {
- args.as_object()?
- .get("session")
- .and_then(|v| v.as_str())
- .filter(|s| !s.is_empty() && *s != "default")
- .map(|s| s.to_owned())
+ let args = args.as_object()?;
+ ["session", "_session_id"].into_iter().find_map(|key| {
+ args.get(key)
+ .and_then(Value::as_str)
+ .filter(|s| !s.is_empty() && *s != "default")
+ .map(str::to_owned)
+ })
+}
+
+fn public_label_of(args: &Value) -> Option<String> {
+ args.get("_public_session_label")
+ .and_then(Value::as_str)
+ .filter(|value| !value.is_empty())
+ .map(str::to_owned)
+}
+
+fn response_session_label(args: &Value, session_id: &str) -> String {
+ public_label_of(args).unwrap_or_else(|| {
+ if args
+ .get("session")
+ .and_then(Value::as_str)
+ .is_some_and(|value| !value.is_empty() && value != "default")
+ {
+ crate::session::public_session_label(session_id).to_owned()
+ } else {
+ // Never expose a transport UUID or runtime-private key merely
+ // because the caller used its unnamed implicit session.
+ "implicit".to_owned()
+ }
+ })
+}
+
+fn owner_transport_of(args: &Value, session_id: &str) -> String {
+ args.get("_transport_session_id")
+ .and_then(Value::as_str)
+ .filter(|value| !value.is_empty())
+ .unwrap_or(session_id)
+ .to_owned()
+}
+
+fn lifecycle_idle_ttl_of(args: &Value) -> Option<std::time::Duration> {
+ args.get("_session_idle_ttl_ms")
+ .and_then(Value::as_u64)
+ .filter(|milliseconds| *milliseconds > 0)
+ .map(std::time::Duration::from_millis)
+}
+
+fn lifecycle_output(snapshot: crate::session::LifecycleSessionSnapshot) -> SessionOutput {
+ let cursor_visible = crate::session::cursor_visible(&snapshot.runtime_id);
+ let recording_active = crate::session::recording_active(&snapshot.runtime_id);
+ SessionOutput {
+ session: snapshot.public_label,
+ implicit: snapshot.implicit,
+ state: if snapshot.ending {
+ SessionLifecycleState::Ending
+ } else {
+ SessionLifecycleState::Active
+ },
+ client_kind: match snapshot.client_kind {
+ crate::session::SessionClientKind::Cli => SessionClientKindOutput::Cli,
+ crate::session::SessionClientKind::Direct => SessionClientKindOutput::Direct,
+ crate::session::SessionClientKind::Mcp => SessionClientKindOutput::Mcp,
+ crate::session::SessionClientKind::PythonSdk => SessionClientKindOutput::PythonSdk,
+ crate::session::SessionClientKind::TypescriptSdk => {
+ SessionClientKindOutput::TypescriptSdk
+ }
+ },
+ transport: match snapshot.transport {
+ crate::session::SessionTransport::Cli => SessionTransportOutput::Cli,
+ crate::session::SessionTransport::Daemon => SessionTransportOutput::Daemon,
+ crate::session::SessionTransport::McpStdio => SessionTransportOutput::McpStdio,
+ crate::session::SessionTransport::McpHttp => SessionTransportOutput::McpHttp,
+ },
+ cursor_visible,
+ recording_active,
+ idle_seconds: snapshot.idle.as_secs(),
+ expires_in_seconds: snapshot.expires_in.as_secs(),
+ }
}
// ── start_session ─────────────────────────────────────────────────────────────
@@ -47,7 +121,7 @@ impl Tool for StartSessionTool {
async fn invoke(&self, args: Value) -> ToolResult {
let Some(id) = session_id_of(&args) else {
- return ToolResult::error("start_session requires a non-empty `session` id.");
+ return ToolResult::error("start_session requires an authenticated transport lease or a non-empty `session` label.");
};
if let Some(raw) = args.get("capture_scope") {
let Some(raw) = raw.as_str() else {
@@ -66,15 +140,50 @@ impl Tool for StartSessionTool {
}));
}
}
- let input = match parse_typed_input::<StartSessionInput>("start_session", args) {
+ let input = match parse_typed_input::<StartSessionInput>("start_session", args.clone()) {
Ok(input) => input,
Err(result) => return result,
};
let requested = input.capture_scope;
- let was_ended = crate::session::is_session_ended(&id);
- if !was_ended {
+ let legacy_capture = requested.is_some();
+ let public_label = public_label_of(&args);
+ let owner = owner_transport_of(&args, &id);
+ let (transport, client_kind) = crate::session::infer_transport_metadata(&owner);
+ if let Some(requested) = requested {
+ if let Some(existing) = get_session(&id) {
+ if existing.policy != requested {
+ return ToolResult::error(
+ "session already uses a different deprecated capture policy",
+ )
+ .with_structured(json!({
+ "code": "session_policy_conflict",
+ "capture_scope": existing.policy.as_str(),
+ "requested_capture_scope": requested.as_str(),
+ }));
+ }
+ }
+ }
+ // Tombstone removal and owner binding are one atomic lifecycle
+ // transition. A guessed public label cannot be claimed in the gap
+ // between revival and activation.
+ let revived = match crate::session::activate_or_revive_session_for_owner(
+ &id,
+ public_label.as_deref(),
+ &owner,
+ public_label.is_none(),
+ transport,
+ client_kind,
+ lifecycle_idle_ttl_of(&args),
+ ) {
+ Ok(revived) => revived,
+ Err(_) => {
+ return ToolResult::error("session is not available to this transport")
+ .with_structured(json!({ "code": "session_unavailable" }));
+ }
+ };
+ let scope = if legacy_capture {
match bind_session(&id, requested) {
- Ok(_) => {}
+ Ok((bound, _)) => bound,
Err(BindError::Conflict {
existing,
requested,
@@ -90,52 +199,35 @@ impl Tool for StartSessionTool {
}));
}
Err(BindError::Ended) => {
- return ToolResult::error(format!(
- "session '{id}' ended concurrently; retry start_session to revive it"
- ))
- .with_structured(json!({ "code": "session_ended", "session": id }));
+ return ToolResult::error(format!("session '{id}' could not be revived"))
+ .with_structured(json!({ "code": "session_ended", "session": id }));
}
}
- }
- // Revive a recycled id: if this session was previously ended (explicit
- // `end_session` / idle-TTL / connection EOF), clear its tombstone so its
- // actions stop being rejected by the daemon's resurrection guard.
- // Re-declaring a session is the EXPLICIT, caller-driven way to reuse an
- // id — a stray late action still can't silently resurrect a dead one.
- let revived = crate::session::revive_session(&id);
- let (scope, _) = match bind_session(&id, requested) {
- Ok(bound) => bound,
- Err(BindError::Conflict {
- existing,
- requested,
- }) => {
- return ToolResult::error(format!(
- "session '{id}' already uses capture_scope='{existing}'; capture scope is immutable until the session ends"
- ))
- .with_structured(json!({
- "code": "session_policy_conflict",
- "session": id,
- "capture_scope": existing.as_str(),
- "requested_capture_scope": requested.as_str(),
- }));
- }
- Err(BindError::Ended) => {
- return ToolResult::error(format!("session '{id}' could not be revived"))
- .with_structured(json!({ "code": "session_ended", "session": id }));
- }
+ } else {
+ get_session(&id).unwrap_or_else(|| {
+ crate::capture_scope::SessionCaptureScope::new(CaptureScope::Auto)
+ })
};
- // Refresh (or begin) the session's idle-TTL clock. The cursor appears on
- // the first action carrying this `session`.
- crate::session::touch_session(&id);
+ // Platform overlays keep their own late-command tombstones. Clear
+ // those only after core revival and capture-policy binding both
+ // succeeded, so a failed declaration cannot revive render state.
+ if revived {
+ crate::session::fire_session_revive_for_owner(&id, &owner);
+ }
let structured = serde_json::to_value(cua_driver_contract::StartSessionOutput {
- state: scope.output(&id),
+ state: scope.output(&response_session_label(&args, &id)),
active: true,
revived,
})
.expect("start_session output serializes");
ToolResult::text(format!(
- "✅ Session '{id}' is active with capture_scope='{}'.",
- scope.policy
+ "✅ Session '{}' is active{}.",
+ public_label.as_deref().unwrap_or("implicit"),
+ if legacy_capture {
+ " with deprecated capture_scope compatibility"
+ } else {
+ ""
+ }
))
.with_structured(structured)
}
@@ -167,10 +259,11 @@ impl Tool for EscalateSessionTool {
return ToolResult::error("escalate_session.reason is invalid.")
.with_structured(json!({ "code": "invalid_escalation_reason" }));
}
- let input = match parse_typed_input::<EscalateSessionInput>("escalate_session", args) {
- Ok(input) => input,
- Err(result) => return result,
- };
+ let input =
+ match parse_typed_input::<EscalateSessionInput>("escalate_session", args.clone()) {
+ Ok(input) => input,
+ Err(result) => return result,
+ };
if input
.detail
.as_ref()
@@ -179,9 +272,16 @@ impl Tool for EscalateSessionTool {
return ToolResult::error("escalate_session.detail must be at most 200 characters.")
.with_structured(json!({ "code": "invalid_escalation_detail" }));
}
+ let owner = owner_transport_of(&args, &id);
+ if crate::session::session_snapshot(&id, &owner, crate::session::DEFAULT_SESSION_IDLE_TTL)
+ .is_none()
+ {
+ return ToolResult::error("session is not visible to this transport")
+ .with_structured(json!({ "code": "session_not_started" }));
+ }
match escalate_session(&id, input.reason, input.detail.as_deref()) {
- Ok(state) => ToolResult::text(format!("✅ Session '{id}' escalated to desktop scope."))
- .with_structured(state.as_json(&id)),
+ Ok(state) => ToolResult::text("✅ Session escalated to desktop scope.")
+ .with_structured(state.as_json(&response_session_label(&args, &id))),
Err(error) => {
let (code, message) = match error {
EscalateError::Ended => (
@@ -227,19 +327,119 @@ impl Tool for GetSessionStateTool {
return ToolResult::error("get_session_state requires a public `session` id.")
.with_structured(json!({ "code": "session_required" }));
};
- if let Err(result) = parse_typed_input::<GetSessionStateInput>("get_session_state", args) {
+ if let Err(result) =
+ parse_typed_input::<GetSessionStateInput>("get_session_state", args.clone())
+ {
return result;
}
- let Some(state) = get_session(&id) else {
- return ToolResult::error(format!("session '{id}' is not active"))
- .with_structured(json!({ "code": "session_not_started", "session": id }));
- };
+ let owner = owner_transport_of(&args, &id);
+ if crate::session::session_snapshot(&id, &owner, crate::session::DEFAULT_SESSION_IDLE_TTL)
+ .is_none()
+ {
+ return ToolResult::error("session is not visible to this transport")
+ .with_structured(json!({ "code": "session_not_started" }));
+ }
+ let state = get_session(&id)
+ .unwrap_or_else(|| crate::capture_scope::SessionCaptureScope::new(CaptureScope::Auto));
ToolResult::text(format!(
"Session '{id}' uses capture_scope='{}' (effective_scope='{}').",
state.policy,
state.effective_scope().as_str()
))
- .with_structured(state.as_json(&id))
+ .with_structured(state.as_json(&response_session_label(&args, &id)))
+ }
+}
+
+// ── get_session / list_sessions ─────────────────────────────────────────────
+
+pub struct GetSessionTool;
+
+static GET_DEF: OnceLock<ToolDef> = OnceLock::new();
+
+#[async_trait]
+impl Tool for GetSessionTool {
+ fn def(&self) -> &ToolDef {
+ GET_DEF.get_or_init(|| session_tool_def("get_session"))
+ }
+
+ async fn invoke(&self, args: Value) -> ToolResult {
+ if let Err(result) = parse_typed_input::<GetSessionInput>("get_session", args.clone()) {
+ return result;
+ }
+ let Some(id) = session_id_of(&args) else {
+ return ToolResult::error("no implicit session is attached to this transport")
+ .with_structured(json!({ "code": "session_not_started" }));
+ };
+ let owner = owner_transport_of(&args, &id);
+ let Some(snapshot) =
+ crate::session::session_snapshot(&id, &owner, crate::session::DEFAULT_SESSION_IDLE_TTL)
+ else {
+ return ToolResult::error("session is not visible to this transport")
+ .with_structured(json!({ "code": "session_not_started" }));
+ };
+ let output = lifecycle_output(snapshot);
+ ToolResult::text("Session is active.")
+ .with_structured(serde_json::to_value(output).expect("get_session output serializes"))
+ }
+}
+
+pub struct ListSessionsTool;
+
+static LIST_DEF: OnceLock<ToolDef> = OnceLock::new();
+
+#[async_trait]
+impl Tool for ListSessionsTool {
+ fn def(&self) -> &ToolDef {
+ LIST_DEF.get_or_init(|| session_tool_def("list_sessions"))
+ }
+
+ async fn invoke(&self, args: Value) -> ToolResult {
+ let input = match parse_typed_input::<ListSessionsInput>("list_sessions", args.clone()) {
+ Ok(input) => input,
+ Err(result) => return result,
+ };
+ let Some(owner) = args
+ .get("_transport_session_id")
+ .and_then(Value::as_str)
+ .filter(|value| !value.is_empty())
+ else {
+ return ToolResult::error("list_sessions requires an authenticated transport lease")
+ .with_structured(json!({ "code": "transport_lease_required" }));
+ };
+ let limit = input.limit.unwrap_or(50);
+ if limit == 0 || limit > 100 {
+ return ToolResult::error("list_sessions.limit must be from 1 to 100")
+ .with_structured(json!({ "code": "invalid_limit" }));
+ }
+ let offset = match input.cursor.as_deref() {
+ None => 0,
+ Some(cursor) => match cursor
+ .strip_prefix("o:")
+ .and_then(|v| v.parse::<usize>().ok())
+ {
+ Some(offset) => offset,
+ None => {
+ return ToolResult::error("list_sessions.cursor is invalid")
+ .with_structured(json!({ "code": "invalid_cursor" }))
+ }
+ },
+ };
+ let sessions =
+ crate::session::list_session_snapshots(owner, crate::session::DEFAULT_SESSION_IDLE_TTL);
+ let end = (offset + limit as usize).min(sessions.len());
+ let page = sessions
+ .get(offset..end)
+ .unwrap_or_default()
+ .iter()
+ .cloned()
+ .map(lifecycle_output)
+ .collect::<Vec<_>>();
+ let output = ListSessionsOutput {
+ sessions: page,
+ next_cursor: (end < sessions.len()).then(|| format!("o:{end}")),
+ };
+ ToolResult::text(format!("{} visible session(s).", output.sessions.len()))
+ .with_structured(serde_json::to_value(output).expect("list_sessions output serializes"))
}
}
@@ -257,15 +457,51 @@ impl Tool for EndSessionTool {
async fn invoke(&self, args: Value) -> ToolResult {
let Some(id) = session_id_of(&args) else {
- return ToolResult::error("end_session requires a non-empty `session` id.");
+ return ToolResult::error(
+ "end_session requires an attached implicit session or a non-empty `session` label.",
+ );
};
- if let Err(result) = parse_typed_input::<EndSessionInput>("end_session", args) {
+ if let Err(result) = parse_typed_input::<EndSessionInput>("end_session", args.clone()) {
return result;
}
- crate::session::end_session(&id);
- ToolResult::text(format!("✅ Session '{id}' ended.")).with_structured(
+ let owner = owner_transport_of(&args, &id);
+ let owned = crate::session::end_session_for_owner(&id, &owner);
+ if owned {
+ let cleanup = if crate::session::is_session_ended(&id) {
+ crate::session::session_cleanup_status(&id)
+ } else {
+ crate::session::SessionCleanupReport {
+ complete: false,
+ in_progress: true,
+ failures: Vec::new(),
+ }
+ };
+ if !cleanup.complete {
+ return ToolResult::error(if cleanup.in_progress {
+ "Session is ending after its in-flight action completes; retry end_session for final cleanup status."
+ } else {
+ "Session ended, but one or more cleanup hooks failed; retry end_session."
+ })
+ .with_structured(json!({
+ "code": if cleanup.in_progress { "session_cleanup_pending" } else { "session_cleanup_partial" },
+ "session": public_label_of(&args)
+ .unwrap_or_else(|| crate::session::public_session_label(&id).to_owned()),
+ "cleanup_complete": false,
+ "cleanup_in_progress": cleanup.in_progress,
+ // Hook names are stable, non-sensitive categories. Keep
+ // implementation errors private because adapters may
+ // include local paths or platform details in them.
+ "failed_hooks": cleanup.failures.into_iter().map(|failure| json!({
+ "hook": failure.hook,
+ "error": "cleanup failed",
+ })).collect::<Vec<_>>(),
+ }));
+ }
+ }
+ let response_label = response_session_label(&args, &id);
+ ToolResult::text(format!("✅ Session '{response_label}' ended.")).with_structured(
serde_json::to_value(cua_driver_contract::EndSessionOutput {
- session: id,
+ session: response_label,
active: false,
})
.expect("end_session output serializes"),
@@ -282,27 +518,57 @@ fn session_tool_def(name: &str) -> ToolDef {
#[cfg(test)]
mod tests {
use super::*;
+ use std::sync::{
+ atomic::{AtomicUsize, Ordering},
+ Arc,
+ };
fn result_code(result: &ToolResult) -> Option<&str> {
result.structured_content.as_ref()?.get("code")?.as_str()
}
#[test]
- fn session_id_of_reads_only_public_session() {
+ fn session_id_of_prefers_public_and_uses_trusted_implicit_fallback() {
assert_eq!(
session_id_of(&json!({ "session": "a" })).as_deref(),
Some("a")
);
- assert_eq!(session_id_of(&json!({ "_session_id": "b" })), None);
assert_eq!(
- session_id_of(&json!({ "session": "", "_session_id": "c" })),
- None
+ session_id_of(&json!({ "_session_id": "b" })).as_deref(),
+ Some("b")
+ );
+ assert_eq!(
+ session_id_of(&json!({ "session": "", "_session_id": "c" })).as_deref(),
+ Some("c")
);
assert_eq!(session_id_of(&json!({})), None);
assert_eq!(session_id_of(&json!({ "session": "" })), None);
assert_eq!(session_id_of(&json!({ "session": "default" })), None);
}
+ #[tokio::test]
+ async fn implicit_start_does_not_expose_its_private_transport_identity() {
+ let id = format!("private-implicit-session-{}", std::process::id());
+ let owner = format!("private-transport-{}", std::process::id());
+ let result = StartSessionTool
+ .invoke(json!({
+ "_session_id": id.clone(),
+ "_transport_session_id": owner.clone(),
+ }))
+ .await;
+ assert_ne!(result.is_error, Some(true));
+ let structured = result.structured_content.as_ref().unwrap();
+ assert_eq!(structured["session"], "implicit");
+ let encoded = serde_json::to_string(structured).unwrap();
+ assert!(!encoded.contains(&owner));
+ EndSessionTool
+ .invoke(json!({
+ "_session_id": id,
+ "_transport_session_id": owner,
+ }))
+ .await;
+ }
+
#[tokio::test]
async fn live_policy_is_immutable_and_ended_id_gets_fresh_policy() {
let id = format!("session-tool-policy-{}", std::process::id());
@@ -334,10 +600,137 @@ mod tests {
assert_eq!(structured["revived"], true);
}
+ #[tokio::test]
+ async fn successful_explicit_revival_notifies_session_owned_subsystems_once() {
+ let id = format!("session-tool-revive-hook-{}", std::process::id());
+ let notifications = Arc::new(AtomicUsize::new(0));
+ let observed_id = id.clone();
+ let notifications_for_hook = notifications.clone();
+ let _registration = crate::session::register_scoped_session_revive_hook(move |got| {
+ if got == observed_id {
+ notifications_for_hook.fetch_add(1, Ordering::SeqCst);
+ }
+ });
+ let start = StartSessionTool;
+
+ let fresh = start
+ .invoke(json!({"session": id, "capture_scope": "window"}))
+ .await;
+ assert_ne!(fresh.is_error, Some(true));
+ assert_eq!(notifications.load(Ordering::SeqCst), 0);
+
+ EndSessionTool.invoke(json!({"session": id})).await;
+ let revived = start
+ .invoke(json!({"session": id, "capture_scope": "desktop"}))
+ .await;
+ assert_ne!(revived.is_error, Some(true));
+ assert_eq!(
+ revived.structured_content.as_ref().unwrap()["revived"],
+ true
+ );
+ assert_eq!(notifications.load(Ordering::SeqCst), 1);
+
+ let idempotent = start
+ .invoke(json!({"session": id, "capture_scope": "desktop"}))
+ .await;
+ assert_ne!(idempotent.is_error, Some(true));
+ assert_eq!(notifications.load(Ordering::SeqCst), 1);
+ EndSessionTool.invoke(json!({"session": id})).await;
+ }
+
+ #[tokio::test]
+ async fn cleanup_failure_response_redacts_adapter_error_details() {
+ let id = format!("session-tool-cleanup-redaction-{}", std::process::id());
+ let calls = Arc::new(AtomicUsize::new(0));
+ let calls_for_hook = calls.clone();
+ let observed_id = id.clone();
+ let _registration =
+ crate::session::register_scoped_fallible_session_end_hook("recording", move |ended| {
+ if ended != observed_id {
+ return Ok(());
+ }
+ let call = calls_for_hook.fetch_add(1, Ordering::SeqCst);
+ if call < 2 {
+ Err("failed at /Users/private/recording.mov".into())
+ } else {
+ Ok(())
+ }
+ });
+
+ let started = StartSessionTool.invoke(json!({"session": id})).await;
+ assert_ne!(started.is_error, Some(true));
+ let ended = EndSessionTool.invoke(json!({"session": id})).await;
+ assert_eq!(ended.is_error, Some(true));
+ assert_eq!(result_code(&ended), Some("session_cleanup_partial"));
+ let encoded = serde_json::to_string(&ended.structured_content).unwrap();
+ assert!(encoded.contains("cleanup failed"));
+ assert!(!encoded.contains("/Users/private"));
+
+ let second = EndSessionTool.invoke(json!({"session": id})).await;
+ assert_eq!(second.is_error, Some(true));
+ assert_eq!(calls.load(Ordering::SeqCst), 2);
+ let third = EndSessionTool.invoke(json!({"session": id})).await;
+ assert_ne!(third.is_error, Some(true));
+ assert_eq!(calls.load(Ordering::SeqCst), 3);
+ }
+
+ #[tokio::test]
+ async fn lifecycle_tools_do_not_expose_or_mutate_foreign_transport_sessions() {
+ let id = format!("session-tool-owner-scope-{}", std::process::id());
+ let owner_a = format!("http-owner-a-{}", std::process::id());
+ let owner_b = format!("http-owner-b-{}", std::process::id());
+ let owned_args = json!({
+ "session": id,
+ "_public_session_label": "shared-label",
+ "_transport_session_id": owner_a,
+ "capture_scope": "auto"
+ });
+ let started = StartSessionTool.invoke(owned_args.clone()).await;
+ assert_ne!(started.is_error, Some(true));
+
+ let foreign = json!({
+ "session": id,
+ "_public_session_label": "shared-label",
+ "_transport_session_id": owner_b
+ });
+ let get = GetSessionTool.invoke(foreign.clone()).await;
+ assert_eq!(get.is_error, Some(true));
+ assert_eq!(result_code(&get), Some("session_not_started"));
+
+ let state = GetSessionStateTool.invoke(foreign.clone()).await;
+ assert_eq!(state.is_error, Some(true));
+ assert_eq!(result_code(&state), Some("session_not_started"));
+
+ let list = ListSessionsTool
+ .invoke(json!({"_transport_session_id": owner_b}))
+ .await;
+ assert_eq!(
+ list.structured_content.as_ref().unwrap()["sessions"],
+ json!([])
+ );
+
+ let ended = EndSessionTool.invoke(foreign.clone()).await;
+ assert_ne!(ended.is_error, Some(true), "end remains non-enumerating");
+ assert!(crate::session::session_snapshot(
+ &id,
+ &owner_a,
+ crate::session::DEFAULT_SESSION_IDLE_TTL
+ )
+ .is_some());
+
+ let stolen = StartSessionTool.invoke(foreign).await;
+ assert_eq!(stolen.is_error, Some(true));
+ assert_eq!(result_code(&stolen), Some("session_unavailable"));
+
+ EndSessionTool.invoke(owned_args).await;
+ }
+
#[tokio::test]
async fn auto_requires_explicit_bounded_escalation() {
let id = format!("session-tool-auto-{}", std::process::id());
- let started = StartSessionTool.invoke(json!({"session": id})).await;
+ let started = StartSessionTool
+ .invoke(json!({"session": id, "capture_scope": "auto"}))
+ .await;
assert_eq!(
started.structured_content.as_ref().unwrap()["capture_scope"],
"auto"
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 dd3f872e0a..a4afc91cba 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
@@ -163,12 +163,13 @@ impl ToolDef {
//
// Published SDK tools resolve capabilities from their typed Rust
// contract. The legacy map remains only for runtime-only tools.
- let caps = advertised_capabilities_for(&self.name, &self.input_schema);
+ let input_schema = advertised_runtime_input_schema(&self.name, &self.input_schema);
+ let caps = advertised_capabilities_for(&self.name, &input_schema);
let risk = crate::authorization::risk_metadata_json(&self.name);
let mut entry = serde_json::json!({
"name": self.name,
"description": self.description,
- "inputSchema": self.input_schema,
+ "inputSchema": input_schema,
"annotations": {
"readOnlyHint": self.read_only,
"destructiveHint": self.destructive,
@@ -203,6 +204,30 @@ impl ToolDef {
}
}
+fn advertised_runtime_input_schema(tool_name: &str, schema: &Value) -> Value {
+ let mut schema = schema.clone();
+ if !crate::action_target::supports_typed_target(tool_name) {
+ return schema;
+ }
+ let Some(properties) = schema.get_mut("properties").and_then(Value::as_object_mut) else {
+ return schema;
+ };
+ // Reuse the portable contract's exact tagged-union schema while retaining
+ // the live runtime's broader legacy `scope=window|desktop` decoder.
+ if let Some(portable) = cua_driver_contract::tool_contract(tool_name) {
+ if let Some(portable_properties) = portable
+ .input_schema
+ .get("properties")
+ .and_then(Value::as_object)
+ {
+ if let Some(field_schema) = portable_properties.get("target") {
+ properties.insert("target".into(), field_schema.clone());
+ }
+ }
+ }
+ schema
+}
+
/// Centralised tool name → capability tokens map. Lookup is by name so
/// platform-specific tool modules don't have to declare their own
/// capabilities — keeps the additive-only contract tight and avoids
@@ -234,9 +259,10 @@ impl ToolDef {
/// `system.permissions.tcc.accessibility`,
/// `system.permissions.tcc.screen_recording`
/// - `system.config.read`, `system.config.write`
-/// - `session.lifecycle.start`, `session.lifecycle.end`,
-/// `session.capture_scope`, `session.capture_scope.read`,
-/// `session.capture_scope.escalate`
+/// - `session.lifecycle.start`, `session.lifecycle.read`,
+/// `session.lifecycle.list`, `session.lifecycle.end`, plus the deprecated
+/// `session.capture_scope`, `session.capture_scope.read`, and
+/// `session.capture_scope.escalate` compatibility tokens
/// - `agent_cursor.move`, `agent_cursor.set_enabled`,
/// `agent_cursor.set_motion`, `agent_cursor.set_theme`,
/// `agent_cursor.state`
@@ -561,7 +587,9 @@ pub struct ToolRegistry {
pub recording: Arc<RecordingSession>,
replay_registry: ReplayRegistrySlot,
session_end_hooks: Vec<crate::session::SessionEndHookRegistration>,
+ session_revive_hooks: Vec<crate::session::SessionReviveHookRegistration>,
cursor_outcome_readers: Vec<crate::session::CursorOutcomeReaderRegistration>,
+ _recording_state_readers: Vec<crate::session::RecordingStateReaderRegistration>,
runtime_cleanups: Vec<RuntimeCleanup>,
/// Runtime-owned protected-consent broker shared by every resource
/// adapter. Keeping it at the canonical dispatch boundary prevents
@@ -610,13 +638,24 @@ impl ToolRegistry {
});
}
});
+ let recording = Arc::new(RecordingSession::new());
+ let weak_recording = Arc::downgrade(&recording);
+ let recording_state_reader =
+ crate::session::register_scoped_recording_state_reader(Arc::new(move |session_id| {
+ weak_recording.upgrade().is_some_and(|recording| {
+ let state = recording.current_state();
+ state.enabled && state.owner.as_deref() == Some(session_id)
+ })
+ }));
Self {
tools: HashMap::new(),
order: Vec::new(),
- recording: Arc::new(RecordingSession::new()),
+ recording,
replay_registry: Arc::new(std::sync::Mutex::new(std::sync::Weak::new())),
session_end_hooks: vec![session_end_hook],
+ session_revive_hooks: Vec::new(),
cursor_outcome_readers: Vec::new(),
+ _recording_state_readers: vec![recording_state_reader],
runtime_cleanups: Vec::new(),
approval_broker,
protected_resource_grants,
@@ -715,6 +754,13 @@ impl ToolRegistry {
self.session_end_hooks.push(registration);
}
+ pub fn retain_session_revive_hook(
+ &mut self,
+ registration: crate::session::SessionReviveHookRegistration,
+ ) {
+ self.session_revive_hooks.push(registration);
+ }
+
pub fn retain_cursor_outcome_reader(
&mut self,
registration: crate::session::CursorOutcomeReaderRegistration,
@@ -740,15 +786,19 @@ impl ToolRegistry {
self.register(Box::new(crate::recording_tools::InstallFfmpegTool));
}
- /// Register the platform-independent session-lifecycle tools
- /// (`start_session` / `end_session`). Call alongside
+ /// Register the platform-independent lifecycle and compatibility tools
+ /// (`start_session`, `get_session`, `list_sessions`, `end_session`, and
+ /// the legacy capture-scope readers). Call alongside
/// `register_recording_tools` from each platform's `register_all`.
pub fn register_session_tools(&mut self) {
use crate::session_tools::{
- EndSessionTool, EscalateSessionTool, GetSessionStateTool, StartSessionTool,
+ EndSessionTool, EscalateSessionTool, GetSessionStateTool, GetSessionTool,
+ ListSessionsTool, StartSessionTool,
};
self.register(Box::new(StartSessionTool));
self.register(Box::new(EscalateSessionTool));
+ self.register(Box::new(GetSessionTool));
+ self.register(Box::new(ListSessionsTool));
self.register(Box::new(GetSessionStateTool));
self.register(Box::new(EndSessionTool));
}
@@ -959,6 +1009,11 @@ impl ToolRegistry {
return ToolResult::error(format!("Unknown tool: {name}"));
};
+ if let Err(result) = crate::action_target::normalize_action_target(resolved_name, &mut args)
+ {
+ return result;
+ }
+
// This registry is the canonical native dispatch boundary shared by
// the same-process SDK and every transport adapter. Authorization must
// live here: transport-only checks leave CuaDriver::create() able to
@@ -981,8 +1036,19 @@ impl ToolRegistry {
// caller-chosen label alone. Translate it only after authorization so
// policy and manifests continue to evaluate the public request.
let runtime_prefix = namespace_runtime_args(&mut args, context, evidence);
+ if session_selecting_tool(resolved_name)
+ && args.get("_session_id").and_then(Value::as_str).is_none()
+ {
+ let implicit = args
+ .get("_transport_session_id")
+ .and_then(Value::as_str)
+ .map(str::to_owned)
+ .unwrap_or_else(|| format!("{runtime_prefix}implicit-direct"));
+ args["_session_id"] = Value::String(implicit.clone());
+ args["_transport_session_id"] = Value::String(implicit);
+ }
let runtime_session = args
- .get("session")
+ .get("_session_id")
.and_then(Value::as_str)
.map(str::to_owned);
if let Some(session) = runtime_session.as_deref() {
@@ -996,7 +1062,6 @@ impl ToolRegistry {
restore_public_runtime_result(&mut result, &runtime_prefix);
return result;
}
- crate::session::touch_session(session);
}
// Reject modality violations before reserving a recording turn. A
@@ -1292,6 +1357,49 @@ impl ToolRegistry {
}
}
+ let lifecycle_dispatch =
+ if session_requiring_tool(resolved_name) && resolved_name != "start_session" {
+ let Some(session_id) = runtime_session.as_deref() else {
+ return protected_refusal(
+ "session_unavailable",
+ "an admitted session-requiring call has no lifecycle identity",
+ );
+ };
+ let owner = args
+ .get("_transport_session_id")
+ .and_then(Value::as_str)
+ .unwrap_or(session_id);
+ let public_label = args.get("_public_session_label").and_then(Value::as_str);
+ let (transport, client_kind) = crate::session::infer_transport_metadata(owner);
+ let admitted = match context.lifecycle_idle_ttl_override() {
+ Some(idle_ttl) => crate::session::begin_session_dispatch_with_ttl(
+ session_id,
+ public_label,
+ owner,
+ public_label.is_none(),
+ transport,
+ client_kind,
+ idle_ttl,
+ ),
+ None => crate::session::begin_session_dispatch(
+ session_id,
+ public_label,
+ owner,
+ public_label.is_none(),
+ transport,
+ client_kind,
+ ),
+ };
+ match admitted {
+ Ok(guard) => Some(guard),
+ Err(message) => {
+ return protected_refusal("session_ended", message);
+ }
+ }
+ } else {
+ None
+ };
+
// Capture start time for recording timestamps only after validation.
let launch_snapshot = if resolved_name == "launch_app" {
self.snapshot_running_pids().await
@@ -1336,6 +1444,7 @@ impl ToolRegistry {
.flatten();
let mut result = tool.invoke(args.clone()).await;
+ drop(lifecycle_dispatch);
// The platform worker has exited, so another text operation for this
// pid may now start even while result projection and evidence capture
// finish for the completed call.
@@ -1381,12 +1490,6 @@ impl ToolRegistry {
// recording/PiP screenshots would unnecessarily block an unrelated
// runtime after the input side effect has already completed.
drop(_desktop_action);
- // A long-running authorized action is active work, not idle time.
- // Refresh again at completion so the idle TTL measures the gap
- // between calls rather than time spent executing the previous call.
- if let Some(session) = runtime_session.as_deref() {
- crate::session::touch_session(session);
- }
restore_public_runtime_result(&mut result, &runtime_prefix);
// Preserve the producer's private summary for recording/replay before
// the public ActionResult projection deliberately replaces legacy
@@ -2034,12 +2137,12 @@ impl ToolRegistry {
{
return Err(
ToolResult::error(
- "config key 'capture_scope' is retired; pass capture_scope=auto|window|desktop to start_session",
+ "config key 'capture_scope' is retired; select a window or desktop target on each action",
)
.with_structured(serde_json::json!({
"code": "config_key_retired",
"key": "capture_scope",
- "replacement": "start_session.capture_scope",
+ "replacement": "action.target",
})),
);
}
@@ -2355,6 +2458,13 @@ fn namespace_runtime_args(
);
}
}
+ if let Some(idle_ttl) = context.lifecycle_idle_ttl_override() {
+ let idle_ttl_ms = idle_ttl.as_millis().min(u64::MAX as u128) as u64;
+ arguments.insert(
+ "_session_idle_ttl_ms".to_owned(),
+ Value::Number(idle_ttl_ms.into()),
+ );
+ }
// The registry is the first boundary shared by every transport and the
// direct SDK. Transport adapters may already have injected `_session_id`,
// but a direct runtime call only carries the public `session` field. Mint
@@ -2395,6 +2505,26 @@ fn namespace_runtime_args(
runtime_prefix
}
+fn session_requiring_tool(tool_name: &str) -> bool {
+ !matches!(
+ tool_name,
+ "check_permissions"
+ | "health_report"
+ | "get_session"
+ | "list_sessions"
+ | "get_session_state"
+ | "end_session"
+ )
+}
+
+fn session_selecting_tool(tool_name: &str) -> bool {
+ session_requiring_tool(tool_name)
+ || matches!(
+ tool_name,
+ "get_session" | "list_sessions" | "get_session_state" | "end_session"
+ )
+}
+
fn publish_action_result(result: &mut ToolResult) -> Result<(), String> {
let action = result
.action_record
@@ -3345,18 +3475,16 @@ resources:
#[tokio::test]
async fn standard_sessionless_owned_process_termination_reproves_the_fingerprint() {
- // A sessionless launch_app records provenance in the runtime-scoped
- // anonymous bucket, so the matching sessionless kill_app can reprove
- // it. Ownership used to be recorded only for calls carrying a
- // session, which left launch-then-kill without one permanently
- // refused even though this runtime had just started the process.
+ // A call without a public label now receives the runtime's implicit
+ // lifecycle identity, so launch provenance and the matching kill_app
+ // resolve through that stable private bucket.
let hits = Arc::new(AtomicUsize::new(0));
let registry = attested_registry("kill_app", None, hits.clone(), false);
let context = standard_context();
registry
.protected_resource_ownership()
.mark_driver_owned_process(
- &context.runtime_session_key("\u{0}anonymous-launch"),
+ &context.runtime_session_key("implicit-direct"),
crate::browser::ProcessFingerprint {
pid: 424242,
start_time: Some(7),
@@ -3397,6 +3525,57 @@ resources:
);
}
+ #[tokio::test]
+ async fn lifecycle_session_selection_cannot_turn_a_denied_action_into_allow() {
+ let hits = Arc::new(AtomicUsize::new(0));
+ let registry = attested_registry("kill_app", None, hits.clone(), false);
+ let context = standard_context();
+ let runtime_prefix = context.runtime_session_key("");
+ let before = crate::session::list_session_snapshots_with_prefix(
+ &runtime_prefix,
+ crate::session::DEFAULT_SESSION_IDLE_TTL,
+ )
+ .len();
+ let variants = [
+ serde_json::json!({"pid": 424242}),
+ serde_json::json!({"pid": 424242, "session": "named-a"}),
+ serde_json::json!({"pid": 424242, "session": "named-b"}),
+ serde_json::json!({
+ "pid": 424242,
+ "session": "named-a",
+ "_session_id": "forged-private-session",
+ "_transport_session_id": "forged-transport"
+ }),
+ ];
+ let mut refusal_codes = Vec::new();
+ for arguments in variants {
+ let result = registry
+ .invoke_with_context("kill_app", arguments, context.clone())
+ .await;
+ refusal_codes.push(
+ result
+ .structured_content
+ .as_ref()
+ .and_then(|value| value.pointer("/refusal/code"))
+ .and_then(serde_json::Value::as_str)
+ .map(str::to_owned),
+ );
+ }
+ assert_eq!(hits.load(Ordering::SeqCst), 0);
+ assert!(refusal_codes
+ .iter()
+ .all(|code| code.as_deref() == Some("foreign_process_termination_denied")));
+ assert_eq!(
+ crate::session::list_session_snapshots_with_prefix(
+ &runtime_prefix,
+ crate::session::DEFAULT_SESSION_IDLE_TTL,
+ )
+ .len(),
+ before,
+ "denied calls must not create or refresh lifecycle sessions"
+ );
+ }
+
#[tokio::test]
async fn sessionless_termination_cannot_reach_a_session_scoped_launch() {
// The anonymous bucket must not become a backdoor into another
@@ -4273,6 +4452,8 @@ mod capability_tests {
"set_config",
// sessions
"start_session",
+ "get_session",
+ "list_sessions",
"escalate_session",
"get_session_state",
"end_session",
@@ -4354,6 +4535,8 @@ mod capability_tests {
"system.config.write",
// sessions
"session.lifecycle.start",
+ "session.lifecycle.read",
+ "session.lifecycle.list",
"session.lifecycle.end",
"session.capture_scope",
"session.capture_scope.read",
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool_schema.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool_schema.rs
index c7e0bb1b51..7a73c2252a 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool_schema.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool_schema.rs
@@ -24,14 +24,12 @@ use serde_json::{json, Value};
// ── Fragments ────────────────────────────────────────────────────────────────
-/// `session` — the per-run agent-cursor identity. Uniform across every tool.
+/// `session` is an optional public lifecycle label. Uniform across every tool.
pub fn session_schema() -> Value {
json!({
"type": "string",
- "description": "Optional session id: declares/uses the agent cursor and \
- per-session state for this run. The same id works over MCP, the CLI, \
- or the raw socket, and follows the run across apps/windows. Omit to \
- run cursor-less."
+ "description": "Optional public session label. Omit it to use the \
+ authenticated transport's implicit lifecycle session."
})
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/window_inspection.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/window_inspection.rs
index 62a8aee325..79d7234699 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/window_inspection.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/window_inspection.rs
@@ -45,12 +45,11 @@ pub fn mark_browser_chrome_capture_coverage(
},
"recovery": {
"when": "verified_window_action_ineffective",
- "escalate": {
- "tool": "escalate_session",
- "reason": "foreground_ineffective"
- },
"inspect": "get_desktop_state",
- "act_scope": "desktop",
+ "act_target": {
+ "kind": "desktop",
+ "display_id": "primary"
+ },
"verify": "get_desktop_state"
}
});
@@ -92,17 +91,17 @@ mod tests {
before["capture_coverage"]["recovery"]["when"],
"verified_window_action_ineffective"
);
- assert_eq!(
- before["capture_coverage"]["recovery"]["escalate"],
- json!({
- "tool": "escalate_session",
- "reason": "foreground_ineffective"
- })
- );
+ assert!(before["capture_coverage"]["recovery"]
+ .get("escalate")
+ .is_none());
assert_eq!(
before["capture_coverage"]["recovery"]["inspect"],
"get_desktop_state"
);
+ assert_eq!(
+ before["capture_coverage"]["recovery"]["act_target"],
+ json!({"kind": "desktop", "display_id": "primary"})
+ );
assert!(before.get("browser_chrome_prompt").is_none());
}
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 03d8c8d38d..5c54e4d322 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
@@ -329,6 +329,11 @@ struct AbiTrustedSessionOptions {
ttl_seconds: u64,
idle_ttl_seconds: u64,
bounded_manifest_path: Option<String>,
+ /// Host-generated lifecycle lease identity. This field is accepted only
+ /// by the in-process Rust bridge; it is not part of the generated public
+ /// TrustedSessionOptions record or any agent-visible tool schema.
+ #[serde(default)]
+ transport_session: Option<String>,
}
fn with_ffi_guard(
@@ -774,7 +779,10 @@ pub unsafe extern "C" fn cua_driver_session_create_v1(
.transpose()?;
let request = DelegatedSessionRequest {
public_session: options.public_session,
- transport_session: format!("direct-{}", uuid::Uuid::new_v4()),
+ transport_session: options
+ .transport_session
+ .filter(|value| !value.trim().is_empty())
+ .unwrap_or_else(|| format!("direct-{}", uuid::Uuid::new_v4())),
mode: options.mode,
ttl: Duration::from_secs(options.ttl_seconds),
idle_ttl: Duration::from_secs(options.idle_ttl_seconds),
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 a6c9c7d8c7..4eb7b05bd3 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
@@ -8,8 +8,9 @@
use cua_driver_contract::{
ActionResult, ClickInput, ClipboardReadInput, ClipboardWriteInput, DragInput, EndSessionInput,
EndSessionOutput, EscalateSessionInput, GetAgentCursorStateInput, GetCursorPositionInput,
- GetDesktopStateInput, GetScreenSizeInput, GetSessionStateInput, HotkeyInput, InvokeMenuInput,
- MoveCursorInput, PressKeyInput, ScrollInput, SessionStateOutput, SetAgentCursorEnabledInput,
+ GetDesktopStateInput, GetScreenSizeInput, GetSessionInput, GetSessionStateInput, HotkeyInput,
+ InvokeMenuInput, ListSessionsInput, ListSessionsOutput, MoveCursorInput, PressKeyInput,
+ ScrollInput, SessionOutput, SessionStateOutput, SetAgentCursorEnabledInput,
SetAgentCursorMotionInput, SetAgentCursorThemeInput, SetWindowFrameInput, StartSessionInput,
StartSessionOutput, ToolInput, TypeTextInput, VerifyStateInput, VerifyStateOutput,
};
@@ -43,6 +44,43 @@ use runtime::RuntimeOptions;
use service_session::ServiceSessionClient;
use worker::{ActionCompletion, PrivateWorkerClient};
+fn host_sessions_json_for_prefix(runtime_prefix: &str) -> Value {
+ let sessions = cua_driver_core::session::list_session_snapshots_with_prefix(
+ runtime_prefix,
+ cua_driver_core::session::DEFAULT_SESSION_IDLE_TTL,
+ )
+ .into_iter()
+ .map(|session| {
+ let transport = match session.transport {
+ cua_driver_core::session::SessionTransport::Cli => "cli",
+ cua_driver_core::session::SessionTransport::Daemon => "daemon",
+ cua_driver_core::session::SessionTransport::McpStdio => "mcp_stdio",
+ cua_driver_core::session::SessionTransport::McpHttp => "mcp_http",
+ };
+ let client_kind = match session.client_kind {
+ cua_driver_core::session::SessionClientKind::Cli => "cli",
+ cua_driver_core::session::SessionClientKind::Direct => "direct",
+ cua_driver_core::session::SessionClientKind::Mcp => "mcp",
+ cua_driver_core::session::SessionClientKind::PythonSdk => "python_sdk",
+ cua_driver_core::session::SessionClientKind::TypescriptSdk => "typescript_sdk",
+ };
+ serde_json::json!({
+ "session": session.public_label.as_deref().and_then(cursor_overlay::sanitize_session_label),
+ "implicit": session.implicit,
+ "state": if session.ending { "ending" } else { "active" },
+ "client_kind": client_kind,
+ "transport": transport,
+ "cursor_visible": cua_driver_core::session::cursor_visible(&session.runtime_id),
+ "recording_active": cua_driver_core::session::recording_active(&session.runtime_id),
+ "started_seconds_ago": session.started_for.as_secs(),
+ "idle_seconds": session.idle.as_secs(),
+ "expires_in_seconds": session.expires_in.as_secs(),
+ })
+ })
+ .collect::<Vec<_>>();
+ serde_json::json!({"count": sessions.len(), "sessions": sessions})
+}
+
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
pub struct ImageContent {
pub mime_type: String,
@@ -241,11 +279,15 @@ enum DriverBackend {
struct DaemonBackend {
socket_path: String,
+ transport_session: String,
}
impl DaemonBackend {
fn new(socket_path: String) -> Arc<Self> {
- Arc::new(Self { socket_path })
+ Arc::new(Self {
+ socket_path,
+ transport_session: format!("sdk-{}", uuid::Uuid::new_v4()),
+ })
}
async fn compatible_metadata(&self) -> Result<DaemonMetadata, DriverError> {
@@ -268,6 +310,20 @@ impl DaemonBackend {
}
}
+impl Drop for DaemonBackend {
+ fn drop(&mut self) {
+ let request = DaemonRequest {
+ method: "session_end".into(),
+ name: None,
+ args: None,
+ session_id: Some(self.transport_session.clone()),
+ observation_origin: Some(ToolObservationOrigin::Direct),
+ client_kind: Some(DaemonClientKind::Unknown),
+ };
+ let _ = send_request(&self.socket_path, &request);
+ }
+}
+
fn validate_daemon_metadata(metadata: &DaemonMetadata) -> Result<(), DriverError> {
let mismatch = if metadata.contract_version != cua_driver_contract::CONTRACT_VERSION {
Some(format!(
@@ -606,6 +662,8 @@ macro_rules! define_exported_tool_names {
const EXPORTED_TOOL_NAMES: &[&str] = &[
<StartSessionInput as ToolInput>::TOOL_NAME,
<EscalateSessionInput as ToolInput>::TOOL_NAME,
+ <GetSessionInput as ToolInput>::TOOL_NAME,
+ <ListSessionsInput as ToolInput>::TOOL_NAME,
<GetSessionStateInput as ToolInput>::TOOL_NAME,
<EndSessionInput as ToolInput>::TOOL_NAME,
$(<$input as ToolInput>::TOOL_NAME,)*
@@ -999,6 +1057,39 @@ impl CuaDriver {
}
}
+ /// Daemon-host bridge for reconnecting one trusted host lease without
+ /// exposing its transport identity through generated bindings.
+ #[doc(hidden)]
+ pub fn create_trusted_session_for_transport(
+ &self,
+ options: TrustedSessionOptions,
+ transport_session: &str,
+ ) -> Result<Arc<CuaDriverSession>, DriverError> {
+ let DriverBackend::Embedded(runtime) = &self.backend else {
+ return Err(DriverError::Configuration {
+ reason:
+ "stable trusted-session transport binding requires an embedded host runtime"
+ .into(),
+ });
+ };
+ if transport_session.trim().is_empty() {
+ return Err(DriverError::Configuration {
+ reason: "trusted-session transport identity must not be empty".into(),
+ });
+ }
+ let native_options = serde_json::json!({
+ "public_session": options.public_session,
+ "mode": options.mode.as_str(),
+ "ttl_seconds": options.ttl_seconds,
+ "idle_ttl_seconds": options.idle_ttl_seconds,
+ "bounded_manifest_path": options.bounded_manifest_path,
+ "transport_session": transport_session,
+ });
+ Ok(Arc::new(CuaDriverSession {
+ backend: SessionBackend::Embedded(Arc::new(runtime.create_session(native_options)?)),
+ }))
+ }
+
/// Bind a trusted session through an authenticated remote carrier without
/// exposing serialized authority to the caller.
pub async fn create_remote_trusted_session(
@@ -1207,7 +1298,7 @@ impl CuaDriver {
method: "list".into(),
name: None,
args: None,
- session_id: None,
+ session_id: Some(daemon.transport_session.clone()),
observation_origin: Some(ToolObservationOrigin::Direct),
client_kind: Some(self.client_kind),
};
@@ -1236,6 +1327,54 @@ impl CuaDriver {
})
}
+ /// Content-free lifecycle summaries for the trusted host's runtime or
+ /// host-lease namespace. This is deliberately separate from the
+ /// agent-facing `list_sessions` tool, whose view is transport scoped.
+ pub async fn list_host_sessions_json(&self) -> Result<String, DriverError> {
+ let result = match &self.backend {
+ DriverBackend::Embedded(runtime) => {
+ let prefix = format!("__cua_runtime_{}:", runtime.runtime_scope_key());
+ host_sessions_json_for_prefix(&prefix)
+ }
+ DriverBackend::PrivateWorker(worker) => worker.list_host_sessions().await?,
+ DriverBackend::Remote(remote) => remote.list_host_sessions().await?,
+ DriverBackend::Daemon(daemon) => {
+ daemon.compatible_metadata().await?;
+ let socket_path = daemon.socket_path.clone();
+ let request_path = socket_path.clone();
+ let request = DaemonRequest {
+ method: "sessions_list".into(),
+ name: None,
+ args: None,
+ session_id: None,
+ observation_origin: Some(ToolObservationOrigin::Direct),
+ client_kind: Some(self.client_kind),
+ };
+ let response =
+ tokio::task::spawn_blocking(move || send_request(&request_path, &request))
+ .await
+ .map_err(|error| DriverError::Protocol {
+ reason: format!("host session listing task failed: {error}"),
+ })?
+ .map_err(|error| DriverError::Transport {
+ socket_path,
+ reason: error.to_string(),
+ })?;
+ if !response.ok {
+ return Err(DriverError::Protocol {
+ reason: response
+ .error
+ .unwrap_or_else(|| "host session listing failed".into()),
+ });
+ }
+ response.result.unwrap_or(Value::Null)
+ }
+ };
+ serde_json::to_string(&result).map_err(|error| DriverError::Protocol {
+ reason: error.to_string(),
+ })
+ }
+
pub async fn start_session(
&self,
input: StartSessionInput,
@@ -1263,6 +1402,21 @@ impl CuaDriver {
.typed_success(GetSessionStateInput::TOOL_NAME)
}
+ pub async fn get_session(&self, input: GetSessionInput) -> Result<SessionOutput, DriverError> {
+ self.invoke_typed(GetSessionInput::TOOL_NAME, input)
+ .await?
+ .typed_success(GetSessionInput::TOOL_NAME)
+ }
+
+ pub async fn list_sessions(
+ &self,
+ input: ListSessionsInput,
+ ) -> Result<ListSessionsOutput, DriverError> {
+ self.invoke_typed(ListSessionsInput::TOOL_NAME, input)
+ .await?
+ .typed_success(ListSessionsInput::TOOL_NAME)
+ }
+
pub async fn end_session(
&self,
input: EndSessionInput,
@@ -1326,6 +1480,21 @@ impl CuaDriverSession {
.typed_success(GetSessionStateInput::TOOL_NAME)
}
+ pub async fn get_session(&self, input: GetSessionInput) -> Result<SessionOutput, DriverError> {
+ self.invoke_typed(GetSessionInput::TOOL_NAME, input)
+ .await?
+ .typed_success(GetSessionInput::TOOL_NAME)
+ }
+
+ pub async fn list_sessions(
+ &self,
+ input: ListSessionsInput,
+ ) -> Result<ListSessionsOutput, DriverError> {
+ self.invoke_typed(ListSessionsInput::TOOL_NAME, input)
+ .await?
+ .typed_success(ListSessionsInput::TOOL_NAME)
+ }
+
pub async fn end_session(
&self,
input: EndSessionInput,
@@ -1460,7 +1629,7 @@ impl CuaDriver {
method: "call".into(),
name: Some(name.into()),
args: Some(arguments),
- session_id: None,
+ session_id: Some(daemon.transport_session.clone()),
observation_origin: Some(ToolObservationOrigin::Direct),
client_kind: Some(self.client_kind),
};
@@ -1864,6 +2033,47 @@ mod tests {
));
}
+ #[tokio::test]
+ async fn trusted_host_listing_spans_its_runtime_without_exposing_owner_keys() {
+ let _runtime_test = crate::runtime::TEST_RUNTIME_LOCK.lock().unwrap();
+ let driver = CuaDriver::create(None).unwrap();
+ let public = format!("host-listing-{}", uuid::Uuid::new_v4());
+ driver
+ .start_session(StartSessionInput {
+ session: Some(public.clone()),
+ capture_scope: None,
+ cursor_theme: None,
+ })
+ .await
+ .unwrap();
+
+ let listed: Value =
+ serde_json::from_str(&driver.list_host_sessions_json().await.unwrap()).unwrap();
+ let session = listed["sessions"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|session| {
+ session["session"]
+ .as_str()
+ .is_some_and(|label| label.starts_with("host-listing-"))
+ })
+ .unwrap_or_else(|| {
+ panic!("host-scoped listing omitted its live named session: {listed}")
+ });
+ assert_eq!(session["implicit"], false);
+ assert!(session.get("owner_transport").is_none());
+ assert!(session.get("runtime_id").is_none());
+
+ driver
+ .end_session(EndSessionInput {
+ session: Some(public),
+ })
+ .await
+ .unwrap();
+ driver.shutdown().await.unwrap();
+ }
+
#[tokio::test]
async fn shutdown_drains_an_already_admitted_call() {
let _runtime_test = crate::runtime::TEST_RUNTIME_LOCK.lock().unwrap();
@@ -2116,6 +2326,44 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn trusted_session_idle_ttl_reaches_the_lifecycle_contract() {
+ let _runtime_test = crate::runtime::TEST_RUNTIME_LOCK.lock().unwrap();
+ let driver = configured_standard_driver();
+ let session = driver
+ .create_trusted_session(TrustedSessionOptions {
+ public_session: "trusted-lifecycle-ttl".into(),
+ mode: SessionPermissionMode::Standard,
+ ttl_seconds: 60,
+ idle_ttl_seconds: 2,
+ bounded_manifest_path: None,
+ })
+ .unwrap();
+
+ let started = session
+ .call_tool("start_session".into(), "{}".into())
+ .await
+ .unwrap();
+ assert!(!started.is_error, "{}", started.text);
+
+ let inspected = session
+ .call_tool("get_session".into(), "{}".into())
+ .await
+ .unwrap();
+ assert!(!inspected.is_error, "{}", inspected.text);
+ let lifecycle: Value =
+ serde_json::from_str(inspected.structured_json.as_deref().unwrap()).unwrap();
+ let expires_in = lifecycle["expires_in_seconds"].as_u64().unwrap();
+ assert!(
+ expires_in <= 2,
+ "trusted lifecycle TTL was not applied: {lifecycle}"
+ );
+ assert_eq!(lifecycle["session"], "trusted-lifecycle-ttl");
+
+ session.close();
+ driver.shutdown().await.unwrap();
+ }
+
#[tokio::test]
async fn authorization_expiry_in_one_runtime_does_not_affect_another() {
let _runtime_test = crate::runtime::TEST_RUNTIME_LOCK.lock().unwrap();
@@ -2544,7 +2792,7 @@ mod tests {
let driver = CuaDriver::connect(Some(socket)).unwrap();
let output = driver
.start_session(StartSessionInput {
- session: "run-2".into(),
+ session: Some("run-2".into()),
capture_scope: Some(cua_driver_contract::CaptureScope::Auto),
cursor_theme: None,
})
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote.rs
index 48db07017d..0b6729ce7c 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/remote.rs
@@ -136,6 +136,10 @@ impl RemoteDriverClient {
exchange(&self.channel, "list", None, None).await
}
+ pub(crate) async fn list_host_sessions(&self) -> Result<Value, DriverError> {
+ exchange(&self.channel, "sessions_list", None, None).await
+ }
+
pub(crate) async fn invoke(&self, name: &str, arguments: Value) -> Result<Value, DriverError> {
exchange(
&self.channel,
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 793dee0fc3..deda518ad1 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
@@ -132,7 +132,11 @@ impl RuntimeSession {
.runtime
.invoke_with_context(name, args, self.context.clone())
.await;
- if name == "end_session" && result.is_some() {
+ if name == "end_session"
+ && result
+ .as_ref()
+ .is_some_and(|result| result.is_error != Some(true))
+ {
self.authorization_registry
.revoke_connection(&self.connection);
}
@@ -556,16 +560,17 @@ fn build_registry(options: &RuntimeOptions) -> ToolRegistry {
register_host_tools(&mut registry);
}
let recording = Arc::downgrade(&registry.recording);
- let recording_session_end =
- cua_driver_core::session::register_scoped_session_end_hook(move |session| {
+ let recording_session_end = cua_driver_core::session::register_scoped_fallible_session_end_hook(
+ "recording",
+ move |session| {
let Some(recording) = recording.upgrade() else {
- return;
+ return Ok(());
};
- let session = session.to_owned();
- std::thread::spawn(move || {
- let _ = recording.stop_owner(Some(&session));
- });
- });
+ recording
+ .stop_owner(Some(session))
+ .map_err(|error| error.to_string())
+ },
+ );
registry.retain_session_end_hook(recording_session_end);
registry
}
@@ -718,7 +723,7 @@ mod tests {
let idle_before_refresh =
cua_driver_core::session::session_idle_duration(&internal).unwrap();
runtime
- .invoke("health_report", serde_json::json!({"session": public}))
+ .invoke("start_session", serde_json::json!({"session": public}))
.await
.unwrap();
let idle_after_refresh =
@@ -785,4 +790,82 @@ mod tests {
runtime.shutdown().await;
}
+
+ #[tokio::test]
+ async fn incomplete_end_keeps_trusted_authorization_live_for_cleanup_retry() {
+ let _runtime_test = TEST_RUNTIME_LOCK.lock().unwrap();
+ let runtime = DriverRuntime::create(standard_options()).unwrap();
+ let public_session = "runtime-end-cleanup-retry";
+ let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let attempts_for_hook = attempts.clone();
+ let _hook = cua_driver_core::session::register_scoped_fallible_session_end_hook(
+ "runtime-end-cleanup-retry-test",
+ move |_| {
+ if attempts_for_hook.fetch_add(1, Ordering::SeqCst) == 0 {
+ Err("synthetic first-attempt failure".into())
+ } else {
+ Ok(())
+ }
+ },
+ );
+ let session = runtime
+ .create_trusted_session(DelegatedSessionRequest {
+ public_session: public_session.into(),
+ transport_session: "runtime-end-cleanup-retry-transport".into(),
+ mode: PermissionMode::Standard,
+ ttl: Duration::from_secs(60),
+ idle_ttl: Duration::from_secs(30),
+ bounded_manifest: None,
+ })
+ .unwrap();
+
+ let started = session
+ .invoke("start_session", serde_json::json!({}))
+ .await
+ .unwrap();
+ assert_ne!(started.is_error, Some(true));
+ let runtime_prefix = format!(
+ "__cua_runtime_{}:",
+ runtime.compatibility_context.runtime_scope_key()
+ );
+ let started_sessions = cua_driver_core::session::list_session_snapshots_with_prefix(
+ &runtime_prefix,
+ Duration::from_secs(300),
+ );
+ assert_eq!(started_sessions.len(), 1, "{started_sessions:?}");
+
+ let first_end = session
+ .invoke("end_session", serde_json::json!({}))
+ .await
+ .unwrap();
+ assert_eq!(
+ first_end.is_error,
+ Some(true),
+ "result={first_end:?} started={started_sessions:?} attempts={}",
+ attempts.load(Ordering::SeqCst)
+ );
+ assert_eq!(attempts.load(Ordering::SeqCst), 1);
+
+ let retried_end = session
+ .invoke("end_session", serde_json::json!({}))
+ .await
+ .unwrap();
+ assert_ne!(retried_end.is_error, Some(true));
+ assert_eq!(attempts.load(Ordering::SeqCst), 2);
+
+ let after_end = session
+ .invoke("health_report", serde_json::json!({}))
+ .await
+ .unwrap();
+ assert_eq!(
+ after_end
+ .structured_content
+ .as_ref()
+ .and_then(|value| value.pointer("/refusal/code"))
+ .and_then(Value::as_str),
+ Some("authorization_revoked")
+ );
+
+ runtime.shutdown().await;
+ }
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/service_session.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/service_session.rs
index 18eefe3d87..302049fd40 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/service_session.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/service_session.rs
@@ -8,11 +8,14 @@ use cua_driver_core::daemon::{DaemonClientKind, DaemonRequest, DaemonResponse};
use serde_json::Value;
use std::io::{BufRead, BufReader, Write};
use std::sync::{Arc, Mutex};
+use std::time::Duration;
#[cfg(unix)]
-use std::time::{Duration, Instant};
+use std::time::Instant;
#[cfg(unix)]
const SERVICE_REQUEST_DEADLINE: Duration = Duration::from_secs(120);
+const RESUME_REGISTRATION_RETRIES: usize = 20;
+const RESUME_REGISTRATION_DELAY: Duration = Duration::from_millis(10);
#[cfg(unix)]
type ServiceStream = std::os::unix::net::UnixStream;
@@ -23,6 +26,7 @@ struct ServiceConnection {
reader: BufReader<ServiceStream>,
writer: ServiceStream,
closed: bool,
+ resume_credential: String,
}
pub(crate) struct ServiceSessionClient {
@@ -55,12 +59,13 @@ impl ServiceSessionClient {
reader: BufReader::new(stream),
writer,
closed: false,
+ resume_credential: String::new(),
}),
});
let arguments = serde_json::to_value(options).map_err(|error| DriverError::Protocol {
reason: format!("serialize trusted service session options: {error}"),
})?;
- client.request(DaemonRequest {
+ let bound = client.request(DaemonRequest {
method: "trusted_session_begin".into(),
name: None,
args: Some(arguments),
@@ -68,6 +73,14 @@ impl ServiceSessionClient {
observation_origin: None,
client_kind: Some(client_kind),
})?;
+ let resume_credential = bound
+ .get("resume_credential")
+ .and_then(Value::as_str)
+ .filter(|value| !value.is_empty())
+ .ok_or_else(|| DriverError::Protocol {
+ reason: "trusted service bind omitted resume credential".into(),
+ })?;
+ client.connection.lock().unwrap().resume_credential = resume_credential.to_owned();
Ok(client)
}
@@ -97,7 +110,9 @@ impl ServiceSessionClient {
pub(crate) fn close(&self) {
let mut connection = self.connection.lock().unwrap();
if connection.closed {
- return;
+ if self.resume_connection(&mut connection).is_err() {
+ return;
+ }
}
let request = DaemonRequest {
method: "trusted_session_end".into(),
@@ -121,7 +136,7 @@ impl ServiceSessionClient {
fn request(&self, request: DaemonRequest) -> Result<Value, DriverError> {
let mut connection = self.connection.lock().unwrap();
if connection.closed {
- return Err(DriverError::Shutdown);
+ self.resume_connection(&mut connection)?;
}
let action_call = request.method == "trusted_session_call";
write_request(&mut connection.writer, &request).map_err(|error| {
@@ -172,6 +187,85 @@ impl ServiceSessionClient {
Ok(response.result.unwrap_or(Value::Null))
}
+ fn resume_connection(&self, connection: &mut ServiceConnection) -> Result<(), DriverError> {
+ if connection.resume_credential.is_empty() {
+ return Err(DriverError::Shutdown);
+ }
+ let credential = connection.resume_credential.clone();
+ for attempt in 0..=RESUME_REGISTRATION_RETRIES {
+ let stream = connect(&self.socket_path)?;
+ let writer = stream.try_clone().map_err(|error| DriverError::Transport {
+ socket_path: self.socket_path.clone(),
+ reason: format!("clone resumed trusted service connection: {error}"),
+ })?;
+
+ // Replace both handles before presenting the credential. Dropping
+ // the old client handles makes the daemon observe EOF and publish
+ // the detachable lease on Unix sockets and Windows named pipes.
+ connection.reader = BufReader::new(stream);
+ connection.writer = writer;
+ let request = DaemonRequest {
+ method: "trusted_session_resume".into(),
+ name: None,
+ args: Some(serde_json::json!({
+ "resume_credential": credential,
+ })),
+ session_id: None,
+ observation_origin: None,
+ client_kind: None,
+ };
+ write_request(&mut connection.writer, &request).map_err(|error| {
+ DriverError::Transport {
+ socket_path: self.socket_path.clone(),
+ reason: format!("write trusted session resume: {error}"),
+ }
+ })?;
+ let line = read_response_line(&mut connection.reader)
+ .map_err(|error| DriverError::Transport {
+ socket_path: self.socket_path.clone(),
+ reason: format!("read trusted session resume: {error}"),
+ })?
+ .ok_or_else(|| DriverError::Transport {
+ socket_path: self.socket_path.clone(),
+ reason: "trusted service closed during resume".into(),
+ })?;
+ let response: DaemonResponse =
+ serde_json::from_str(&line).map_err(|error| DriverError::Protocol {
+ reason: format!("parse trusted session resume response: {error}"),
+ })?;
+ if response.ok {
+ let rotated = response
+ .result
+ .as_ref()
+ .and_then(|value| value.get("resume_credential"))
+ .and_then(Value::as_str)
+ .filter(|value| !value.is_empty())
+ .ok_or_else(|| DriverError::Protocol {
+ reason: "trusted session resume omitted rotated credential".into(),
+ })?;
+ connection.resume_credential = rotated.to_owned();
+ connection.closed = false;
+ return Ok(());
+ }
+
+ let reason = response
+ .error
+ .unwrap_or_else(|| "trusted session resume failed".into());
+ let registration_race = reason.contains("unavailable or already used")
+ && attempt < RESUME_REGISTRATION_RETRIES;
+ if registration_race {
+ std::thread::sleep(RESUME_REGISTRATION_DELAY);
+ continue;
+ }
+ connection.resume_credential.clear();
+ return Err(DriverError::Transport {
+ socket_path: self.socket_path.clone(),
+ reason,
+ });
+ }
+ unreachable!("bounded resume loop returns on its final attempt")
+ }
+
fn connection_failure(&self, action_call: bool, reason: String) -> DriverError {
if action_call {
DriverError::ActionInterrupted {
@@ -363,7 +457,10 @@ mod tests {
writeln!(
writer,
"{}",
- serde_json::to_string(&DaemonResponse::ok(serde_json::json!({}))).unwrap()
+ serde_json::to_string(&DaemonResponse::ok(serde_json::json!({
+ "resume_credential": "resume-test-1"
+ })))
+ .unwrap()
)
.unwrap();
@@ -399,6 +496,121 @@ mod tests {
server.join().unwrap();
}
+ #[tokio::test]
+ async fn next_call_resumes_with_single_use_host_credential_after_disconnect() {
+ let directory = tempfile::tempdir().unwrap();
+ let socket = directory.path().join("resumable-service.sock");
+ let listener = UnixListener::bind(&socket).unwrap();
+ let server = std::thread::spawn(move || {
+ serve_compatible_metadata(&listener);
+ {
+ let (stream, _) = listener.accept().unwrap();
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
+ let mut writer = stream;
+ let mut line = String::new();
+ reader.read_line(&mut line).unwrap();
+ let begin: DaemonRequest = serde_json::from_str(&line).unwrap();
+ assert_eq!(begin.method, "trusted_session_begin");
+ writeln!(
+ writer,
+ "{}",
+ serde_json::to_string(&DaemonResponse::ok(serde_json::json!({
+ "resume_credential": "resume-original"
+ })))
+ .unwrap()
+ )
+ .unwrap();
+
+ line.clear();
+ reader.read_line(&mut line).unwrap();
+ let call: DaemonRequest = serde_json::from_str(&line).unwrap();
+ assert_eq!(call.method, "trusted_session_call");
+ // Drop without a response. The SDK must not retry this action.
+ }
+
+ // The reconnect can beat the daemon task that records EOF from the
+ // previous connection. A transient unavailable response must keep
+ // the single-use credential intact and retry on a fresh socket.
+ {
+ let (stream, _) = listener.accept().unwrap();
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
+ let mut writer = stream;
+ let mut line = String::new();
+ reader.read_line(&mut line).unwrap();
+ let resume: DaemonRequest = serde_json::from_str(&line).unwrap();
+ assert_eq!(resume.method, "trusted_session_resume");
+ writeln!(
+ writer,
+ "{}",
+ serde_json::to_string(&DaemonResponse::err(
+ "trusted session resume credential is unavailable or already used",
+ 77,
+ ))
+ .unwrap()
+ )
+ .unwrap();
+ }
+
+ let (stream, _) = listener.accept().unwrap();
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
+ let mut writer = stream;
+ let mut line = String::new();
+ reader.read_line(&mut line).unwrap();
+ let resume: DaemonRequest = serde_json::from_str(&line).unwrap();
+ assert_eq!(resume.method, "trusted_session_resume");
+ assert_eq!(resume.args.unwrap()["resume_credential"], "resume-original");
+ writeln!(
+ writer,
+ "{}",
+ serde_json::to_string(&DaemonResponse::ok(serde_json::json!({
+ "resume_credential": "resume-rotated"
+ })))
+ .unwrap()
+ )
+ .unwrap();
+
+ line.clear();
+ reader.read_line(&mut line).unwrap();
+ let call: DaemonRequest = serde_json::from_str(&line).unwrap();
+ assert_eq!(call.method, "trusted_session_call");
+ writeln!(
+ writer,
+ "{}",
+ serde_json::to_string(&DaemonResponse::ok(serde_json::json!({
+ "resumed": true
+ })))
+ .unwrap()
+ )
+ .unwrap();
+ });
+
+ let client = ServiceSessionClient::connect_and_bind(
+ socket.to_string_lossy().into_owned(),
+ TrustedSessionOptions {
+ public_session: "resume-test".into(),
+ mode: SessionPermissionMode::Standard,
+ ttl_seconds: 60,
+ idle_ttl_seconds: 30,
+ bounded_manifest_path: None,
+ },
+ DaemonClientKind::Unknown,
+ )
+ .unwrap();
+ assert!(matches!(
+ client.invoke("click", serde_json::json!({})).await,
+ Err(DriverError::ActionInterrupted {
+ completion: crate::worker::ActionCompletion::Unknown,
+ ..
+ })
+ ));
+ let resumed = client
+ .invoke("get_session", serde_json::json!({}))
+ .await
+ .unwrap();
+ assert_eq!(resumed["resumed"], true);
+ server.join().unwrap();
+ }
+
#[tokio::test]
async fn transient_read_timeouts_are_poll_intervals_not_action_deadlines() {
let directory = tempfile::tempdir().unwrap();
@@ -415,7 +627,10 @@ mod tests {
writeln!(
writer,
"{}",
- serde_json::to_string(&DaemonResponse::ok(serde_json::json!({}))).unwrap()
+ serde_json::to_string(&DaemonResponse::ok(serde_json::json!({
+ "resume_credential": "resume-test-2"
+ })))
+ .unwrap()
)
.unwrap();
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/worker.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/worker.rs
index 1c76c76333..638b516b75 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/worker.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/worker.rs
@@ -233,6 +233,10 @@ impl PrivateWorkerClient {
self.request_async("list", None, None, None).await
}
+ pub(crate) async fn list_host_sessions(self: &Arc<Self>) -> Result<Value, DriverError> {
+ self.request_async("sessions_list", None, None, None).await
+ }
+
pub(crate) async fn invoke(
self: &Arc<Self>,
name: &str,
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 5fc6a9dd55..6b7712210b 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
@@ -87,6 +87,12 @@ pub enum Command {
Status {
socket: Option<String>,
},
+ /// `cua-driver sessions list [--json]` — content-free operator view of
+ /// the live sessions owned by the selected daemon runtime.
+ Sessions {
+ json: bool,
+ socket: Option<String>,
+ },
Recording {
subcommand: String,
args: Vec<String>,
@@ -269,6 +275,7 @@ fn finite_command_name_from_args(args: &[String]) -> Option<&'static str> {
Some("stop") => Some("stop"),
Some("revoke") => Some("revoke"),
Some("status") => Some("status"),
+ Some("sessions") => Some("sessions"),
Some("recording") => Some("recording"),
Some("dump-docs") => Some("dump_docs"),
Some("update") => Some("update"),
@@ -346,6 +353,10 @@ fn finite_operation_from_args(args: &[String]) -> &'static str {
"reset" => "reset",
_ => "other",
},
+ Some("sessions") => match subcommand.unwrap_or("list") {
+ "list" => "list",
+ _ => "other",
+ },
Some("autostart") => match subcommand.unwrap_or("") {
"enable" => "enable",
"disable" => "disable",
@@ -432,7 +443,7 @@ pub fn parse_command() -> Command {
env!("CARGO_PKG_VERSION")
);
println!("Usage: cua-driver [SUBCOMMAND] [OPTIONS]");
- println!("Subcommands: mcp, list-tools, describe, call, serve, stop, revoke, status, config, telemetry, recording, update, check-update, doctor, diagnose, permissions, autostart, skills, browser-approve, manifest, cursor-theme");
+ println!("Subcommands: mcp, list-tools, describe, call, serve, stop, revoke, status, config, telemetry, recording, update, check-update, doctor, diagnose, permissions, autostart, skills, browser-approve, manifest, cursor-theme, sessions");
println!();
println!("permissions options (macOS):");
println!(" cua-driver permissions status Report Accessibility + Screen Recording status. Read-only (no prompt).");
@@ -712,6 +723,17 @@ pub fn parse_command() -> Command {
}
}
Some("status") => Command::Status { socket },
+ Some("sessions") => {
+ let subcommand = pos.next().unwrap_or("list");
+ if subcommand != "list" {
+ eprintln!("Unknown sessions subcommand '{subcommand}'. Valid: list");
+ process::exit(64);
+ }
+ Command::Sessions {
+ json: args.iter().any(|arg| arg == "--json"),
+ socket,
+ }
+ }
Some("recording") => {
let subcommand = pos.next().unwrap_or("status").to_string();
let rest: Vec<String> = pos.map(str::to_owned).collect();
@@ -1496,6 +1518,13 @@ pub fn build_manifest() -> serde_json::Value {
{ "name": "status",
"description": "Report daemon status (running / not / unhealthy).",
"args": [ { "name": "--socket", "type": "string", "description": "Override the daemon socket path." } ] },
+ { "name": "sessions",
+ "description": "List content-free lifecycle summaries for sessions owned by the daemon runtime.",
+ "args": [
+ { "name": "subcommand", "type": "positional-string", "description": "Only: list. Default: list." },
+ { "name": "--json", "type": "flag", "description": "Emit the machine-readable session summary." },
+ { "name": "--socket", "type": "string", "description": "Override the daemon socket path." }
+ ] },
{ "name": "list-tools",
"description": "Print the canonical tool name + one-line summary for every registered MCP tool.",
"args": [] },
@@ -1907,16 +1936,32 @@ pub fn run_call(
.clone()
.unwrap_or(serde_json::Value::Object(serde_json::Map::new()));
cua_driver_core::tool_args::sanitize_reserved_args(&mut args_for_daemon);
+ let transport_session = format!("cli-{}", uuid::Uuid::new_v4());
let req = crate::serve::DaemonRequest {
method: "call".into(),
name: Some(tool.to_owned()),
args: Some(args_for_daemon),
- // CLI one-shot is its own ephemeral, anonymous/global session.
- session_id: None,
+ // Every one-shot call owns one disposable implicit transport
+ // session. The daemon closes all lifecycle state attached to it
+ // synchronously after the response is received.
+ session_id: Some(transport_session.clone()),
observation_origin: Some(crate::serve::ToolObservationOrigin::Direct),
client_kind: Some(cua_driver_core::daemon::DaemonClientKind::Cli),
};
- match crate::serve::send_request(&socket_path, &req) {
+ let response = crate::serve::send_request(&socket_path, &req);
+ let cleanup = crate::serve::DaemonRequest {
+ method: "session_end".into(),
+ name: None,
+ args: None,
+ session_id: Some(transport_session),
+ observation_origin: None,
+ client_kind: Some(cua_driver_core::daemon::DaemonClientKind::Cli),
+ };
+ let cleanup_result = crate::serve::send_request(&socket_path, &cleanup);
+ if let Err(error) = cleanup_result {
+ eprintln!("warning: disposable session cleanup failed: {error}");
+ }
+ match response {
Ok(resp) => {
if resp.ok {
if let Some(result) = resp.result {
@@ -3677,7 +3722,7 @@ pub fn run_config_cmd(
};
if key == "capture_scope" {
eprintln!(
- "config key 'capture_scope' is retired; use start_session(capture_scope=auto|window|desktop)"
+ "config key 'capture_scope' is retired; select a window or desktop target on each action"
);
process::exit(64);
}
@@ -3718,7 +3763,7 @@ pub fn run_config_cmd(
};
if key == "capture_scope" {
eprintln!(
- "config key 'capture_scope' is retired; use start_session(capture_scope=auto|window|desktop)"
+ "config key 'capture_scope' is retired; select a window or desktop target on each action"
);
process::exit(64);
}
@@ -3936,6 +3981,11 @@ mod tests {
"set"
);
assert_eq!(finite_operation_from_args(&args(&["skills"])), "status");
+ assert_eq!(finite_operation_from_args(&args(&["sessions"])), "list");
+ assert_eq!(
+ finite_operation_from_args(&args(&["sessions", "private-value"])),
+ "other"
+ );
assert_eq!(
finite_operation_from_args(&args(&["update", "--apply"])),
"apply"
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 6d7e67c792..c94e5c7e3d 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
@@ -704,6 +704,10 @@ fn main() {
let pid_path = serve::default_pid_file_path();
serve::run_status_cmd(&sp, &pid_path);
}
+ cli::Command::Sessions { json, socket } => {
+ let sp = socket.unwrap_or_else(serve::default_socket_path);
+ serve::run_sessions_list_cmd(&sp, json);
+ }
cli::Command::Recording {
subcommand,
args,
@@ -958,6 +962,11 @@ fn main() -> anyhow::Result<()> {
serve::run_status_cmd(&sp, &pid_path);
return Ok(());
}
+ cli::Command::Sessions { json, socket } => {
+ let sp = socket.unwrap_or_else(serve::default_socket_path);
+ serve::run_sessions_list_cmd(&sp, json);
+ return Ok(());
+ }
cli::Command::Recording {
subcommand,
args,
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs b/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs
index 0de9dba09c..f5da8b3911 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs
@@ -91,6 +91,20 @@ async fn serve_conn(
sdk: Arc<crate::sdk_adapter::SdkAdapter>,
token: Arc<str>,
) -> anyhow::Result<()> {
+ let transport_session = format!("http-{}", uuid::Uuid::new_v4());
+ struct TransportCleanup {
+ sdk: Arc<crate::sdk_adapter::SdkAdapter>,
+ transport_session: String,
+ }
+ impl Drop for TransportCleanup {
+ fn drop(&mut self) {
+ self.sdk.end_transport_sessions(&self.transport_session);
+ }
+ }
+ let _cleanup = TransportCleanup {
+ sdk: sdk.clone(),
+ transport_session: transport_session.clone(),
+ };
loop {
let Some(req) = read_http_request(&mut stream, &token).await? else {
return Ok(()); // clean EOF
@@ -122,7 +136,7 @@ async fn serve_conn(
)
.await?;
} else {
- match dispatch(&req.body, &sdk).await {
+ match dispatch(&req.body, &sdk, &transport_session).await {
Some(resp_json) => {
write_http(&mut stream, 200, resp_json.as_bytes(), keep_alive).await?
}
@@ -142,13 +156,18 @@ async fn serve_conn(
/// Parse a JSON-RPC request body and dispatch via the shared MCP handler. Returns
/// `Some(json)` for a request, or `None` for a notification (no `id`). Applies the
/// caller-declared `session` identity so HTTP behaves identically to stdio.
-async fn dispatch(body: &[u8], sdk: &Arc<crate::sdk_adapter::SdkAdapter>) -> Option<String> {
+async fn dispatch(
+ body: &[u8],
+ sdk: &Arc<crate::sdk_adapter::SdkAdapter>,
+ transport_session: &str,
+) -> Option<String> {
let mut req: Request = match serde_json::from_slice(body) {
Ok(r) => r,
Err(_) => return Some(serialize(&Response::parse_error())),
};
req.id.as_ref()?;
let initialize_metadata = req.initialize_metadata();
+ apply_session_identity(&mut req, transport_session);
let session_context = req.tool_call().ok().and_then(|call| {
sdk.begin_tool_call(
&call.name,
@@ -158,7 +177,6 @@ async fn dispatch(body: &[u8], sdk: &Arc<crate::sdk_adapter::SdkAdapter>) -> Opt
)
});
let id = req.id.clone().unwrap_or(serde_json::Value::Null);
- apply_session_identity(&mut req);
let timer = http_tool_observation_timer(&req, |name| sdk.is_known_tool(name));
let response = handle_request(req, id, sdk.as_ref()).await;
if let Some(timer) = timer {
@@ -194,7 +212,7 @@ fn serialize(resp: &Response) -> String {
/// recording key) — the HTTP-side equivalent of
/// `serve.rs::apply_session_identity`. Runtime-private idle-TTL activity is
/// refreshed later at the authorized registry boundary.
-fn apply_session_identity(req: &mut Request) {
+fn apply_session_identity(req: &mut Request, transport_session: &str) {
let Some(params) = req.params.as_mut() else {
return;
};
@@ -206,10 +224,15 @@ fn apply_session_identity(req: &mut Request) {
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_owned());
- if let Some(sess) = session {
- args.entry("_session_id")
- .or_insert_with(|| serde_json::Value::String(sess.clone()));
- }
+ let effective = session.unwrap_or_else(|| transport_session.to_owned());
+ args.insert(
+ "_session_id".to_owned(),
+ serde_json::Value::String(effective),
+ );
+ args.insert(
+ "_transport_session_id".to_owned(),
+ serde_json::Value::String(transport_session.to_owned()),
+ );
}
/// One parsed HTTP/1.1 request.
@@ -418,7 +441,7 @@ mod tests {
"params": { "name": "click", "arguments": { "pid": 1, "session": "alpha" } }
}))
.unwrap();
- apply_session_identity(&mut req);
+ apply_session_identity(&mut req, "http-test");
let args = req.params.unwrap();
let args = args.get("arguments").unwrap();
assert_eq!(args.get("_session_id").unwrap(), "alpha");
@@ -426,15 +449,16 @@ mod tests {
}
#[test]
- fn apply_session_identity_noop_without_session() {
+ fn apply_session_identity_uses_transport_implicit_without_session() {
let mut req: Request = serde_json::from_value(json!({
"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": { "name": "list_apps", "arguments": {} }
}))
.unwrap();
- apply_session_identity(&mut req);
+ apply_session_identity(&mut req, "http-test");
let args = req.params.unwrap();
- assert!(args.get("arguments").unwrap().get("_session_id").is_none());
+ assert_eq!(args["arguments"]["_session_id"], "http-test");
+ assert_eq!(args["arguments"]["_transport_session_id"], "http-test");
}
#[test]
@@ -503,6 +527,7 @@ mod tests {
let response = dispatch(
br#"{"jsonrpc":"2.0","id":7,"method":"tools/list","params":{}}"#,
&sdk,
+ "http-test",
)
.await
.expect("JSON-RPC response");
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 da0f4fd25d..a7405f059d 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
@@ -239,6 +239,11 @@ async fn handle_request(
.await
.map_err(|error| error.to_string())
.and_then(|json| serde_json::from_str(&json).map_err(|error| error.to_string())),
+ "sessions_list" => driver
+ .list_host_sessions_json()
+ .await
+ .map_err(|error| error.to_string())
+ .and_then(|json| serde_json::from_str(&json).map_err(|error| error.to_string())),
"call" => {
let name = request.name.as_deref().unwrap_or("");
let arguments = request
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
index f47ecfd15d..001547e28c 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
@@ -48,7 +48,20 @@ pub async fn run_direct(driver: Arc<cua_driver_sdk::CuaDriver>) -> anyhow::Resul
let mut writer = tokio::io::BufWriter::new(stdout);
let mut line = String::new();
let mut session_observed = false;
- let mut public_sessions = std::collections::HashSet::new();
+ let transport_session = format!("mcp-{}", uuid::Uuid::new_v4());
+ struct DirectTransportCleanup {
+ sdk: Arc<crate::sdk_adapter::SdkAdapter>,
+ transport_session: String,
+ }
+ impl Drop for DirectTransportCleanup {
+ fn drop(&mut self) {
+ self.sdk.end_transport_sessions(&self.transport_session);
+ }
+ }
+ let _cleanup = DirectTransportCleanup {
+ sdk: sdk.clone(),
+ transport_session: transport_session.clone(),
+ };
loop {
line.clear();
@@ -65,32 +78,19 @@ pub async fn run_direct(driver: Arc<cua_driver_sdk::CuaDriver>) -> anyhow::Resul
Response::parse_error()
}
Ok(request) if request.is_notification() => continue,
- Ok(request) => {
+ Ok(mut request) => {
+ apply_direct_session_identity(&mut request, &transport_session);
let initialize_metadata = (!session_observed)
.then(|| request.initialize_metadata())
.flatten();
- let session_context = request
- .tool_call()
- .ok()
- .and_then(|call| {
- call.args
- .get("session")
- .and_then(serde_json::Value::as_str)
- .filter(|session| !session.is_empty())
- .map(str::to_owned)
- })
- .map(|session| {
- public_sessions.insert(session);
- request.tool_call().ok().and_then(|call| {
- sdk.begin_tool_call(
- &call.name,
- &call.args,
- cua_driver_core::session::SessionTransport::McpStdio,
- cua_driver_core::session::SessionClientKind::Mcp,
- )
- })
- })
- .flatten();
+ let session_context = request.tool_call().ok().and_then(|call| {
+ sdk.begin_tool_call(
+ &call.name,
+ &call.args,
+ cua_driver_core::session::SessionTransport::McpStdio,
+ cua_driver_core::session::SessionClientKind::Mcp,
+ )
+ });
let timer = tool_observation_timer(
&request,
|name| sdk.is_known_tool(name),
@@ -122,12 +122,31 @@ pub async fn run_direct(driver: Arc<cua_driver_sdk::CuaDriver>) -> anyhow::Resul
writer.flush().await?;
}
- for session in public_sessions {
- let _ = sdk.end_session(&session).await;
- }
sdk.shutdown().await.map_err(anyhow::Error::msg)
}
+fn apply_direct_session_identity(request: &mut Request, transport_session: &str) {
+ let Some(arguments) = request
+ .params
+ .as_mut()
+ .and_then(|params| params.get_mut("arguments"))
+ .and_then(serde_json::Value::as_object_mut)
+ else {
+ return;
+ };
+ let effective = arguments
+ .get("session")
+ .and_then(serde_json::Value::as_str)
+ .filter(|session| !session.is_empty())
+ .unwrap_or(transport_session)
+ .to_owned();
+ arguments.insert("_session_id".into(), serde_json::Value::String(effective));
+ arguments.insert(
+ "_transport_session_id".into(),
+ serde_json::Value::String(transport_session.to_owned()),
+ );
+}
+
/// Run the MCP stdio proxy. Reads JSON-RPC lines from stdin, forwards
/// the body of each `tools/list` / `tools/call` to the daemon at
/// `socket_path`, and writes the daemon's response back as a proper
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs b/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs
index 9cf90faab9..f835bd482c 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
@@ -150,10 +150,21 @@ impl SdkAdapter {
.and_then(Value::as_str)
.filter(|session| !session.is_empty() && *session != "default")
.map(str::to_owned);
+ // The socket adapter's compatibility tombstone is keyed by the value
+ // its early guard sees. Explicit sessions use their public label;
+ // unnamed sessions use the transport-minted lifecycle id. Tracking
+ // both shapes lets an explicit start_session revive either episode.
+ let mirror_session = public_session.clone().or_else(|| {
+ arguments
+ .get("_session_id")
+ .and_then(Value::as_str)
+ .filter(|session| !session.is_empty() && *session != "default")
+ .map(str::to_owned)
+ });
let ending_session = (name == "end_session")
- .then_some(public_session.as_deref())
+ .then_some(mirror_session.as_deref())
.flatten();
- if let Some(session) = &public_session {
+ if let Some(session) = &mirror_session {
self.public_sessions
.lock()
.unwrap()
@@ -200,7 +211,7 @@ impl SdkAdapter {
.unwrap()
.rollback_ended(session, marker, previous);
}
- } else if let Some(session) = public_session.as_deref() {
+ } else if let Some(session) = mirror_session.as_deref() {
let capture_scope = value
.pointer("/structuredContent/capture_scope")
.cloned()
@@ -279,12 +290,73 @@ impl SdkAdapter {
.map(|_| ())
}
- pub fn create_trusted_session(
+ pub fn end_transport_sessions(&self, transport_session: &str) -> usize {
+ let owner = format!("{}{}", self.runtime_prefix, transport_session);
+ cua_driver_core::session::end_sessions_for_owner(
+ &owner,
+ cua_driver_core::session::SessionEndReason::ProcessExit,
+ )
+ }
+
+ pub fn operator_sessions_json(&self) -> Value {
+ let sessions = cua_driver_core::session::list_session_snapshots_with_prefix(
+ &self.runtime_prefix,
+ cua_driver_core::session::DEFAULT_SESSION_IDLE_TTL,
+ )
+ .into_iter()
+ .map(|session| {
+ let owner_short_id = session
+ .owner_transport
+ .chars()
+ .filter(|ch| ch.is_ascii_alphanumeric())
+ .rev()
+ .take(8)
+ .collect::<String>()
+ .chars()
+ .rev()
+ .collect::<String>();
+ let transport = match session.transport {
+ cua_driver_core::session::SessionTransport::Cli => "cli",
+ cua_driver_core::session::SessionTransport::Daemon => "daemon",
+ cua_driver_core::session::SessionTransport::McpStdio => "mcp_stdio",
+ cua_driver_core::session::SessionTransport::McpHttp => "mcp_http",
+ };
+ let client_kind = match session.client_kind {
+ cua_driver_core::session::SessionClientKind::Cli => "cli",
+ cua_driver_core::session::SessionClientKind::Direct => "direct",
+ cua_driver_core::session::SessionClientKind::Mcp => "mcp",
+ cua_driver_core::session::SessionClientKind::PythonSdk => "python_sdk",
+ cua_driver_core::session::SessionClientKind::TypescriptSdk => "typescript_sdk",
+ };
+ json!({
+ "session": session.public_label.as_deref().and_then(cursor_overlay::sanitize_session_label),
+ "implicit": session.implicit,
+ "state": if session.ending { "ending" } else { "active" },
+ "client_kind": client_kind,
+ "transport": transport,
+ "owner_short_id": owner_short_id,
+ "cursor_visible": cua_driver_core::session::cursor_visible(&session.runtime_id),
+ "recording_active": cua_driver_core::session::recording_active(&session.runtime_id),
+ "started_seconds_ago": session.started_for.as_secs(),
+ "idle_seconds": session.idle.as_secs(),
+ "expires_in_seconds": session.expires_in.as_secs(),
+ })
+ })
+ .collect::<Vec<_>>();
+ let count = sessions.len();
+ json!({
+ "sessions": sessions,
+ "count": count,
+ })
+ }
+
+ pub fn create_trusted_session_for_transport(
&self,
options: TrustedSessionOptions,
+ transport_session: &str,
) -> Result<Arc<CuaDriverSession>, String> {
self.driver
- .create_trusted_session(options)
+ .create_trusted_session_for_transport(options, transport_session)
.map_err(|error| error.to_string())
}
@@ -442,6 +514,45 @@ mod tests {
sdk.shutdown().await.expect("shutdown");
}
+ #[tokio::test]
+ async fn public_observation_mirror_revives_an_implicit_transport_session() {
+ let _runtime_guard = crate::test_runtime_lock().lock().await;
+ let sdk = SdkAdapter::load(host_driver()).await.expect("SDK adapter");
+ let transport_session = "adapter-implicit-transport";
+ let implicit_args = || {
+ json!({
+ "_session_id": transport_session,
+ "_transport_session_id": transport_session,
+ })
+ };
+
+ let started = sdk
+ .invoke_raw("start_session", implicit_args())
+ .await
+ .expect("start implicit session");
+ assert_ne!(started["isError"], true);
+
+ let ended = sdk
+ .invoke_raw("end_session", implicit_args())
+ .await
+ .expect("end implicit session");
+ assert_ne!(ended["isError"], true);
+ assert!(sdk.is_session_ended(transport_session));
+
+ let revived = sdk
+ .invoke_raw("start_session", implicit_args())
+ .await
+ .expect("revive implicit session");
+ assert_ne!(revived["isError"], true);
+ assert_eq!(revived["structuredContent"]["revived"], true);
+ assert!(
+ !sdk.is_session_ended(transport_session),
+ "successful implicit revival must clear the adapter's early tombstone"
+ );
+
+ sdk.shutdown().await.expect("shutdown");
+ }
+
#[tokio::test]
async fn runtime_owned_end_hook_updates_only_its_adapter() {
let _runtime_guard = crate::test_runtime_lock().lock().await;
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 ebbe719480..07073e02b3 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
@@ -21,7 +21,7 @@
//! Source-installed local builds use the corresponding `cua-driver-local`
//! namespace on every platform.
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use std::sync::{Mutex, OnceLock};
pub use cua_driver_core::daemon::{
@@ -31,6 +31,111 @@ pub use cua_driver_core::daemon::{
static ACTIVE_PROXY_SESSIONS: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
+#[derive(Clone, Debug)]
+struct TrustedResumeRecord {
+ options: cua_driver_sdk::TrustedSessionOptions,
+ transport_session: String,
+ expires_at: std::time::Instant,
+}
+
+struct TrustedConnectionSession {
+ session: std::sync::Arc<cua_driver_sdk::CuaDriverSession>,
+ options: cua_driver_sdk::TrustedSessionOptions,
+ transport_session: String,
+ resume_credential: String,
+}
+
+type TrustedResumeRegistry =
+ std::sync::Arc<tokio::sync::Mutex<HashMap<String, TrustedResumeRecord>>>;
+
+fn new_resume_credential() -> String {
+ format!("resume-{}", uuid::Uuid::new_v4())
+}
+
+fn resume_expiry(options: &cua_driver_sdk::TrustedSessionOptions) -> std::time::Instant {
+ std::time::Instant::now() + std::time::Duration::from_secs(options.idle_ttl_seconds.max(1))
+}
+
+fn bind_trusted_connection(
+ sdk: &crate::sdk_adapter::SdkAdapter,
+ options: cua_driver_sdk::TrustedSessionOptions,
+ transport_session: String,
+) -> Result<TrustedConnectionSession, String> {
+ let session = sdk.create_trusted_session_for_transport(options.clone(), &transport_session)?;
+ Ok(TrustedConnectionSession {
+ session,
+ options,
+ transport_session,
+ resume_credential: new_resume_credential(),
+ })
+}
+
+async fn resume_trusted_connection(
+ sdk: &crate::sdk_adapter::SdkAdapter,
+ registry: &TrustedResumeRegistry,
+ credential: &str,
+) -> Result<TrustedConnectionSession, String> {
+ let record = take_trusted_resume_record(registry, credential).await?;
+ bind_trusted_connection(sdk, record.options, record.transport_session)
+}
+
+async fn take_trusted_resume_record(
+ registry: &TrustedResumeRegistry,
+ credential: &str,
+) -> Result<TrustedResumeRecord, String> {
+ // Remove before validation so every presented credential is single use,
+ // including expired or otherwise invalid attempts.
+ let now = std::time::Instant::now();
+ let record = {
+ let mut records = registry.lock().await;
+ let record = records.remove(credential);
+ records.retain(|_, candidate| candidate.expires_at > now);
+ record
+ }
+ .ok_or_else(|| "trusted session resume credential is unavailable or already used".to_owned())?;
+ if now >= record.expires_at {
+ return Err("trusted session resume credential expired".to_owned());
+ }
+ Ok(record)
+}
+
+async fn detach_trusted_connection(
+ registry: &TrustedResumeRegistry,
+ connection: TrustedConnectionSession,
+) {
+ connection.session.close();
+ let now = std::time::Instant::now();
+ let mut records = registry.lock().await;
+ records.retain(|_, candidate| candidate.expires_at > now);
+ records.insert(
+ connection.resume_credential,
+ TrustedResumeRecord {
+ expires_at: resume_expiry(&connection.options),
+ options: connection.options,
+ transport_session: connection.transport_session,
+ },
+ );
+}
+
+async fn end_trusted_connection(connection: &TrustedConnectionSession) -> Result<(), String> {
+ let result = connection
+ .session
+ .call_tool(
+ "end_session".to_owned(),
+ serde_json::json!({"session": connection.options.public_session}).to_string(),
+ )
+ .await
+ .map_err(|error| error.to_string())?;
+ if result.is_error {
+ return Err(if result.text.is_empty() {
+ "trusted session cleanup did not complete".to_owned()
+ } else {
+ result.text
+ });
+ }
+ Ok(())
+}
+
fn active_proxy_sessions() -> &'static Mutex<HashSet<String>> {
ACTIVE_PROXY_SESSIONS.get_or_init(|| Mutex::new(HashSet::new()))
}
@@ -60,15 +165,11 @@ fn inject_browser_approvals(tool_name: &str, args: &mut serde_json::Value, sessi
/// Resolve + apply the session identity for a tool call at the daemon boundary.
///
-/// A session is a **caller-declared** identity (the public `session` arg), not a
-/// property of the MCP connection. We mirror an explicit `session` into the
-/// reserved `_session_id` key that every session-aware tool already reads
-/// (cursor key, per-session config override, recording owner). When no `session`
-/// was declared we fall back to the per-connection minted id for `_session_id`
-/// ONLY — that preserves connection-EOF cleanup of recording / config as before.
-/// The cursor is deliberately NOT driven by that fallback: `resolve_cursor_key`
-/// reads the explicit `session`/`cursor_id` arg only, so a cursor appears
-/// exactly when a run declares its session (explicit-required).
+/// Resolve optional public naming and the trusted transport's default lifecycle
+/// identity independently. An explicit `session` is mirrored into the reserved
+/// `_session_id` key; otherwise the per-connection lease id becomes the implicit
+/// lifecycle key. Cursor, recording, configuration, and cleanup all use that
+/// resolved identity, so ordinary callers do not need a setup call.
///
/// The registry refreshes the runtime-private idle-TTL key after authorization;
/// this transport helper only returns the effective `_session_id` for the
@@ -533,6 +634,8 @@ pub async fn run_serve(
// Shutdown channel.
let (shutdown_tx, mut shutdown_rx) = tokio::sync::oneshot::channel::<()>();
let shutdown_tx = std::sync::Arc::new(tokio::sync::Mutex::new(Some(shutdown_tx)));
+ let trusted_resume_registry: TrustedResumeRegistry =
+ std::sync::Arc::new(tokio::sync::Mutex::new(HashMap::new()));
let parent_liveness = async {
if cua_driver_core::parent_liveness_stdin_enabled() {
wait_for_parent_stdin_eof().await;
@@ -560,6 +663,7 @@ pub async fn run_serve(
authenticate_embedded_host_connection(&stream).is_ok();
let reg = sdk.clone();
let shutdown_tx2 = shutdown_tx.clone();
+ let trusted_resume_registry = trusted_resume_registry.clone();
tokio::spawn(async move {
let (reader, mut writer) = stream.into_split();
@@ -572,9 +676,7 @@ pub async fn run_serve(
// connection EOFs (graceful proxy exit OR kill -9, both
// kernel-guaranteed), the post-loop block reaps the session.
let mut control_session_id: Option<String> = None;
- let mut trusted_session: Option<
- std::sync::Arc<cua_driver_sdk::CuaDriverSession>,
- > = None;
+ let mut trusted_session: Option<TrustedConnectionSession> = None;
while let Ok(Some(line)) = lines.next_line().await {
let req: DaemonRequest = match serde_json::from_str(&line) {
@@ -707,12 +809,21 @@ pub async fn run_serve(
serde_json::from_value(value)
.map_err(|error| format!("invalid trusted session options: {error}"))
});
- match options.and_then(|options| reg.create_trusted_session(options)) {
- Ok(session) => {
- trusted_session = Some(session);
+ match options.and_then(|options| {
+ bind_trusted_connection(
+ &reg,
+ options,
+ format!("trusted-{}", uuid::Uuid::new_v4()),
+ )
+ }) {
+ Ok(connection) => {
+ let resume_credential =
+ connection.resume_credential.clone();
+ trusted_session = Some(connection);
DaemonResponse::ok(serde_json::json!({
"bound": true,
"connection_bound": true,
+ "resume_credential": resume_credential,
}))
}
Err(error) => DaemonResponse::err(error, 77),
@@ -722,14 +833,58 @@ pub async fn run_serve(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
).await;
}
+ "trusted_session_resume" => {
+ let resp = if !trusted_host_connection {
+ DaemonResponse::err(
+ "trusted service sessions require the original authenticated embedded host connection",
+ 77,
+ )
+ } else if trusted_session.is_some() {
+ DaemonResponse::err(
+ "this accepted connection already owns a trusted session",
+ 65,
+ )
+ } else {
+ let credential = req.args
+ .as_ref()
+ .and_then(|value| value.get("resume_credential"))
+ .and_then(serde_json::Value::as_str)
+ .filter(|value| !value.is_empty());
+ match credential {
+ Some(credential) => match resume_trusted_connection(
+ &reg,
+ &trusted_resume_registry,
+ credential,
+ ).await {
+ Ok(connection) => {
+ let rotated = connection.resume_credential.clone();
+ trusted_session = Some(connection);
+ DaemonResponse::ok(serde_json::json!({
+ "bound": true,
+ "connection_bound": true,
+ "resume_credential": rotated,
+ }))
+ }
+ Err(error) => DaemonResponse::err(error, 77),
+ },
+ None => DaemonResponse::err(
+ "trusted_session_resume omitted resume credential",
+ 65,
+ ),
+ }
+ };
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ }
"trusted_session_call" => {
let resp = match trusted_session.as_ref() {
- Some(session) => {
+ Some(connection) => {
let name = req.name.unwrap_or_default();
let arguments = req.args.unwrap_or_else(|| {
serde_json::Value::Object(serde_json::Map::new())
});
- match session.call_tool(name, arguments.to_string()).await {
+ match connection.session.call_tool(name, arguments.to_string()).await {
Ok(result) => match serde_json::from_str(&result.raw_json) {
Ok(value) => DaemonResponse::ok(value),
Err(error) => DaemonResponse::err(
@@ -750,12 +905,24 @@ pub async fn run_serve(
).await;
}
"trusted_session_end" => {
- if let Some(session) = trusted_session.take() {
- session.close();
- }
- let resp = DaemonResponse::ok(
- serde_json::json!({"closed": true})
- );
+ let resp = match trusted_session.as_ref() {
+ Some(connection) => match end_trusted_connection(connection).await {
+ Ok(()) => {
+ if let Some(connection) = trusted_session.take() {
+ connection.session.close();
+ }
+ DaemonResponse::ok(serde_json::json!({"closed": true}))
+ }
+ Err(error) => DaemonResponse::err(error, 77),
+ },
+ None => DaemonResponse::ok(serde_json::json!({"closed": true})),
+ };
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ }
+ "sessions_list" => {
+ let resp = DaemonResponse::ok(reg.operator_sessions_json());
let _ = writer.write_all(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
).await;
@@ -791,8 +958,10 @@ pub async fn run_serve(
// proxies never send it — the control-connection
// EOF is the single teardown path. Always ACK ok.
if let Some(sid) = req.session_id.as_deref() {
- if let Err(error) = reg.end_session(sid).await {
- tracing::warn!("legacy session_end failed: {error}");
+ if reg.end_transport_sessions(sid) == 0 {
+ if let Err(error) = reg.end_session(sid).await {
+ tracing::warn!("legacy session_end failed: {error}");
+ }
}
}
let resp = DaemonResponse::ok(
@@ -824,12 +993,10 @@ pub async fn run_serve(
// benign.
if let Some(sid) = control_session_id {
active_proxy_sessions().lock().unwrap().remove(&sid);
- if let Err(error) = reg.end_session(&sid).await {
- tracing::warn!("control-session cleanup failed: {error}");
- }
+ reg.end_transport_sessions(&sid);
}
- if let Some(session) = trusted_session {
- session.close();
+ if let Some(connection) = trusted_session {
+ detach_trusted_connection(&trusted_resume_registry, connection).await;
}
});
}
@@ -1147,6 +1314,8 @@ pub async fn run_serve(
let (shutdown_tx, mut shutdown_rx) = tokio::sync::oneshot::channel::<()>();
let shutdown_tx = std::sync::Arc::new(tokio::sync::Mutex::new(Some(shutdown_tx)));
+ let trusted_resume_registry: TrustedResumeRegistry =
+ std::sync::Arc::new(tokio::sync::Mutex::new(HashMap::new()));
let parent_liveness = async {
if cua_driver_core::parent_liveness_stdin_enabled() {
wait_for_parent_stdin_eof().await;
@@ -1211,6 +1380,7 @@ pub async fn run_serve(
let reg = sdk.clone();
let shutdown_tx2 = shutdown_tx.clone();
+ let trusted_resume_registry = trusted_resume_registry.clone();
tokio::spawn(async move {
let (reader, mut writer) = tokio::io::split(server);
@@ -1222,9 +1392,7 @@ pub async fn run_serve(
// ERROR_BROKEN_PIPE on the next read, ending the while-let
// loop equally reliably.
let mut control_session_id: Option<String> = None;
- let mut trusted_session: Option<
- std::sync::Arc<cua_driver_sdk::CuaDriverSession>,
- > = None;
+ let mut trusted_session: Option<TrustedConnectionSession> = None;
while let Ok(Some(line)) = lines.next_line().await {
let req: DaemonRequest = match serde_json::from_str(&line) {
@@ -1338,12 +1506,20 @@ pub async fn run_serve(
serde_json::from_value(value)
.map_err(|error| format!("invalid trusted session options: {error}"))
});
- match options.and_then(|options| reg.create_trusted_session(options)) {
- Ok(session) => {
- trusted_session = Some(session);
+ match options.and_then(|options| {
+ bind_trusted_connection(
+ &reg,
+ options,
+ format!("trusted-{}", uuid::Uuid::new_v4()),
+ )
+ }) {
+ Ok(connection) => {
+ let resume_credential = connection.resume_credential.clone();
+ trusted_session = Some(connection);
DaemonResponse::ok(serde_json::json!({
"bound": true,
"connection_bound": true,
+ "resume_credential": resume_credential,
}))
}
Err(error) => DaemonResponse::err(error, 77),
@@ -1353,14 +1529,58 @@ pub async fn run_serve(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
).await;
}
+ "trusted_session_resume" => {
+ let resp = if !trusted_host_connection {
+ DaemonResponse::err(
+ "trusted service sessions require the original authenticated embedded host connection",
+ 77,
+ )
+ } else if trusted_session.is_some() {
+ DaemonResponse::err(
+ "this accepted connection already owns a trusted session",
+ 65,
+ )
+ } else {
+ let credential = req.args
+ .as_ref()
+ .and_then(|value| value.get("resume_credential"))
+ .and_then(serde_json::Value::as_str)
+ .filter(|value| !value.is_empty());
+ match credential {
+ Some(credential) => match resume_trusted_connection(
+ &reg,
+ &trusted_resume_registry,
+ credential,
+ ).await {
+ Ok(connection) => {
+ let rotated = connection.resume_credential.clone();
+ trusted_session = Some(connection);
+ DaemonResponse::ok(serde_json::json!({
+ "bound": true,
+ "connection_bound": true,
+ "resume_credential": rotated,
+ }))
+ }
+ Err(error) => DaemonResponse::err(error, 77),
+ },
+ None => DaemonResponse::err(
+ "trusted_session_resume omitted resume credential",
+ 65,
+ ),
+ }
+ };
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ }
"trusted_session_call" => {
let resp = match trusted_session.as_ref() {
- Some(session) => {
+ Some(connection) => {
let name = req.name.unwrap_or_default();
let arguments = req.args.unwrap_or_else(|| {
serde_json::Value::Object(serde_json::Map::new())
});
- match session.call_tool(name, arguments.to_string()).await {
+ match connection.session.call_tool(name, arguments.to_string()).await {
Ok(result) => match serde_json::from_str(&result.raw_json) {
Ok(value) => DaemonResponse::ok(value),
Err(error) => DaemonResponse::err(
@@ -1381,12 +1601,24 @@ pub async fn run_serve(
).await;
}
"trusted_session_end" => {
- if let Some(session) = trusted_session.take() {
- session.close();
- }
- let resp = DaemonResponse::ok(
- serde_json::json!({"closed": true})
- );
+ let resp = match trusted_session.as_ref() {
+ Some(connection) => match end_trusted_connection(connection).await {
+ Ok(()) => {
+ if let Some(connection) = trusted_session.take() {
+ connection.session.close();
+ }
+ DaemonResponse::ok(serde_json::json!({"closed": true}))
+ }
+ Err(error) => DaemonResponse::err(error, 77),
+ },
+ None => DaemonResponse::ok(serde_json::json!({"closed": true})),
+ };
+ let _ = writer.write_all(
+ (serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
+ ).await;
+ }
+ "sessions_list" => {
+ let resp = DaemonResponse::ok(reg.operator_sessions_json());
let _ = writer.write_all(
(serde_json::to_string(&resp).unwrap() + "\n").as_bytes()
).await;
@@ -1415,8 +1647,10 @@ pub async fn run_serve(
// connection; control_session_id stays None so no
// EOF double-fire. fire_session_end is idempotent.
if let Some(sid) = req.session_id.as_deref() {
- if let Err(error) = reg.end_session(sid).await {
- tracing::warn!("legacy session_end failed: {error}");
+ if reg.end_transport_sessions(sid) == 0 {
+ if let Err(error) = reg.end_session(sid).await {
+ tracing::warn!("legacy session_end failed: {error}");
+ }
}
}
let resp = DaemonResponse::ok(
@@ -1442,12 +1676,10 @@ pub async fn run_serve(
// control_session_id None.
if let Some(sid) = control_session_id {
active_proxy_sessions().lock().unwrap().remove(&sid);
- if let Err(error) = reg.end_session(&sid).await {
- tracing::warn!("control-session cleanup failed: {error}");
- }
+ reg.end_transport_sessions(&sid);
}
- if let Some(session) = trusted_session {
- session.close();
+ if let Some(connection) = trusted_session {
+ detach_trusted_connection(&trusted_resume_registry, connection).await;
}
});
}
@@ -1701,6 +1933,65 @@ pub fn run_status_cmd(socket_path: &str, pid_file_path: &str) {
}
}
+/// `cua-driver sessions list` implementation. This is an operator surface,
+/// not an MCP tool: the daemon returns only content-free lifecycle metadata
+/// and redacts transport ownership to a short correlation id.
+pub fn run_sessions_list_cmd(socket_path: &str, json: bool) {
+ let request = DaemonRequest {
+ method: "sessions_list".to_owned(),
+ name: None,
+ args: None,
+ session_id: None,
+ observation_origin: Some(ToolObservationOrigin::Direct),
+ client_kind: None,
+ };
+ match send_request(socket_path, &request) {
+ Ok(response) if response.ok => {
+ let result = response
+ .result
+ .unwrap_or_else(|| serde_json::json!({"sessions": [], "count": 0}));
+ if json {
+ println!("{}", serde_json::to_string(&result).unwrap());
+ return;
+ }
+ let sessions = result
+ .get("sessions")
+ .and_then(serde_json::Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+ if sessions.is_empty() {
+ println!("No live sessions.");
+ return;
+ }
+ println!("STATE\tTRANSPORT\tCLIENT\tSESSION\tOWNER\tIDLE");
+ for session in sessions {
+ println!(
+ "{}\t{}\t{}\t{}\t{}\t{}s",
+ session["state"].as_str().unwrap_or("unknown"),
+ session["transport"].as_str().unwrap_or("unknown"),
+ session["client_kind"].as_str().unwrap_or("unknown"),
+ session["session"].as_str().unwrap_or("(implicit)"),
+ session["owner_short_id"].as_str().unwrap_or("unknown"),
+ session["idle_seconds"].as_u64().unwrap_or(0),
+ );
+ }
+ }
+ Ok(response) => {
+ eprintln!(
+ "{}",
+ response
+ .error
+ .unwrap_or_else(|| "session listing failed".to_owned())
+ );
+ std::process::exit(response.exit_code.unwrap_or(1));
+ }
+ Err(error) => {
+ eprintln!("session listing failed: {error}");
+ std::process::exit(1);
+ }
+ }
+}
+
/// Revoke one authorization/session scope or every live scope. This local
/// control is intentionally deny-only and never accepts a grant token.
pub fn run_revoke_cmd(socket_path: &str, session: Option<&str>, all: bool) {
@@ -2114,6 +2405,58 @@ mod telemetry_routing_tests {
}
}
+#[cfg(test)]
+mod trusted_resume_tests {
+ use super::{take_trusted_resume_record, TrustedResumeRecord, TrustedResumeRegistry};
+ use cua_driver_sdk::{SessionPermissionMode, TrustedSessionOptions};
+ use std::collections::HashMap;
+ use std::sync::Arc;
+ use std::time::{Duration, Instant};
+ use tokio::sync::Mutex;
+
+ fn record(expires_at: Instant, transport_session: &str) -> TrustedResumeRecord {
+ TrustedResumeRecord {
+ options: TrustedSessionOptions {
+ public_session: "public-test".into(),
+ mode: SessionPermissionMode::Standard,
+ ttl_seconds: 60,
+ idle_ttl_seconds: 30,
+ bounded_manifest_path: None,
+ },
+ transport_session: transport_session.into(),
+ expires_at,
+ }
+ }
+
+ #[tokio::test]
+ async fn resume_credentials_are_single_use_expiring_and_prune_orphans() {
+ let now = Instant::now();
+ let registry: TrustedResumeRegistry = Arc::new(Mutex::new(HashMap::from([
+ ("expired-target".into(), record(now, "expired-target-lease")),
+ ("expired-orphan".into(), record(now, "expired-orphan-lease")),
+ (
+ "live".into(),
+ record(now + Duration::from_secs(60), "live-lease"),
+ ),
+ ])));
+
+ let error = take_trusted_resume_record(&registry, "expired-target")
+ .await
+ .expect_err("expired credential must fail closed");
+ assert!(error.contains("expired"));
+ assert!(!registry.lock().await.contains_key("expired-orphan"));
+
+ let live = take_trusted_resume_record(&registry, "live")
+ .await
+ .expect("live credential is consumed once");
+ assert_eq!(live.transport_session, "live-lease");
+ let replay = take_trusted_resume_record(&registry, "live")
+ .await
+ .expect_err("consumed credential must not replay");
+ assert!(replay.contains("unavailable or already used"));
+ }
+}
+
#[cfg(test)]
mod service_authorization_status_tests {
use super::service_authorization_status;
@@ -2164,9 +2507,9 @@ mod session_boundary_tests {
#[test]
fn no_session_falls_back_to_minted_for_session_id_only() {
- // The minted per-connection id drives `_session_id` (recording / config
- // lifecycle) but there is NO explicit `session`, so the cursor resolver
- // — which reads `session`/`cursor_id`, not `_session_id` — sees nothing.
+ // The minted per-connection id drives the complete implicit lifecycle,
+ // including cursor, recording, configuration, and cleanup, without
+ // manufacturing a caller-visible public `session` label.
let mut args = json!({ "x": 1 });
let eff = apply_session_identity(&mut args, &Some("mcp-123".to_owned()));
assert_eq!(args["_session_id"], "mcp-123");
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs b/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs
index 2d63685d20..16e17f50fd 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs
@@ -502,6 +502,8 @@ struct AgentSessionState {
used_cursor_tools: bool,
used_recording: bool,
used_config_write: bool,
+ used_window_modality: bool,
+ used_desktop_modality: bool,
}
impl AgentSessionState {
@@ -529,6 +531,8 @@ impl AgentSessionState {
used_cursor_tools: false,
used_recording: false,
used_config_write: false,
+ used_window_modality: false,
+ used_desktop_modality: false,
}
}
@@ -536,10 +540,19 @@ impl AgentSessionState {
&mut self,
transport: Transport,
computer_action: bool,
+ capture_modality: Option<cua_driver_core::session::CaptureModality>,
escalation_reason: Option<cua_driver_core::EscalationReason>,
outcome: &cua_driver_core::server::ToolCompletionObservation,
) {
self.transport_bits |= transport_bit(transport);
+ self.used_window_modality |= matches!(
+ capture_modality,
+ Some(cua_driver_core::session::CaptureModality::Window)
+ );
+ self.used_desktop_modality |= matches!(
+ capture_modality,
+ Some(cua_driver_core::session::CaptureModality::Desktop)
+ );
let tool_name = outcome.tool_name.as_str();
if tool_name == "escalate_session"
&& outcome.success
@@ -608,6 +621,7 @@ impl AgentSessionState {
let cursor = cursor.unwrap_or(cua_driver_core::session::CursorOutcomeObservation {
observed: false,
enabled: false,
+ visible: false,
theme: CursorThemeCategory::Unknown,
motion_customized: false,
active_cursor_count: 0,
@@ -649,6 +663,14 @@ impl AgentSessionState {
("used_cursor_tools", Value::Bool(self.used_cursor_tools)),
("used_recording", Value::Bool(self.used_recording)),
("used_config_write", Value::Bool(self.used_config_write)),
+ (
+ "used_window_modality",
+ Value::Bool(self.used_window_modality),
+ ),
+ (
+ "used_desktop_modality",
+ Value::Bool(self.used_desktop_modality),
+ ),
("cursor_outcome_observed", Value::Bool(cursor.observed)),
("cursor_overlay_enabled_at_end", Value::Bool(cursor.enabled)),
("cursor_theme", Value::String(cursor_theme.into())),
@@ -847,6 +869,7 @@ impl cua_driver_core::session::SessionObserver for TelemetryObserver {
session_id: &str,
transport: cua_driver_core::session::SessionTransport,
computer_action: bool,
+ capture_modality: Option<cua_driver_core::session::CaptureModality>,
escalation_reason: Option<cua_driver_core::EscalationReason>,
outcome: &cua_driver_core::server::ToolCompletionObservation,
) {
@@ -860,6 +883,7 @@ impl cua_driver_core::session::SessionObserver for TelemetryObserver {
state.observe(
session_transport(transport),
computer_action,
+ capture_modality,
escalation_reason,
outcome,
);
@@ -3282,6 +3306,7 @@ mod tests {
state.observe(
Transport::McpHttp,
true,
+ Some(cua_driver_core::session::CaptureModality::Window),
None,
&ToolCompletionObservation {
tool_name: "click".into(),
@@ -3298,6 +3323,7 @@ mod tests {
state.observe(
Transport::McpHttp,
false,
+ None,
Some(cua_driver_core::EscalationReason::NoWindowTarget),
&ToolCompletionObservation {
tool_name: "escalate_session".into(),
@@ -3314,6 +3340,7 @@ mod tests {
state.observe(
Transport::McpHttp,
false,
+ Some(cua_driver_core::session::CaptureModality::Desktop),
None,
&ToolCompletionObservation {
tool_name: "page".into(),
@@ -3332,6 +3359,7 @@ mod tests {
Some(cua_driver_core::session::CursorOutcomeObservation {
observed: true,
enabled: true,
+ visible: true,
theme: cua_driver_core::session::CursorThemeCategory::Custom,
motion_customized: true,
active_cursor_count: 3,
@@ -3351,6 +3379,8 @@ mod tests {
assert_eq!(properties["multi_cursor_bucket"], "3_5");
assert_eq!(properties["observed_multiple_transports"], true);
assert_eq!(properties["client_kind"], "python_sdk");
+ assert_eq!(properties["used_window_modality"], true);
+ assert_eq!(properties["used_desktop_modality"], true);
assert_eq!(properties["capture_scope"], "auto");
assert_eq!(properties["auto_escalated_to_desktop"], true);
assert_eq!(properties["escalation_reason"], "no_window_target");
@@ -3401,6 +3431,7 @@ mod tests {
auto.observe(
Transport::Daemon,
false,
+ None,
Some(cua_driver_core::EscalationReason::Other),
&failed,
);
@@ -3420,6 +3451,7 @@ mod tests {
desktop.observe(
Transport::Daemon,
false,
+ None,
Some(cua_driver_core::EscalationReason::Other),
&successful,
);
@@ -3461,7 +3493,7 @@ mod tests {
cua_driver_core::session::SessionClientKind::Mcp,
cua_driver_core::CaptureScope::Window,
);
- state.observe(Transport::McpStdio, true, None, &outcome);
+ state.observe(Transport::McpStdio, true, None, None, &outcome);
let session_properties =
state.ended_properties(cua_driver_core::session::SessionEndReason::Explicit, None);
assert_eq!(session_properties["computer_action_count_bucket"], "0");
@@ -3500,6 +3532,7 @@ mod tests {
Transport::McpStdio,
true,
None,
+ None,
&ToolCompletionObservation {
tool_name: tool_name.into(),
operation,
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
index e0b1509650..0e21737c1d 100644
--- 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
@@ -13,6 +13,9 @@ use image::RgbaImage;
const CELL_ID: &str = "desktop-agent-cursor-showcase-px";
const SESSION: &str = "Cursor showcase";
+// MoveTo offsets the cursor artwork by 16 points so its tip lands on the
+// requested coordinate. The session badge follows that artwork anchor.
+const MAX_CURSOR_ANCHOR_OFFSET: f64 = 16.0;
#[test]
#[ignore]
@@ -32,15 +35,11 @@ fn semantic_cursor_showcase_records_session_and_action_states() {
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"
- }),
- );
-
+ // Capture the empty desktop before declaring the explicit session.
+ // `start_session` may revive and materialize the session-owned overlay
+ // at the current pointer position, which can otherwise put the badge
+ // in both frames when a previous showcase left the pointer at this
+ // deterministic target.
let (baseline_png, width, height) = capture_desktop_png(&mut driver);
let baseline = image::load_from_memory(&baseline_png)
.expect("decode baseline desktop screenshot")
@@ -50,6 +49,14 @@ fn semantic_cursor_showcase_records_session_and_action_states() {
"showcase requires a normal desktop, got {width}x{height}"
);
+ call_ok(
+ &mut driver,
+ "start_session",
+ serde_json::json!({
+ "session": SESSION
+ }),
+ );
+
call_ok(
&mut driver,
"set_agent_cursor_enabled",
@@ -81,14 +88,13 @@ fn semantic_cursor_showcase_records_session_and_action_states() {
"y": center_y - 80.0
}),
);
+ // move_cursor waits for the configured glide, but X11/Wayland capture
+ // still needs a compositor round-trip before the overlay is guaranteed
+ // to appear in the driver-owned screenshot. The badge remains fully
+ // visible for two seconds, so this settle stays inside that window.
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_png = capture_cursor_oracle_png(&mut driver);
let cursor_frame = image::load_from_memory(&cursor_png)
.expect("decode cursor desktop screenshot")
.to_rgba8();
@@ -107,22 +113,12 @@ fn semantic_cursor_showcase_records_session_and_action_states() {
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",
+ "target": {"kind": "desktop", "display_id": "primary"},
"x": center_x,
"y": center_y,
"delivery_mode": "foreground"
@@ -135,7 +131,7 @@ fn semantic_cursor_showcase_records_session_and_action_states() {
"type_text",
serde_json::json!({
"session": SESSION,
- "scope": "desktop",
+ "target": {"kind": "desktop", "display_id": "primary"},
"text": "cua",
"delivery_mode": "foreground"
}),
@@ -147,7 +143,7 @@ fn semantic_cursor_showcase_records_session_and_action_states() {
"scroll",
serde_json::json!({
"session": SESSION,
- "scope": "desktop",
+ "target": {"kind": "desktop", "display_id": "primary"},
"x": center_x,
"y": center_y,
"direction": "down",
@@ -162,7 +158,7 @@ fn semantic_cursor_showcase_records_session_and_action_states() {
"drag",
serde_json::json!({
"session": SESSION,
- "scope": "desktop",
+ "target": {"kind": "desktop", "display_id": "primary"},
"from_x": center_x - 90.0,
"from_y": center_y + 80.0,
"to_x": center_x + 120.0,
@@ -215,8 +211,9 @@ fn assert_cursor_and_badge_pixels_changed(
let badge_half_width = (f64::from(BADGE_MAX_WIDTH) * 0.5 * scale_x).ceil() as i64;
let badge_cursor_exclusion = (34.0 * scale_x).ceil() as i64;
let badge_top = center_y + (f64::from(BADGE_CURSOR_GAP) * scale_y).floor() as i64;
- let badge_bottom =
- center_y + (f64::from(BADGE_CURSOR_GAP + BADGE_HEIGHT) * scale_y).ceil() as i64;
+ let badge_bottom = center_y
+ + ((f64::from(BADGE_CURSOR_GAP + BADGE_HEIGHT) + MAX_CURSOR_ANCHOR_OFFSET) * scale_y).ceil()
+ as i64;
// Ignore the center corridor where the pointer's lower edge or glow could
// overlap the pill. Requiring changed pixels in the badge's outer wings
// makes this an independent badge assertion.
@@ -303,6 +300,38 @@ fn capture_desktop_png(driver: &mut McpDriver) -> (Vec<u8>, f64, f64) {
(png, width, height)
}
+fn capture_cursor_oracle_png(driver: &mut McpDriver) -> Vec<u8> {
+ #[cfg(target_os = "linux")]
+ {
+ // A compositor-less X11 root read can omit the overlay client's own
+ // shaped window even while an independent display capture sees the
+ // complete cursor and badge. The action evidence recorder is the
+ // canonical external behavior oracle and has already captured the
+ // move_cursor after-frame before this call returns.
+ let path = driver
+ .recording_dir()
+ .expect("showcase recording directory")
+ .join("turn-00001/after.png");
+ for _ in 0..20 {
+ if let Ok(png) = std::fs::read(&path) {
+ if !png.is_empty() {
+ return png;
+ }
+ }
+ settle(50);
+ }
+ panic!(
+ "action evidence did not produce the cursor after-frame at {}",
+ path.display()
+ );
+ }
+
+ #[cfg(not(target_os = "linux"))]
+ {
+ capture_desktop_png(driver).0
+ }
+}
+
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());
@@ -339,6 +368,23 @@ mod pixel_oracle_tests {
);
}
+ #[test]
+ fn accepts_badge_at_shifted_cursor_artwork_anchor() {
+ let baseline = RgbaImage::new(WIDTH, HEIGHT);
+ let mut overlay = baseline.clone();
+ paint_changed_rect(&mut overlay, 196, 146, 200, 150);
+ paint_changed_rect(&mut overlay, 250, 204, 256, 210);
+
+ assert_cursor_and_badge_pixels_changed(
+ &baseline,
+ &overlay,
+ CURSOR_X,
+ CURSOR_Y,
+ f64::from(WIDTH),
+ f64::from(HEIGHT),
+ );
+ }
+
#[test]
#[should_panic(expected = "badge region changed 0 pixels")]
fn rejects_pointer_without_badge() {
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs
index 69e3d2be9c..9b5fc38de7 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs
@@ -9,7 +9,7 @@ use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
use cua_driver_contract::{CaptureScope, GetSessionStateInput, StartSessionInput};
-use cua_driver_sdk::{CuaDriver, EmbeddedCuaDriverHost, EmbeddedDriverHostState};
+use cua_driver_sdk::{CuaDriver, DriverError, EmbeddedCuaDriverHost, EmbeddedDriverHostState};
use cua_driver_testkit::{spawn_in_job, ChildReaper};
use serde_json::{json, Value};
@@ -140,7 +140,7 @@ async fn embedded_host_serves_sdk_and_mcp_with_one_contract() {
let sdk_session = sdk
.start_session(StartSessionInput {
- session: "embedded-sdk-window".into(),
+ session: Some("embedded-sdk-window".into()),
capture_scope: Some(CaptureScope::Window),
cursor_theme: None,
})
@@ -172,23 +172,47 @@ async fn embedded_host_serves_sdk_and_mcp_with_one_contract() {
"desktop"
);
- // Session policy belongs to the session, not the daemon or transport:
- // one SDK session can remain strict-window while an MCP session sharing
- // the same embedded host is strict-desktop.
+ // Session policy belongs to the session and ordinary lifecycle inspection
+ // is transport-scoped: the SDK and MCP connections can each inspect their
+ // own session without enumerating the other's label.
let sdk_state = sdk
.get_session_state(GetSessionStateInput {
- session: "embedded-sdk-window".into(),
+ session: Some("embedded-sdk-window".into()),
})
.await
.expect("read SDK session");
- let mcp_state = sdk
+ let foreign = sdk
.get_session_state(GetSessionStateInput {
- session: "embedded-mcp-desktop".into(),
+ session: Some("embedded-mcp-desktop".into()),
})
.await
- .expect("read MCP-created session through SDK");
+ .expect_err("SDK transport must not inspect an MCP-created session");
assert_eq!(sdk_state.capture_scope, CaptureScope::Window);
- assert_eq!(mcp_state.capture_scope, CaptureScope::Desktop);
+ assert!(matches!(
+ foreign,
+ DriverError::Tool { error_code, .. } if error_code == "session_not_started"
+ ));
+
+ writeln!(
+ stdin,
+ "{}",
+ json!({
+ "jsonrpc": "2.0",
+ "id": 4,
+ "method": "tools/call",
+ "params": {
+ "name": "get_session",
+ "arguments": {"session": "embedded-mcp-desktop"}
+ }
+ })
+ )
+ .unwrap();
+ stdin.flush().unwrap();
+ let mcp_state = read_json(&mut stdout);
+ assert_eq!(
+ mcp_state["result"]["structuredContent"]["session"],
+ "embedded-mcp-desktop"
+ );
drop(stdin);
let mut reaper = ChildReaper::new();
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs
index 3d850724c6..a2ee5c604b 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_schema_test.rs
@@ -157,9 +157,8 @@ fn tools_list_schema_shape() {
list_resp["result"]["capability_version"], "1",
"adding one capability token is additive and must not bump the vocabulary version"
);
- // Capture scope belongs to the session lifecycle on every platform. The
- // action-level `scope` selects a coordinate/transport form but cannot
- // override the session policy enforced by the registry.
+ // Session capture scope remains advertised only for compatibility. New
+ // clients choose one typed window or desktop target on each action.
let capture_scope = &properties("start_session")["capture_scope"];
for expected in ["auto", "window", "desktop"] {
assert!(
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_tools_call_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_tools_call_test.rs
index 3fe4c0cf32..df76760fa2 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_tools_call_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_tools_call_test.rs
@@ -702,14 +702,41 @@ fn type_text_chars_tool() {
return;
};
- // type_text_chars with delay_ms=5 — just verify the tool invocation is accepted.
+ // Resolve an exact on-screen window. PID-only targeting is deliberately
+ // refused when an app owns multiple eligible windows.
d.send(&serde_json::json!({
"jsonrpc":"2.0","id":3,"method":"tools/call",
+ "params":{"name":"list_windows","arguments":{"pid":pid,"on_screen_only":true}}
+ }));
+ let resp = d.recv();
+ let windows = resp["result"]["structuredContent"]["windows"].as_array();
+ let Some(window_id) = windows
+ .and_then(|windows| windows.first())
+ .and_then(|window| window["window_id"].as_u64())
+ else {
+ eprintln!("TextEdit has no on-screen windows — skipping type_text_chars test");
+ return;
+ };
+
+ // type_text_chars with delay_ms=5 — just verify the tool invocation is accepted.
+ d.send(&serde_json::json!({
+ "jsonrpc":"2.0","id":4,"method":"tools/call",
"params":{"name":"type_text_chars","arguments":{
- "pid": pid, "text": "hi", "delay_ms": 5
+ "pid": pid, "window_id": window_id, "text": "hi", "delay_ms": 5
}}
}));
let resp = d.recv();
+ if resp["result"]["isError"].as_bool().unwrap_or(false)
+ && matches!(
+ resp["result"]["structuredContent"]["code"].as_str(),
+ Some("off_space_or_ax_unresolved" | "window_target_not_found")
+ )
+ {
+ eprintln!(
+ "TextEdit has no safe AX-resolved input target in this desktop session — skipping type_text_chars test"
+ );
+ return;
+ }
assert!(
!resp["result"]["isError"].as_bool().unwrap_or(false),
"type_text_chars returned error: {resp:?}"
@@ -1034,14 +1061,14 @@ fn set_value_via_element_index() {
let element_count = resp["result"]["structuredContent"]["element_count"]
.as_u64()
.unwrap_or(0);
- let snapshot_id = resp["result"]["structuredContent"]["snapshot_id"]
- .as_str()
- .expect("get_window_state snapshot_id")
- .to_owned();
if element_count == 0 {
eprintln!("No AX elements — skipping set_value test");
return;
}
+ let snapshot_id = resp["result"]["structuredContent"]["snapshot_id"]
+ .as_str()
+ .expect("get_window_state snapshot_id")
+ .to_owned();
// set_value on element 0 — this is the document / text area in a new TextEdit document.
d.send(&serde_json::json!({
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/session_capture_scope_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/session_capture_scope_test.rs
index 86ba8146a5..21acfde0d9 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/session_capture_scope_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/session_capture_scope_test.rs
@@ -171,6 +171,6 @@ fn persistent_capture_scope_key_is_retired() {
assert_eq!(code(&response), Some("config_key_retired"));
assert_eq!(
response["result"]["structuredContent"]["replacement"],
- "start_session.capture_scope"
+ "action.target"
);
}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
index d1b62f1147..7100a9a496 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/standalone_browser_behavior_test.rs
@@ -3664,34 +3664,22 @@ fn run_browser_owned_permission_prompt(spec: &BrowserSpec) {
before.raw
);
assert_eq!(
- before.structured()["capture_coverage"]["recovery"]["escalate"],
+ before.structured()["capture_coverage"]["recovery"]["act_target"],
serde_json::json!({
- "tool": "escalate_session",
- "reason": "foreground_ineffective",
+ "kind": "desktop",
+ "display_id": "primary",
}),
"{}",
before.raw
);
+ assert!(
+ before.structured()["capture_coverage"]["recovery"]
+ .get("escalate")
+ .is_none(),
+ "{}",
+ before.raw
+ );
}
- let escalated = fixture.driver.call(
- "escalate_session",
- serde_json::json!({
- "session": window_session,
- "reason": "foreground_ineffective",
- "detail": "browser chrome may be outside window capture",
- }),
- );
- assert!(
- !escalated.is_error(),
- "desktop inspection escalation failed: {}",
- escalated.raw
- );
- assert_eq!(
- escalated.structured()["effective_scope"],
- "desktop",
- "{}",
- escalated.raw
- );
let desktop_before = fixture.driver.call(
"get_desktop_state",
serde_json::json!({
@@ -3828,7 +3816,7 @@ fn run_browser_owned_permission_prompt(spec: &BrowserSpec) {
"click",
serde_json::json!({
"session": window_session,
- "scope": "desktop",
+ "target": {"kind": "desktop", "display_id": "primary"},
"x": x,
"y": y,
}),
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 f5ab60eb1c..185c7f341b 100644
--- a/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cursor-overlay/src/lib.rs
@@ -314,14 +314,18 @@ pub struct KeyedOverlayCommand {
pub cmd: OverlayCommand,
}
-/// Message carried over the macOS overlay channel. Either a keyed render
-/// command or a lifecycle removal. A separate lifecycle enum (rather than an
-/// `OverlayCommand::Remove` variant) keeps `OverlayCommand` render-only and
-/// avoids forcing a no-op arm onto the Windows/Linux match.
+/// Message carried over a platform overlay channel. Either a keyed render
+/// command or an explicit session-lifecycle transition. A separate lifecycle
+/// enum (rather than `OverlayCommand` variants) keeps render commands
+/// render-only.
#[derive(Debug, Clone)]
pub enum OverlayMsg {
Cmd(KeyedOverlayCommand),
Remove(CursorKey),
+ /// Clear the render-side tombstone for an explicitly revived session.
+ /// This deliberately does not recreate a cursor; the next command does so
+ /// lazily after the successful `start_session` boundary.
+ Revive(CursorKey),
}
/// Commands sent from MCP tool handlers to the overlay's render thread.
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs
index 47d0a44aa4..f408864f1f 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs
@@ -2141,7 +2141,7 @@ pub fn send_key_xtest(key: &str, modifiers: &[&str]) -> Result<()> {
Ok(())
}
-/// Screen-absolute click via the XTest extension — the `capture_scope="desktop"`
+/// Screen-absolute click via the XTest extension — the desktop-target
/// foreground click. It warps the real pointer to `(x, y)` and injects a true
/// button press/release there, so the event lands on whatever window owns that
/// screen pixel (the Linux peer of the Windows `WindowFromPoint` + macOS
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 b9ae2365ed..710aa22e01 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/overlay.rs
@@ -200,6 +200,12 @@ fn apply_msg(map: &mut RenderMap, msg: OverlayMsg) -> Option<CursorKey> {
}
None
}
+ OverlayMsg::Revive(key) => {
+ if key != "default" {
+ map.ended.remove(&key);
+ }
+ None
+ }
OverlayMsg::Cmd(KeyedOverlayCommand { key, cmd }) => {
if map.ended.contains(&key) {
tracing::debug!(key = %key, cmd = ?cmd, "overlay: command dropped — key was ended");
@@ -383,6 +389,26 @@ pub fn is_enabled_for(key: &str) -> bool {
.unwrap_or(false)
}
+/// Truthful render acknowledgement for lifecycle inspection. This checks the
+/// exact session key and never inherits the seeded default cursor.
+pub fn is_visible_for_session(key: &str) -> bool {
+ RENDER
+ .lock()
+ .ok()
+ .and_then(|guard| {
+ guard
+ .as_ref()
+ .and_then(|map| map.cursors.get(key))
+ .map(|rs| {
+ rs.core.cfg.enabled
+ && rs.core.visible
+ && rs.core.idle_alpha >= 0.004
+ && rs.core.pos.0 >= -100.0
+ })
+ })
+ .unwrap_or(false)
+}
+
pub fn current_position() -> (f64, f64) {
current_position_for("default")
}
@@ -517,6 +543,23 @@ pub fn remove_cursor(key: CursorKey) {
}
}
+/// Clear the X11 render-side tombstone after a successful explicit session
+/// revival. Wayland has no keyed tombstone, so forwarding this lifecycle
+/// signal there is an accepted no-op.
+pub fn revive_cursor(key: CursorKey) {
+ if key.is_empty() {
+ return;
+ }
+ let msg = OverlayMsg::Revive(key);
+ if let Some(tx) = CMD_TX.get() {
+ let _ = tx.try_send(msg.clone());
+ }
+ #[cfg(target_os = "linux")]
+ if crate::wayland::is_wayland() && !crate::wayland::shell_helper::available() {
+ let _ = crate::wayland::overlay::forward(&msg);
+ }
+}
+
/// Spawn the overlay on a dedicated thread. Non-blocking.
pub fn run_on_thread() {
let rx = match CMD_RX_CELL.lock().unwrap().take() {
@@ -3074,6 +3117,32 @@ mod tests {
}
}
+ #[test]
+ fn explicit_revival_clears_tombstone_and_recreates_lazily() {
+ let move_msg = |x, y| {
+ OverlayMsg::Cmd(KeyedOverlayCommand {
+ key: "sessA".to_owned(),
+ cmd: OverlayCommand::MoveTo {
+ x,
+ y,
+ end_heading_radians: 0.0,
+ },
+ })
+ };
+ let mut map = default_render_map();
+ apply_msg(&mut map, move_msg(10.0, 10.0));
+ apply_msg(&mut map, OverlayMsg::Remove("sessA".to_owned()));
+ assert!(apply_msg(&mut map, move_msg(20.0, 20.0)).is_none());
+
+ apply_msg(&mut map, OverlayMsg::Revive("sessA".to_owned()));
+ assert!(!map.cursors.contains_key("sessA"));
+ assert!(!map.ended.contains("sessA"));
+
+ let resolved = apply_msg(&mut map, move_msg(30.0, 30.0));
+ assert_eq!(resolved.as_deref(), Some("sessA"));
+ assert!(map.cursors.contains_key("sessA"));
+ }
+
fn test_message() -> OverlayMsg {
OverlayMsg::Cmd(KeyedOverlayCommand {
key: "default".to_owned(),
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
index 422a2609fa..4e2f091e14 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
@@ -1887,7 +1887,7 @@ fn mouse_button_name(button: u8) -> &'static str {
}
fn resolve_cursor_key(args: &Value) -> String {
- for key in ["session", "cursor_id"] {
+ for key in ["session", "_session_id", "cursor_id"] {
if let Some(v) = args.get(key).and_then(|v| v.as_str()) {
if !v.is_empty() {
return v.to_owned();
@@ -1897,6 +1897,35 @@ fn resolve_cursor_key(args: &Value) -> String {
"default".to_owned()
}
+#[cfg(test)]
+mod cursor_key_resolution_tests {
+ use super::resolve_cursor_key;
+ use serde_json::json;
+
+ #[test]
+ fn trusted_implicit_session_owns_the_cursor() {
+ assert_eq!(resolve_cursor_key(&json!({})), "default");
+ assert_eq!(
+ resolve_cursor_key(&json!({"_session_id": "implicit-lease"})),
+ "implicit-lease"
+ );
+ assert_eq!(
+ resolve_cursor_key(&json!({
+ "_session_id": "implicit-lease",
+ "cursor_id": "legacy"
+ })),
+ "implicit-lease"
+ );
+ assert_eq!(
+ resolve_cursor_key(&json!({
+ "session": "named",
+ "_session_id": "implicit-lease"
+ })),
+ "named"
+ );
+ }
+}
+
fn mouse_hold_json(cursor_id: &str, hold: Option<&MouseHoldState>) -> Value {
match hold {
Some(hold) => json!({
@@ -2210,7 +2239,7 @@ impl Tool for ClickTool {
let cursor_id = resolve_cursor_key(&args);
let modifiers: Vec<String> = args.str_array("modifier");
- // ── Window-less screen-absolute branch (capture_scope="desktop") ──────
+ // ── Window-less screen-absolute branch (desktop target) ───────────────
// x,y with NO pid and NO window_id → TRUE SCREEN pixels. Foreground,
// desktop-scope click (the Linux peer of the Windows WindowFromPoint /
// macOS global-HID path). The core registry has already enforced the
@@ -6241,12 +6270,11 @@ impl Tool for GetDesktopStateTool {
fn def(&self) -> &ToolDef {
GDS_DEF.get_or_init(|| ToolDef {
name: "get_desktop_state".into(),
- description: "Full-display vision screenshot in true screen pixels (no downscale), \
- for capture_scope=\"desktop\" GUI loops. Captures the entire display (root \
- window) as native-size PNG so screen-absolute pixel coordinates land exactly. \
- No AT-SPI walk.".into(),
+ description: "Capture the full display in true screen pixels with no downscale. \
+ Use its native-size PNG as the coordinate source for actions whose target is \
+ {kind:\"desktop\",display_id:\"primary\"}. No AT-SPI walk.".into(),
input_schema: json!({"type":"object","properties":{
- "session":{"type":"string","description":"Optional session id."},
+ "session":{"type":"string","description":"Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session."},
"screenshot_out_file":{"type":"string","description":"Write PNG here instead of base64."}
},"additionalProperties":false}),
read_only: true, destructive: false, idempotent: false, open_world: false,
@@ -6462,14 +6490,9 @@ impl Tool for MoveCursorTool {
// End pointing upper-left (45°) — matches Swift's
// `AgentCursor.animateAndWait(endAngleDegrees: 45)` convention so the
// overlay arrow settles to the natural macOS-style pose.
- crate::overlay::send_command_for(
- cursor_id.clone(),
- cursor_overlay::OverlayCommand::MoveTo {
- x,
- y,
- end_heading_radians: std::f64::consts::FRAC_PI_4,
- },
- );
+ // Use the acknowledged animation path so a first-ever move seeds and
+ // displays the session cursor just as reliably as a coordinate click.
+ crate::overlay::animate_cursor_to_for(cursor_id.clone(), x, y).await;
// Native Wayland: also warp the real cursor via zwlr_virtual_pointer.
// Off-thread because the wayland-client roundtrip is blocking. Best-effort
// — overlay update + registry write already succeeded; surface a warning
@@ -6867,12 +6890,12 @@ impl Tool for SetConfigTool {
|| args.get("key").and_then(Value::as_str) == Some("capture_scope")
{
return ToolResult::error(
- "config key 'capture_scope' is retired; pass capture_scope=auto|window|desktop to start_session",
+ "config key 'capture_scope' is retired; select a window or desktop target on each action",
)
.with_structured(json!({
"code": "config_key_retired",
"key": "capture_scope",
- "replacement": "start_session.capture_scope",
+ "replacement": "action.target",
}));
}
let mut cfg = self.state.config.write().unwrap();
@@ -7768,11 +7791,13 @@ pub fn build_registry_with_provider(
Some(state) => cua_driver_core::session::bounded_cursor_outcome(
true,
state.config.enabled,
+ crate::overlay::is_visible_for_session(session_id),
Some(state.config.theme_id.as_str()),
motion_customized,
active_cursor_count,
),
None => cua_driver_core::session::bounded_cursor_outcome(
+ false,
false,
false,
None,
@@ -7797,9 +7822,14 @@ pub fn build_registry_with_provider(
crate::input::forget_master_pointer(session_id);
})
};
+ let session_revive_hook =
+ cua_driver_core::session::register_scoped_session_revive_hook(move |session_id| {
+ crate::overlay::revive_cursor(session_id.to_owned());
+ });
let mut r = ToolRegistry::new_with_protected_consent_provider(provider);
r.retain_cursor_outcome_reader(cursor_outcome_reader);
r.retain_session_end_hook(session_end_hook);
+ r.retain_session_revive_hook(session_revive_hook);
if let Some(runtime_scope) = cua_driver_core::tool::current_dispatch_runtime_scope() {
let prefix = format!("__cua_runtime_{runtime_scope}:");
let cursor_registry = state.cursor_registry.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 63c35971a7..088846188e 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
@@ -98,6 +98,11 @@ pub fn forward(msg: &OverlayMsg) -> bool {
if !should_forward(CONFIG_ENABLED.load(Ordering::Acquire), msg) {
return false;
}
+ // The native Wayland path owns one cursor and does not keep keyed session
+ // tombstones. Accept revival without starting the compositor thread.
+ if matches!(msg, OverlayMsg::Revive(_)) {
+ return true;
+ }
// Lazy startup: spawning the layer-shell owner thread + connecting to
// the Wayland compositor takes 100-300ms. Doing that at cua-driver mcp
// boot (the old eager-init path) was tipping the borderline CI
@@ -123,6 +128,7 @@ pub fn forward(msg: &OverlayMsg) -> bool {
});
true
}
+ OverlayMsg::Revive(_) => true,
}
}
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 d30a109555..a99fe59823 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
@@ -91,13 +91,13 @@ struct RenderMap {
backing_scale: f64,
/// Frozen launch-time config used as the template for lazily-created cursors.
template: CursorConfig,
- /// Render-side tombstone of permanently-ended session cursor keys. A `Cmd`
+ /// Render-side tombstone of ended session cursor keys. A `Cmd`
/// for a key in here is dropped WITHOUT get-or-create, so an in-flight
/// click/move from another task that lands AFTER the owning session's
/// `Remove` can never resurrect the just-removed cursor (the ghost-cursor
- /// resurrection race). Keyed on session_id, which is unique per session, so
- /// a permanent tombstone is correct (no cursor_id reuse across a
- /// session_end boundary). "default" is never tombstoned.
+ /// resurrection race). An explicit owner-checked `start_session` revival
+ /// clears this tombstone before the cursor is reused. "default" is never
+ /// tombstoned.
ended: std::collections::HashSet<CursorKey>,
}
@@ -114,7 +114,7 @@ fn render_state_for_key(template: &CursorConfig, key: &str) -> RenderState {
/// unit-testable without AppKit.
///
/// Returns the resolved cursor key for a `Cmd` (so the caller can track the
-/// last-active key for z-order pinning); `None` for a `Remove`.
+/// last-active key for z-order pinning); `None` for a lifecycle message.
fn apply_msg(map: &mut RenderMap, msg: OverlayMsg) -> Option<CursorKey> {
match msg {
OverlayMsg::Remove(key) => {
@@ -134,6 +134,12 @@ fn apply_msg(map: &mut RenderMap, msg: OverlayMsg) -> Option<CursorKey> {
}
None
}
+ OverlayMsg::Revive(key) => {
+ if key != "default" {
+ map.ended.remove(&key);
+ }
+ None
+ }
OverlayMsg::Cmd(KeyedOverlayCommand { key, cmd }) => {
// Drop a command for an already-ended session WITHOUT get-or-create
// — this is the resurrection guard. Without it, a ClickPulse/MoveTo
@@ -214,8 +220,8 @@ pub fn init(cfg: CursorConfig) {
/// Send a keyed command from any thread (MCP tool, etc.). Non-blocking; drops
/// if the channel is full (old commands are less important than new ones).
pub fn send_command(key: CursorKey, cmd: OverlayCommand) {
- // Empty key is the explicit no-cursor sentinel → drop the command so a
- // cursor-less run never paints.
+ // Empty key is the explicit no-cursor sentinel for direct platform calls
+ // that bypass lifecycle dispatch.
if key.is_empty() {
return;
}
@@ -230,6 +236,22 @@ pub fn send_command_default(cmd: OverlayCommand) {
send_command("default".to_owned(), cmd);
}
+/// Truthful render acknowledgement for lifecycle inspection. This never falls
+/// back to the seeded default cursor: an absent, off-screen, disabled, or
+/// idle-faded session cursor is not reported as visible.
+pub fn is_visible_for_session(key: &str) -> bool {
+ RENDER
+ .lock()
+ .ok()
+ .and_then(|guard| {
+ guard
+ .as_ref()
+ .and_then(|map| map.cursors.get(key))
+ .map(cursor_is_externally_visible)
+ })
+ .unwrap_or(false)
+}
+
/// Remove a session's owned cursor from the render collection (fired from the
/// `session_end` hook). The `"default"` key is guarded against removal on the
/// render side, so this is a no-op for it; removing an absent key (anonymous
@@ -243,6 +265,17 @@ pub fn remove_cursor(key: CursorKey) {
}
}
+/// Clear the render-side tombstone after a successful explicit session
+/// revival. Cursor recreation remains lazy until the next render command.
+pub fn revive_cursor(key: CursorKey) {
+ if key.is_empty() {
+ return;
+ }
+ if let Some(tx) = CMD_TX.get() {
+ let _ = tx.try_send(OverlayMsg::Revive(key));
+ }
+}
+
/// Return a snapshot of a cursor's current motion config (for use by
/// set_agent_cursor_motion to apply partial overrides without losing other
/// knobs). Reads the motion of the cursor `key`, falling back to the
@@ -1384,6 +1417,22 @@ mod tests {
);
}
+ #[test]
+ fn explicit_revival_clears_tombstone_and_recreates_lazily() {
+ let mut map = empty_map();
+ apply_msg(&mut map, move_msg("sessA", 10.0, 10.0));
+ apply_msg(&mut map, OverlayMsg::Remove("sessA".to_owned()));
+ assert!(apply_msg(&mut map, move_msg("sessA", 20.0, 20.0)).is_none());
+
+ apply_msg(&mut map, OverlayMsg::Revive("sessA".to_owned()));
+ assert!(!map.cursors.contains_key("sessA"));
+ assert!(!map.ended.contains("sessA"));
+
+ let resolved = apply_msg(&mut map, move_msg("sessA", 30.0, 30.0));
+ assert_eq!(resolved.as_deref(), Some("sessA"));
+ assert!(map.cursors.contains_key("sessA"));
+ }
+
#[test]
fn default_is_never_tombstoned() {
// Remove("default") is guarded, so default is never tombstoned and a
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs
index 59298a27f4..8faa6c24df 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs
@@ -159,14 +159,14 @@ fn def() -> &'static ToolDef {
// cua_driver_core::tool_schema.)
"required": [],
"properties": {
- "session": { "type": "string", "description": "Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less." },
+ "session": { "type": "string", "description": "Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session." },
"pid": { "type": "integer", "description": "Target process ID." },
"window_id": { "type": "integer", "description": "Target window ID. Required for element_index. Optional when element_token is supplied (the token carries it)." },
"element_index": cua_driver_core::tool_schema::element_index_schema(),
"element_token": cua_driver_core::tool_schema::element_token_schema(),
"snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),
- "x": { "type": "number", "description": "X in screenshot pixels, read straight off the image you were handed — no scaling math needed. With pid+window_id (capture_scope=window): window-local pixels from the get_window_state PNG (top-left origin). Windowless (no pid/window_id, capture_scope=desktop): pixels from the get_desktop_state PNG (the native full-display image). Either way, the pixel you read IS the pixel that gets clicked; the driver undoes the Retina backing scale + any downscale internally." },
- "y": { "type": "number", "description": "Y in screenshot pixels (see x). Window-local from get_window_state, or full-display from get_desktop_state under capture_scope=desktop." },
+ "x": { "type": "number", "description": "X in screenshot pixels. A window target uses the get_window_state PNG; a desktop target uses the native get_desktop_state PNG. The driver reverses Retina backing scale and any window-image downscale." },
+ "y": { "type": "number", "description": "Y in screenshot pixels from the image selected by target." },
"action": { "type": "string", "description": "AX action: press, show_menu, pick, confirm, cancel, open." },
"button": {
"type": "string",
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/cursor_tools.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/cursor_tools.rs
index 1ae5d4799c..8023a2055b 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/cursor_tools.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/cursor_tools.rs
@@ -352,6 +352,10 @@ mod tests {
})),
"explicit"
);
+ assert_eq!(
+ resolve_cursor_key(&json!({"_session_id": "implicit-lease"})),
+ "implicit-lease"
+ );
}
#[test]
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs
index 26b03e06e8..c3ae1439ce 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs
@@ -48,7 +48,7 @@ fn def() -> &'static ToolDef {
"type": "object",
"required": ["pid"],
"properties": {
- "session": { "type": "string", "description": "Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less." },
+ "session": { "type": "string", "description": "Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session." },
"pid": { "type": "integer" },
"x": { "type": "number", "description": "Screen X coordinate (pixel path)." },
"y": { "type": "number", "description": "Screen Y coordinate (pixel path)." },
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs
index 8eb5638fd3..62c9d1aadc 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs
@@ -56,7 +56,7 @@ fn def() -> &'static ToolDef {
"type": "object",
"required": ["from_x", "from_y", "to_x", "to_y"],
"properties": {
- "session": { "type": "string", "description": "Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less." },
+ "session": { "type": "string", "description": "Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session." },
"pid": { "type": "integer", "description": "Target process ID." },
"window_id": {
"type": "integer",
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_config.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_config.rs
index a1b1474952..a1dc0cbab1 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_config.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_config.rs
@@ -76,8 +76,8 @@ impl Tool for GetConfigTool {
// sharing its package version.
"source_sha": option_env!("CUA_DRIVER_SOURCE_SHA"),
"platform": "macos",
- // capture_mode is per-call; capture_scope is per-session and is
- // reported by get_session_state rather than persistent config.
+ // capture_mode is deprecated; capture_scope is retired from
+ // persistent config. Actions select a target per call.
"max_image_dimension": max_image_dimension,
"agent_cursor": {
"enabled": cursor_enabled,
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_desktop_state.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_desktop_state.rs
index 1a6775ca16..5bb1a51cef 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_desktop_state.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_desktop_state.rs
@@ -3,9 +3,8 @@
//! Vision-only desktop capture: grabs the ENTIRE main display at native
//! pixel size (no downscale) so screen-absolute pixel picks land exactly,
//! then reports the true screen size + backing scale. No AX walk, no
-//! pid/window_id — this is the capture surface for `capture_scope="desktop"`
-//! GUI loops where the agent drives `click(x,y)` / `scroll(x,y)` against
-//! screen-absolute coordinates.
+//! pid/window_id. This is the capture surface for actions with a primary-display
+//! desktop target and screen-absolute coordinates.
//!
//! Mirrors `get_window_state.rs`'s vision ToolResult shape: an `image_png`
//! content part (or a written-out file path), a text summary line, and a
@@ -29,16 +28,15 @@ static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();
fn def() -> &'static ToolDef {
DEF.get_or_init(|| ToolDef {
name: "get_desktop_state".into(),
- description: "Capture a full-display vision screenshot in true screen pixels \
- (no downscale), for scope=\"desktop\" GUI loops where the agent then \
- drives click(x,y, scope=\"desktop\") with no pid/window_id. Returns the PNG at native \
- display resolution plus the true screen size and backing scale factor so \
- screen-absolute pixel picks land exactly. Vision-only: no AX tree walk."
+ description: "Capture the full display in true screen pixels with no downscale. \
+ Use its native-size PNG as the coordinate source for actions whose target is \
+ {kind:\"desktop\",display_id:\"primary\"}. Returns the true screen size and \
+ backing scale factor. Vision-only: no AX tree walk."
.into(),
input_schema: serde_json::json!({
"type": "object",
"properties": {
- "session": { "type": "string", "description": "Optional session id." },
+ "session": { "type": "string", "description": "Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session." },
"screenshot_out_file": { "type": "string", "description": "Write PNG here instead of base64." }
},
"additionalProperties": false
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs
index 2e9477b4fc..e32a8dbbe0 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs
@@ -74,7 +74,7 @@ fn def() -> &'static ToolDef {
"type": "object",
"required": ["pid", "window_id"],
"properties": {
- "session": { "type": "string", "description": "Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less." },
+ "session": { "type": "string", "description": "Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session." },
"pid": { "type": "integer", "description": "Target process ID." },
"window_id": { "type": "integer", "description": "Target window ID from list_windows." },
"query": { "type": "string", "description": "Case-insensitive filter for tree_markdown and structured elements. Returns matching actionable rows plus their actionable ancestors without renumbering element_index values." },
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/hotkey.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/hotkey.rs
index b2e8438f89..b907d7b2d0 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/hotkey.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/hotkey.rs
@@ -61,7 +61,7 @@ fn def() -> &'static ToolDef {
"type": "object",
"required": ["keys"],
"properties": {
- "session": { "type": "string", "description": "Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less." },
+ "session": { "type": "string", "description": "Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session." },
"pid": { "type": "integer", "description": "Target process ID." },
"keys": {
"type": "array",
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
index 1a322910ad..fe7269f154 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
@@ -773,11 +773,13 @@ pub fn register_all(
Some(state) => cua_driver_core::session::bounded_cursor_outcome(
true,
state.config.enabled,
+ crate::cursor::overlay::is_visible_for_session(session_id),
Some(state.config.theme_id.as_str()),
motion_customized,
active_cursor_count,
),
None => cua_driver_core::session::bounded_cursor_outcome(
+ false,
false,
false,
None,
@@ -826,6 +828,11 @@ pub fn register_all(
crate::cursor::overlay::remove_cursor(session_id.to_owned());
});
registry.retain_session_end_hook(registration);
+ let revive_registration =
+ cua_driver_core::session::register_scoped_session_revive_hook(move |session_id| {
+ crate::cursor::overlay::revive_cursor(session_id.to_owned());
+ });
+ registry.retain_session_revive_hook(revive_registration);
}
registry.register(Box::new(list_apps::ListAppsTool));
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/move_cursor.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/move_cursor.rs
index f47ca64245..59bc55f4b8 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/move_cursor.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/move_cursor.rs
@@ -32,7 +32,7 @@ fn def() -> &'static ToolDef {
"type": "object",
"required": ["x", "y"],
"properties": {
- "session": { "type": "string", "description": "Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less." },
+ "session": { "type": "string", "description": "Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session." },
"x": { "type": "number" },
"y": { "type": "number" },
"scope": { "type": "string", "enum": ["window", "desktop"], "default": "window" },
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/press_key.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/press_key.rs
index 228ff8848f..6854393ec0 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/press_key.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/press_key.rs
@@ -200,7 +200,7 @@ fn def() -> &'static ToolDef {
"type": "object",
"required": ["key"],
"properties": {
- "session": { "type": "string", "description": "Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less." },
+ "session": { "type": "string", "description": "Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session." },
"pid": { "type": "integer" },
"key": { "type": "string", "description": "Key name: return, tab, escape, up, down, etc." },
"modifiers": {
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs
index c32d343013..112b0b2339 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs
@@ -43,7 +43,7 @@ fn def() -> &'static ToolDef {
"type": "object",
"required": ["pid"],
"properties": {
- "session": { "type": "string", "description": "Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less." },
+ "session": { "type": "string", "description": "Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session." },
"pid": { "type": "integer", "description": "Target process ID." },
"element_index": cua_driver_core::tool_schema::element_index_schema(),
"element_token": cua_driver_core::tool_schema::element_token_schema(),
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rs
index c788ee7af0..33f1b67d91 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rs
@@ -79,7 +79,7 @@ fn def() -> &'static ToolDef {
// schema — keeps the contract consistent across platforms.
"required": ["direction"],
"properties": {
- "session": { "type": "string", "description": "Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less." },
+ "session": { "type": "string", "description": "Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session." },
"pid": { "type": "integer" },
"direction": {
"type": "string",
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_config.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_config.rs
index 56c9e08378..dbf3d225f3 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_config.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_config.rs
@@ -29,7 +29,8 @@ fn def() -> &'static ToolDef {
take effect on the next daemon restart (the PiP backend is \
initialised once at startup).\n\nNote: capture_mode is a per-call \
param (on get_window_state / click), not a stored setting. Capture \
- scope is selected by start_session, not set_config.".into(),
+ modality is selected by each action's target; the old \
+ capture_scope config key is retired.".into(),
input_schema: serde_json::json!({
"type": "object",
"properties": {
@@ -78,12 +79,12 @@ impl Tool for SetConfigTool {
|| args.get("key").and_then(Value::as_str) == Some("capture_scope")
{
return ToolResult::error(
- "config key 'capture_scope' is retired; pass capture_scope=auto|window|desktop to start_session",
+ "config key 'capture_scope' is retired; select a window or desktop target on each action",
)
.with_structured(serde_json::json!({
"code": "config_key_retired",
"key": "capture_scope",
- "replacement": "start_session.capture_scope",
+ "replacement": "action.target",
}));
}
// The daemon injects `_session_id` for non-anonymous MCP sessions.
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rs
index 340b15fd35..d91f3c6ece 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/set_value.rs
@@ -64,7 +64,7 @@ fn def() -> &'static ToolDef {
"type": "object",
"required": ["pid", "value"],
"properties": {
- "session": { "type": "string", "description": "Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less." },
+ "session": { "type": "string", "description": "Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session." },
"pid": { "type": "integer" },
"window_id": {
"type": "integer",
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs
index aa2a283059..b92a02a9cd 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs
@@ -90,7 +90,7 @@ fn def() -> &'static ToolDef {
"type": "object",
"required": ["text"],
"properties": {
- "session": { "type": "string", "description": "Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less." },
+ "session": { "type": "string", "description": "Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session." },
"pid": { "type": "integer", "description": "Target process ID." },
"text": { "type": "string", "description": "Text to insert at the target's cursor." },
"window_id": {
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 f18f1d4762..d9ecc74bfa 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/overlay.rs
@@ -98,11 +98,12 @@ struct RenderMap {
last_tick: Instant,
/// Frozen launch-time config used as the template for lazily-created cursors.
template: CursorConfig,
- /// Render-side tombstone of permanently-ended session cursor keys. A `Cmd`
+ /// Render-side tombstone of ended session cursor keys. A `Cmd`
/// for a key in here is dropped WITHOUT get-or-create, so an in-flight
/// click/move from another task that lands AFTER the owning session's
- /// `Remove` can never resurrect the just-removed cursor. "default" is never
- /// tombstoned (it backs the anonymous / one-shot path).
+ /// `Remove` can never resurrect the just-removed cursor. An explicit
+ /// owner-checked revival clears the tombstone. "default" is never
+ /// tombstoned for legacy direct platform calls.
ended: HashSet<CursorKey>,
/// Cursor key whose target the overlay should currently sit above. A single
/// layered window can occupy only one z-band, so the most-recently-touched
@@ -123,7 +124,7 @@ fn render_state_for_key(template: &CursorConfig, key: &str) -> RenderState {
/// unit-testable without any Win32 window.
///
/// Returns the resolved cursor key for a `Cmd` (so the caller can track the
-/// last-active key for z-order pinning); `None` for a `Remove`.
+/// last-active key for z-order pinning); `None` for a lifecycle message.
fn apply_msg(map: &mut RenderMap, msg: OverlayMsg) -> Option<CursorKey> {
match msg {
OverlayMsg::Remove(key) => {
@@ -145,6 +146,12 @@ fn apply_msg(map: &mut RenderMap, msg: OverlayMsg) -> Option<CursorKey> {
}
None
}
+ OverlayMsg::Revive(key) => {
+ if key != "default" {
+ map.ended.remove(&key);
+ }
+ None
+ }
OverlayMsg::Cmd(KeyedOverlayCommand { key, cmd }) => {
// Drop a command for an already-ended session WITHOUT get-or-create
// — this is the resurrection guard. Without it, a ClickPulse/MoveTo
@@ -296,6 +303,18 @@ pub fn remove_cursor(key: CursorKey) {
}
}
+/// Clear the render-side tombstone after a successful explicit session
+/// revival. Cursor recreation remains lazy until the next render command.
+pub fn revive_cursor(key: CursorKey) {
+ if key.is_empty() {
+ return;
+ }
+ if let Some(tx) = CMD_TX.get() {
+ let _ = tx.try_send(OverlayMsg::Revive(key));
+ wake_overlay();
+ }
+}
+
/// Returns true if the cursor for `key` is currently enabled/visible. A session
/// with no own cursor yet falls back to the seeded `"default"` cursor.
pub fn is_enabled(key: &str) -> bool {
@@ -313,6 +332,27 @@ pub fn is_enabled(key: &str) -> bool {
.unwrap_or(false)
}
+/// Truthful render acknowledgement for lifecycle inspection. Unlike
+/// [`is_enabled`], this checks the exact session key and never falls back to
+/// the seeded default cursor.
+pub fn is_visible_for_session(key: &str) -> bool {
+ RENDER
+ .lock()
+ .ok()
+ .and_then(|guard| {
+ guard
+ .as_ref()
+ .and_then(|map| map.cursors.get(key))
+ .map(|rs| {
+ rs.core.cfg.enabled
+ && rs.core.visible
+ && rs.core.idle_alpha >= 0.004
+ && rs.core.pos.0 >= -100.0
+ })
+ })
+ .unwrap_or(false)
+}
+
/// Snapshot the current motion config for `key`, falling back to the
/// `"default"` cursor's motion when that key has no own entry yet.
pub fn current_motion(key: &str) -> MotionConfig {
@@ -1711,6 +1751,22 @@ mod tests {
assert_eq!(map.cursors.len(), 1);
}
+ #[test]
+ fn explicit_revival_clears_tombstone_and_recreates_lazily() {
+ let mut map = empty_map();
+ apply_msg(&mut map, move_msg("sessA", 10.0, 10.0));
+ apply_msg(&mut map, OverlayMsg::Remove("sessA".to_owned()));
+ assert!(apply_msg(&mut map, move_msg("sessA", 20.0, 20.0)).is_none());
+
+ apply_msg(&mut map, OverlayMsg::Revive("sessA".to_owned()));
+ assert!(!map.cursors.contains_key("sessA"));
+ assert!(!map.ended.contains("sessA"));
+
+ let resolved = apply_msg(&mut map, move_msg("sessA", 30.0, 30.0));
+ assert_eq!(resolved.as_deref(), Some("sessA"));
+ assert!(map.cursors.contains_key("sessA"));
+ }
+
#[test]
fn default_is_never_tombstoned() {
let mut map = empty_map();
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
index d67ac8021c..a1ca333b17 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
@@ -11,8 +11,8 @@ use async_trait::async_trait;
/// the host appears in the z-order. `GA_ROOT` normalises both inputs to the
/// host so the overlay sits at z+1 of whatever is actually painted on screen.
///
-/// No-op when the overlay is disabled or `key` is empty (anonymous, cursor-less
-/// run); the command is just dropped by the render thread in that case.
+/// No-op when the overlay is disabled or `key` is empty (a direct platform
+/// call without lifecycle metadata); the render thread drops the command.
fn pin_overlay_above(key: &str, hwnd: u64) {
use windows::Win32::Foundation::HWND;
use windows::Win32::UI::WindowsAndMessaging::{GetAncestor, GA_ROOT};
@@ -242,8 +242,8 @@ fn screen_to_bitmap(hwnd: u64, sx: i32, sy: i32) -> (i32, i32) {
/// `tokio::sleep(80..600 ms)` was racing the spring-physics glide).
///
/// `key` is the session's cursor key (see [`resolve_cursor_key`]). An empty key
-/// (anonymous, no declared session) is cursor-less: every overlay op
-/// short-circuits, so the action runs with no visible cursor.
+/// is possible only for a direct platform call without lifecycle metadata; in
+/// that case every overlay operation short-circuits.
async fn overlay_glide_to(key: &str, sx: f64, sy: f64) {
if key.is_empty() {
return;
@@ -465,23 +465,19 @@ fn pid_window_guarded<T: Tool + 'static>(
})
}
-/// The cursor key for an anonymous (cursor-less) call. A run opts into a cursor
-/// by declaring a `session`; without one, every cursor op short-circuits on
-/// this empty key (see `overlay::send_command` / `overlay_glide_to`).
+/// Cursor sentinel for a direct platform call without lifecycle metadata.
+/// Normal runtime dispatch supplies either a named or implicit session key.
pub(crate) const NO_CURSOR: &str = "";
/// Resolve the cursor key for a tool invocation, or [`NO_CURSOR`] (`""`) for an
/// anonymous call.
///
-/// A cursor is tied to a **caller-declared session**, never to the MCP
-/// connection. Precedence: an explicit `session` arg, then its legacy alias
-/// `cursor_id`. We deliberately do NOT fall back to the connection-injected
-/// `_session_id` or to a seeded `"default"` cursor — `""` means "no session
-/// declared → no cursor", while the underlying action (click/type/…) still
-/// executes. Mirrors `platform_macos::tools::cursor_tools::resolve_cursor_key`
-/// so the two platforms key cursors identically.
+/// A cursor is tied to the lifecycle session selected at the trusted dispatch
+/// boundary. Precedence: explicit `session`, trusted implicit `_session_id`,
+/// then the legacy `cursor_id` alias. A direct platform invocation that has no
+/// lifecycle metadata remains cursor-less.
pub(crate) fn resolve_cursor_key(args: &Value) -> String {
- for key in ["session", "cursor_id"] {
+ for key in ["session", "_session_id", "cursor_id"] {
if let Some(v) = args.get(key).and_then(|v| v.as_str()) {
if !v.is_empty() {
return v.to_owned();
@@ -2905,7 +2901,7 @@ impl Tool for ClickTool {
use cua_driver_core::tool_args::ArgsExt;
let cursor_key = resolve_cursor_key(&args);
- // ── Window-less screen-absolute branch (capture_scope="desktop") ──────
+ // ── Window-less screen-absolute branch (desktop target) ───────────────
// When the caller gives x,y with NO pid/window_id, treat x,y as TRUE
// SCREEN pixels. The core registry has already enforced the session's
// effective capture scope; this local check validates the action form.
@@ -5609,7 +5605,7 @@ impl Tool for ScrollTool {
async fn invoke(&self, args: Value) -> ToolResult {
use crate::input::delivery::{DeliveryMode, EventKind};
use cua_driver_core::tool_args::ArgsExt;
- // ── Window-less screen-absolute branch (capture_scope="desktop") ──────
+ // ── Window-less screen-absolute branch (desktop target) ───────────────
// No pid/window_id + numeric x,y + desktop scope → synthesize a wheel
// event at the screen point via SendInput. The wheel routes to whatever
// window is under (x,y). up/down map to a vertical wheel (sign), and
@@ -7251,9 +7247,8 @@ impl Tool for GetScreenSizeTool {
/// Vision-only desktop capture: grabs the ENTIRE primary display at native
/// physical-pixel size (no downscale) so screen-absolute pixel picks land
/// exactly, then reports the true screen size. No UIA walk, no pid/window_id —
-/// this is the capture surface for `capture_scope="desktop"` GUI loops where
-/// the agent drives `click(x,y)` / `scroll(x,y)` against screen-absolute
-/// coordinates.
+/// this is the capture surface for actions with a primary-display desktop
+/// target and screen-absolute coordinates.
///
/// Mirrors the `get_window_state` vision branch's ToolResult shape: an
/// `image_png` content part (or a written-out file path), a text summary line,
@@ -7266,15 +7261,14 @@ impl Tool for GetDesktopStateTool {
fn def(&self) -> &ToolDef {
GDS_DEF.get_or_init(|| ToolDef {
name: "get_desktop_state".into(),
- description: "Capture a full-display vision screenshot in true screen pixels \
- (no downscale), for capture_scope=\"desktop\" GUI loops where the agent then \
- drives click(x,y)/scroll(x,y) with no pid/window_id. Returns the PNG at native \
- display resolution plus the true screen size so screen-absolute pixel picks \
- land exactly. Vision-only: no UIA tree walk.".into(),
+ description: "Capture the full display in true screen pixels with no downscale. \
+ Use its native-size PNG as the coordinate source for actions whose target is \
+ {kind:\"desktop\",display_id:\"primary\"}. Returns the true screen size. \
+ Vision-only: no UIA tree walk.".into(),
input_schema: json!({
"type": "object",
"properties": {
- "session": { "type": "string", "description": "Optional session id." },
+ "session": { "type": "string", "description": "Optional public session label. Omit it to use the authenticated transport's implicit lifecycle session." },
"screenshot_out_file": { "type": "string", "description": "Write PNG here instead of base64." }
},
"additionalProperties": false
@@ -7441,8 +7435,8 @@ impl Tool for MoveCursorTool {
}
let x = args.f64_or("x", 0.0);
let y = args.f64_or("y", 0.0);
- // Cursor key precedence: caller-declared `session` > legacy `cursor_id`
- // > NO_CURSOR. An anonymous run (no session) has no cursor to move.
+ // The trusted dispatch boundary always supplies a lifecycle key,
+ // including for an unnamed implicit session.
let cursor_key = resolve_cursor_key(&args);
if !cursor_key.is_empty() {
self.state
@@ -7452,14 +7446,9 @@ impl Tool for MoveCursorTool {
// End pointing upper-left (45°) — matches Swift's
// `AgentCursor.animateAndWait(endAngleDegrees: 45)` convention so
// the cursor settles to the natural macOS-style pose.
- crate::overlay::send_command(
- cursor_key.clone(),
- cursor_overlay::OverlayCommand::MoveTo {
- x,
- y,
- end_heading_radians: std::f64::consts::FRAC_PI_4,
- },
- );
+ // Use the acknowledged animation path so a first-ever move seeds and
+ // displays the session cursor just as reliably as a coordinate click.
+ crate::overlay::animate_cursor_to(cursor_key.clone(), x, y).await;
let shown = if cursor_key.is_empty() {
"default"
} else {
@@ -7977,12 +7966,12 @@ impl Tool for SetConfigTool {
|| args.get("key").and_then(Value::as_str) == Some("capture_scope")
{
return ToolResult::error(
- "config key 'capture_scope' is retired; pass capture_scope=auto|window|desktop to start_session",
+ "config key 'capture_scope' is retired; select a window or desktop target on each action",
)
.with_structured(json!({
"code": "config_key_retired",
"key": "capture_scope",
- "replacement": "start_session.capture_scope",
+ "replacement": "action.target",
}));
}
let mut cfg = self.state.config.write().unwrap();
@@ -9362,11 +9351,13 @@ pub fn build_registry_with_provider(
Some(state) => cua_driver_core::session::bounded_cursor_outcome(
true,
state.config.enabled,
+ crate::overlay::is_visible_for_session(session_id),
Some(state.config.theme_id.as_str()),
motion_customized,
active_cursor_count,
),
None => cua_driver_core::session::bounded_cursor_outcome(
+ false,
false,
false,
None,
@@ -9395,10 +9386,15 @@ pub fn build_registry_with_provider(
cursor_registry.remove(session_id);
crate::overlay::remove_cursor(session_id.to_owned());
});
+ let session_revive_hook =
+ cua_driver_core::session::register_scoped_session_revive_hook(move |session_id| {
+ crate::overlay::revive_cursor(session_id.to_owned());
+ });
let mut r = ToolRegistry::new_with_protected_consent_provider(provider);
r.retain_cursor_outcome_reader(cursor_outcome_reader);
r.retain_session_end_hook(session_end_hook);
+ r.retain_session_revive_hook(session_revive_hook);
if let Some(runtime_scope) = cua_driver_core::tool::current_dispatch_runtime_scope() {
let prefix = format!("__cua_runtime_{runtime_scope}:");
let cursor_registry = state.cursor_registry.clone();
@@ -9576,15 +9572,15 @@ mod cursor_key_resolution_tests {
use serde_json::json;
#[test]
- fn anonymous_resolves_to_no_cursor() {
+ fn direct_platform_call_without_lifecycle_resolves_to_no_cursor() {
// No session/cursor_id → NO_CURSOR (""): the action still runs but no
- // cursor is shown. The connection-injected `_session_id` is NOT a cursor
- // source — it stays the recording/config lifecycle key.
+ // cursor is shown. Canonical core dispatch injects `_session_id` before
+ // real platform calls.
assert_eq!(resolve_cursor_key(&json!({})), NO_CURSOR);
assert_eq!(resolve_cursor_key(&json!({ "pid": 1 })), NO_CURSOR);
assert_eq!(
resolve_cursor_key(&json!({ "_session_id": "mcp-1-2" })),
- NO_CURSOR
+ "mcp-1-2"
);
}
@@ -9606,6 +9602,10 @@ mod cursor_key_resolution_tests {
resolve_cursor_key(&json!({ "session": "s1", "cursor_id": "c1" })),
"s1"
);
+ assert_eq!(
+ resolve_cursor_key(&json!({ "_session_id": "implicit", "cursor_id": "c1" })),
+ "implicit"
+ );
}
#[test]
diff --git a/libs/cua-driver/typescript/README.md b/libs/cua-driver/typescript/README.md
index a8b7135730..448843c716 100644
--- a/libs/cua-driver/typescript/README.md
+++ b/libs/cua-driver/typescript/README.md
@@ -30,7 +30,6 @@ agent SDK.
```ts
import {
- CaptureScope,
CuaDriver,
CursorReducedMotion,
EndSessionInput,
@@ -43,7 +42,6 @@ const driver = CuaDriver.create(undefined) // same process; no daemon
await driver.startSession(
StartSessionInput.new({
session: "demo",
- captureScope: CaptureScope.Desktop,
}),
)
@@ -73,7 +71,13 @@ images, verification/error metadata, and `structuredJson` / `rawJson` for
platform-extensible results. Session lifecycle calls return dedicated generated
records.
-The agent cursor is session-owned. Its default theme and custom dotLottie
+`startSession` is optional for ordinary calls. The runtime creates one
+implicit session for this SDK transport and reuses it until shutdown, explicit
+end, or five minutes of inactivity. Use a named session when application code
+needs to configure or inspect that run explicitly.
+
+The agent cursor is session-owned and initializes on the first cursor-bearing
+action, including `moveCursor`. 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
diff --git a/libs/cua-driver/typescript/src/native/cua_driver_contract.ts b/libs/cua-driver/typescript/src/native/cua_driver_contract.ts
index ff50e94b3b..c95b948ea4 100644
--- a/libs/cua-driver/typescript/src/native/cua_driver_contract.ts
+++ b/libs/cua-driver/typescript/src/native/cua_driver_contract.ts
@@ -6,7 +6,7 @@
import nativeModule from "./cua_driver_contract-ffi.js";
import { type UniffiRustFutureContinuationCallback, type UniffiForeignFutureDroppedCallback, type UniffiForeignFutureDroppedCallbackStruct,
} from "./cua_driver_contract-ffi.js";
-import { type UniffiByteArray, AbstractFfiConverterByteArray, FfiConverterArray, FfiConverterBool, FfiConverterFloat64, FfiConverterInt32, FfiConverterInt64, FfiConverterOptional, FfiConverterUInt32, FfiConverterUInt64, FfiConverterUInt8, RustBuffer, UniffiEnum, UniffiInternalError, UniffiRustCaller, uniffiCreateFfiConverterString, uniffiCreateRecord,
+import { type UniffiByteArray, AbstractFfiConverterByteArray, FfiConverterArray, FfiConverterBool, FfiConverterFloat64, FfiConverterInt32, FfiConverterInt64, FfiConverterOptional, FfiConverterUInt32, FfiConverterUInt64, FfiConverterUInt8, RustBuffer, UniffiEnum, UniffiInternalError, UniffiRustCaller, uniffiCreateFfiConverterString, uniffiCreateRecord, uniffiTypeNameSymbol,
} from "@ubjs/core";
const uniffiCaller = new UniffiRustCaller(() => ({ code: 0 }));
@@ -470,6 +470,180 @@ const FfiConverterTypeBoundsExpectation = (() => {
return new FFIConverter();
})();
+const stringConverter = (() => {
+ const encoder = new TextEncoder();
+ const decoder = new TextDecoder();
+ return {
+ stringToBytes: (s: string) => encoder.encode(s),
+ bytesToString: (ab: UniffiByteArray) => decoder.decode(ab),
+ stringByteLength: (s: string) => encoder.encode(s).byteLength,
+ writeStringIntoBuffer: (s: string, buf: any, offset: number): number => {
+ const view = new Uint8Array(
+ buf.arrayBuffer,
+ offset,
+ buf.arrayBuffer.byteLength - offset,
+ );
+ return encoder.encodeInto(s, view).written;
+ },
+ readStringFromBuffer: (buf: any, offset: number, length: number): string =>
+ decoder.decode(new Uint8Array(buf.arrayBuffer, offset, length)),
+ };
+})();
+const FfiConverterString = uniffiCreateFfiConverterString(stringConverter);
+
+
+// Enum: ActionTarget
+export enum ActionTarget_Tags {
+ Window = "Window",
+ Desktop = "Desktop"
+}
+/**
+ * Exact capture/input target selected independently for each action.
+ *
+ * `display_id="primary"` is the portable desktop target in this release.
+ * Platforms that cannot address another display reject it explicitly rather
+ * than silently changing coordinate spaces.
+ */
+export const ActionTarget = (() => {
+
+ type Window__interface = {
+ tag: ActionTarget_Tags.Window;
+ inner:
+Readonly<{pid: number; windowId: bigint}>
+ };
+ class Window_ extends UniffiEnum implements Window__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "ActionTarget";
+ readonly tag = ActionTarget_Tags.Window;
+ readonly inner:
+Readonly<{pid: number; windowId: bigint}>;
+ constructor(
+inner: {pid: number; windowId: bigint }) {
+ super("ActionTarget", "Window");
+
+ this.inner = Object.freeze(inner);
+ }
+ static new(
+inner: {pid: number; windowId: bigint }): Window_ {
+ return new Window_(inner);
+ }
+
+ static instanceOf(obj: any): obj is Window_ {
+ return obj.tag === ActionTarget_Tags.Window;
+ }
+
+ }
+
+ type Desktop__interface = {
+ tag: ActionTarget_Tags.Desktop;
+ inner:
+Readonly<{displayId: string}>
+ };
+ class Desktop_ extends UniffiEnum implements Desktop__interface {
+ /**
+ * @private
+ * This field is private and should not be used, use `tag` instead.
+ */
+ readonly [uniffiTypeNameSymbol] = "ActionTarget";
+ readonly tag = ActionTarget_Tags.Desktop;
+ readonly inner:
+Readonly<{displayId: string}>;
+ constructor(
+inner: {displayId: string }) {
+ super("ActionTarget", "Desktop");
+
+ this.inner = Object.freeze(inner);
+ }
+ static new(
+inner: {displayId: string }): Desktop_ {
+ return new Desktop_(inner);
+ }
+
+ static instanceOf(obj: any): obj is Desktop_ {
+ return obj.tag === ActionTarget_Tags.Desktop;
+ }
+
+ }
+
+ function instanceOf(obj: any): obj is ActionTarget {
+ return obj[uniffiTypeNameSymbol] === "ActionTarget";
+ }
+
+ return Object.freeze({
+ instanceOf,
+ Window: Window_,
+ Desktop: Desktop_
+ });
+
+})();
+/**
+ * Exact capture/input target selected independently for each action.
+ *
+ * `display_id="primary"` is the portable desktop target in this release.
+ * Platforms that cannot address another display reject it explicitly rather
+ * than silently changing coordinate spaces.
+ */
+export type ActionTarget = InstanceType<
+ typeof ActionTarget['Window' | 'Desktop']
+>;
+
+// FfiConverter for enum ActionTarget
+const FfiConverterTypeActionTarget = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = ActionTarget;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return new ActionTarget.Window({pid: FfiConverterUInt32.read(from), windowId: FfiConverterUInt64.read(from) });
+ case 2: return new ActionTarget.Desktop({displayId: FfiConverterString.read(from) });
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value.tag) {
+ case ActionTarget_Tags.Window: {
+ ordinalConverter.write(1, into);
+ const inner = value.inner;
+ FfiConverterUInt32.write(inner.pid, into);
+ FfiConverterUInt64.write(inner.windowId, into);
+ return;
+ }
+ case ActionTarget_Tags.Desktop: {
+ ordinalConverter.write(2, into);
+ const inner = value.inner;
+ FfiConverterString.write(inner.displayId, into);
+ return;
+ }
+ default:
+ // Throwing from here means that ActionTarget_Tags hasn't matched an ordinal.
+ throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ allocationSize(value: TypeName): number {
+ switch (value.tag) {
+ case ActionTarget_Tags.Window: {
+ const inner = value.inner;
+ let size = ordinalConverter.allocationSize(1);
+ size += FfiConverterUInt32.allocationSize(inner.pid);
+ size += FfiConverterUInt64.allocationSize(inner.windowId);
+ return size;
+ }
+ case ActionTarget_Tags.Desktop: {
+ const inner = value.inner;
+ let size = ordinalConverter.allocationSize(2);
+ size += FfiConverterString.allocationSize(inner.displayId);
+ return size;
+ }
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ }
+ return new FFIConverter();
+})();
+
export enum DesktopScope {
Desktop
}
@@ -496,27 +670,6 @@ const FfiConverterTypeDesktopScope = (() => {
return new FFIConverter();
})();
-const stringConverter = (() => {
- const encoder = new TextEncoder();
- const decoder = new TextDecoder();
- return {
- stringToBytes: (s: string) => encoder.encode(s),
- bytesToString: (ab: UniffiByteArray) => decoder.decode(ab),
- stringByteLength: (s: string) => encoder.encode(s).byteLength,
- writeStringIntoBuffer: (s: string, buf: any, offset: number): number => {
- const view = new Uint8Array(
- buf.arrayBuffer,
- offset,
- buf.arrayBuffer.byteLength - offset,
- );
- return encoder.encodeInto(s, view).written;
- },
- readStringFromBuffer: (buf: any, offset: number, length: number): string =>
- decoder.decode(new Uint8Array(buf.arrayBuffer, offset, length)),
- };
-})();
-const FfiConverterString = uniffiCreateFfiConverterString(stringConverter);
-
export enum ClickButton {
Left,
Right,
@@ -552,7 +705,11 @@ const FfiConverterTypeClickButton = (() => {
export type ClickInput = {
x: number,
y: number,
- scope: DesktopScope,
+ target?: ActionTarget,
+ /**
+ * Deprecated flat desktop target retained for wire compatibility.
+ */
+ scope?: DesktopScope,
/**
* Optional session id.
*/
@@ -584,7 +741,8 @@ const FfiConverterTypeClickInput = (() => {
return {
x: FfiConverterFloat64.read(from),
y: FfiConverterFloat64.read(from),
- scope: FfiConverterTypeDesktopScope.read(from),
+ target: FfiConverterOptionalTypeActionTarget.read(from),
+ scope: FfiConverterOptionalTypeDesktopScope.read(from),
session: FfiConverterOptionalString.read(from),
button: FfiConverterOptionalTypeClickButton.read(from),
count: FfiConverterOptionalUInt32.read(from)
@@ -593,7 +751,8 @@ const FfiConverterTypeClickInput = (() => {
write(value: TypeName, into: RustBuffer): void {
FfiConverterFloat64.write(value.x, into);
FfiConverterFloat64.write(value.y, into);
- FfiConverterTypeDesktopScope.write(value.scope, into);
+ FfiConverterOptionalTypeActionTarget.write(value.target, into);
+ FfiConverterOptionalTypeDesktopScope.write(value.scope, into);
FfiConverterOptionalString.write(value.session, into);
FfiConverterOptionalTypeClickButton.write(value.button, into);
FfiConverterOptionalUInt32.write(value.count, into);
@@ -601,7 +760,8 @@ const FfiConverterTypeClickInput = (() => {
allocationSize(value: TypeName): number {
return FfiConverterFloat64.allocationSize(value.x) +
FfiConverterFloat64.allocationSize(value.y) +
- FfiConverterTypeDesktopScope.allocationSize(value.scope) +
+ FfiConverterOptionalTypeActionTarget.allocationSize(value.target) +
+ FfiConverterOptionalTypeDesktopScope.allocationSize(value.scope) +
FfiConverterOptionalString.allocationSize(value.session) +
FfiConverterOptionalTypeClickButton.allocationSize(value.button) +
FfiConverterOptionalUInt32.allocationSize(value.count);
@@ -1201,7 +1361,11 @@ export type DragInput = {
fromY: number,
toX: number,
toY: number,
- scope: DesktopScope,
+ target?: ActionTarget,
+ /**
+ * Deprecated flat desktop target retained for wire compatibility.
+ */
+ scope?: DesktopScope,
/**
* Optional session id.
*/
@@ -1237,7 +1401,8 @@ const FfiConverterTypeDragInput = (() => {
fromY: FfiConverterFloat64.read(from),
toX: FfiConverterFloat64.read(from),
toY: FfiConverterFloat64.read(from),
- scope: FfiConverterTypeDesktopScope.read(from),
+ target: FfiConverterOptionalTypeActionTarget.read(from),
+ scope: FfiConverterOptionalTypeDesktopScope.read(from),
session: FfiConverterOptionalString.read(from),
durationMs: FfiConverterOptionalUInt64.read(from),
steps: FfiConverterOptionalUInt64.read(from),
@@ -1250,7 +1415,8 @@ const FfiConverterTypeDragInput = (() => {
FfiConverterFloat64.write(value.fromY, into);
FfiConverterFloat64.write(value.toX, into);
FfiConverterFloat64.write(value.toY, into);
- FfiConverterTypeDesktopScope.write(value.scope, into);
+ FfiConverterOptionalTypeActionTarget.write(value.target, into);
+ FfiConverterOptionalTypeDesktopScope.write(value.scope, into);
FfiConverterOptionalString.write(value.session, into);
FfiConverterOptionalUInt64.write(value.durationMs, into);
FfiConverterOptionalUInt64.write(value.steps, into);
@@ -1262,7 +1428,8 @@ const FfiConverterTypeDragInput = (() => {
FfiConverterFloat64.allocationSize(value.fromY) +
FfiConverterFloat64.allocationSize(value.toX) +
FfiConverterFloat64.allocationSize(value.toY) +
- FfiConverterTypeDesktopScope.allocationSize(value.scope) +
+ FfiConverterOptionalTypeActionTarget.allocationSize(value.target) +
+ FfiConverterOptionalTypeDesktopScope.allocationSize(value.scope) +
FfiConverterOptionalString.allocationSize(value.session) +
FfiConverterOptionalUInt64.allocationSize(value.durationMs) +
FfiConverterOptionalUInt64.allocationSize(value.steps) +
@@ -1381,9 +1548,10 @@ const FfiConverterTypeElementPredicate = (() => {
export type EndSessionInput = {
/**
- * The session id to end.
+ * Optional public label to end. When omitted, end the caller's attached
+ * implicit session.
*/
- session: string
+ session?: string
}
/**
@@ -1407,14 +1575,14 @@ const FfiConverterTypeEndSessionInput = (() => {
class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
read(from: RustBuffer): TypeName {
return {
- session: FfiConverterString.read(from)
+ session: FfiConverterOptionalString.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
- FfiConverterString.write(value.session, into);
+ FfiConverterOptionalString.write(value.session, into);
}
allocationSize(value: TypeName): number {
- return FfiConverterString.allocationSize(value.session);
+ return FfiConverterOptionalString.allocationSize(value.session);
}
};
@@ -1786,8 +1954,55 @@ const FfiConverterTypeGetScreenSizeInput = (() => {
return new FFIConverter();
})();
+export type GetSessionInput = {
+ /**
+ * Optional public label. When omitted, inspect the caller's attached
+ * implicit session.
+ */
+ session?: string
+}
+
+/**
+ * Generated factory for {@link GetSessionInput} record objects.
+ */
+export const GetSessionInput = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<GetSessionInput, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<GetSessionInput>,
+ });
+})();
+
+const FfiConverterTypeGetSessionInput = (() => {
+ type TypeName = GetSessionInput;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ session: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterOptionalString.write(value.session, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterOptionalString.allocationSize(value.session);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export type GetSessionStateInput = {
- session: string
+ /**
+ * Optional public label. When omitted, inspect the caller's attached
+ * implicit session.
+ */
+ session?: string
}
/**
@@ -1811,14 +2026,14 @@ const FfiConverterTypeGetSessionStateInput = (() => {
class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
read(from: RustBuffer): TypeName {
return {
- session: FfiConverterString.read(from)
+ session: FfiConverterOptionalString.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
- FfiConverterString.write(value.session, into);
+ FfiConverterOptionalString.write(value.session, into);
}
allocationSize(value: TypeName): number {
- return FfiConverterString.allocationSize(value.session);
+ return FfiConverterOptionalString.allocationSize(value.session);
}
};
@@ -1827,7 +2042,11 @@ const FfiConverterTypeGetSessionStateInput = (() => {
export type HotkeyInput = {
keys: Array<string>,
- scope: DesktopScope,
+ target?: ActionTarget,
+ /**
+ * Deprecated flat desktop target retained for wire compatibility.
+ */
+ scope?: DesktopScope,
/**
* Optional session id.
*/
@@ -1856,18 +2075,21 @@ const FfiConverterTypeHotkeyInput = (() => {
read(from: RustBuffer): TypeName {
return {
keys: FfiConverterSequenceString.read(from),
- scope: FfiConverterTypeDesktopScope.read(from),
+ target: FfiConverterOptionalTypeActionTarget.read(from),
+ scope: FfiConverterOptionalTypeDesktopScope.read(from),
session: FfiConverterOptionalString.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
FfiConverterSequenceString.write(value.keys, into);
- FfiConverterTypeDesktopScope.write(value.scope, into);
+ FfiConverterOptionalTypeActionTarget.write(value.target, into);
+ FfiConverterOptionalTypeDesktopScope.write(value.scope, into);
FfiConverterOptionalString.write(value.session, into);
}
allocationSize(value: TypeName): number {
return FfiConverterSequenceString.allocationSize(value.keys) +
- FfiConverterTypeDesktopScope.allocationSize(value.scope) +
+ FfiConverterOptionalTypeActionTarget.allocationSize(value.target) +
+ FfiConverterOptionalTypeDesktopScope.allocationSize(value.scope) +
FfiConverterOptionalString.allocationSize(value.session);
}
@@ -1934,10 +2156,289 @@ const FfiConverterTypeInvokeMenuInput = (() => {
return new FFIConverter();
})();
+export type ListSessionsInput = {
+ /**
+ * Maximum number of content-free summaries to return (default 50, max
+ * 100). Ordinary agent transports are scoped to their own lease.
+ */
+ limit?: number,
+ /**
+ * Opaque continuation cursor returned by a previous call.
+ */
+ cursor?: string
+}
+
+/**
+ * Generated factory for {@link ListSessionsInput} record objects.
+ */
+export const ListSessionsInput = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<ListSessionsInput, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<ListSessionsInput>,
+ });
+})();
+
+const FfiConverterTypeListSessionsInput = (() => {
+ type TypeName = ListSessionsInput;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ limit: FfiConverterOptionalUInt32.read(from),
+ cursor: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterOptionalUInt32.write(value.limit, into);
+ FfiConverterOptionalString.write(value.cursor, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterOptionalUInt32.allocationSize(value.limit) +
+ FfiConverterOptionalString.allocationSize(value.cursor);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export enum SessionLifecycleState {
+ Active,
+ Ending
+}
+
+const FfiConverterTypeSessionLifecycleState = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = SessionLifecycleState;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return SessionLifecycleState.Active;
+ case 2: return SessionLifecycleState.Ending;
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value) {
+ case SessionLifecycleState.Active: return ordinalConverter.write(1, into);
+ case SessionLifecycleState.Ending: return ordinalConverter.write(2, into);
+ }
+ }
+ allocationSize(value: TypeName): number {
+ return ordinalConverter.allocationSize(0);
+ }
+ }
+ return new FFIConverter();
+})();
+
+export enum SessionClientKindOutput {
+ Cli,
+ Direct,
+ Mcp,
+ PythonSdk,
+ TypescriptSdk
+}
+
+const FfiConverterTypeSessionClientKindOutput = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = SessionClientKindOutput;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return SessionClientKindOutput.Cli;
+ case 2: return SessionClientKindOutput.Direct;
+ case 3: return SessionClientKindOutput.Mcp;
+ case 4: return SessionClientKindOutput.PythonSdk;
+ case 5: return SessionClientKindOutput.TypescriptSdk;
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value) {
+ case SessionClientKindOutput.Cli: return ordinalConverter.write(1, into);
+ case SessionClientKindOutput.Direct: return ordinalConverter.write(2, into);
+ case SessionClientKindOutput.Mcp: return ordinalConverter.write(3, into);
+ case SessionClientKindOutput.PythonSdk: return ordinalConverter.write(4, into);
+ case SessionClientKindOutput.TypescriptSdk: return ordinalConverter.write(5, into);
+ }
+ }
+ allocationSize(value: TypeName): number {
+ return ordinalConverter.allocationSize(0);
+ }
+ }
+ return new FFIConverter();
+})();
+
+export enum SessionTransportOutput {
+ Cli,
+ Daemon,
+ McpStdio,
+ McpHttp
+}
+
+const FfiConverterTypeSessionTransportOutput = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = SessionTransportOutput;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return SessionTransportOutput.Cli;
+ case 2: return SessionTransportOutput.Daemon;
+ case 3: return SessionTransportOutput.McpStdio;
+ case 4: return SessionTransportOutput.McpHttp;
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value) {
+ case SessionTransportOutput.Cli: return ordinalConverter.write(1, into);
+ case SessionTransportOutput.Daemon: return ordinalConverter.write(2, into);
+ case SessionTransportOutput.McpStdio: return ordinalConverter.write(3, into);
+ case SessionTransportOutput.McpHttp: return ordinalConverter.write(4, into);
+ }
+ }
+ allocationSize(value: TypeName): number {
+ return ordinalConverter.allocationSize(0);
+ }
+ }
+ return new FFIConverter();
+})();
+
+/**
+ * Content-free lifecycle state safe for an ordinary agent transport.
+ */
+export type SessionOutput = {
+ /**
+ * Sanitized public label, or null for an unnamed implicit session.
+ */
+ session?: string,
+ implicit: boolean,
+ state: SessionLifecycleState,
+ clientKind: SessionClientKindOutput,
+ transport: SessionTransportOutput,
+ cursorVisible: boolean,
+ recordingActive: boolean,
+ idleSeconds: bigint,
+ expiresInSeconds: bigint
+}
+
+/**
+ * Generated factory for {@link SessionOutput} record objects.
+ */
+export const SessionOutput = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<SessionOutput, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<SessionOutput>,
+ });
+})();
+
+const FfiConverterTypeSessionOutput = (() => {
+ type TypeName = SessionOutput;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ session: FfiConverterOptionalString.read(from),
+ implicit: FfiConverterBool.read(from),
+ state: FfiConverterTypeSessionLifecycleState.read(from),
+ clientKind: FfiConverterTypeSessionClientKindOutput.read(from),
+ transport: FfiConverterTypeSessionTransportOutput.read(from),
+ cursorVisible: FfiConverterBool.read(from),
+ recordingActive: FfiConverterBool.read(from),
+ idleSeconds: FfiConverterUInt64.read(from),
+ expiresInSeconds: FfiConverterUInt64.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterOptionalString.write(value.session, into);
+ FfiConverterBool.write(value.implicit, into);
+ FfiConverterTypeSessionLifecycleState.write(value.state, into);
+ FfiConverterTypeSessionClientKindOutput.write(value.clientKind, into);
+ FfiConverterTypeSessionTransportOutput.write(value.transport, into);
+ FfiConverterBool.write(value.cursorVisible, into);
+ FfiConverterBool.write(value.recordingActive, into);
+ FfiConverterUInt64.write(value.idleSeconds, into);
+ FfiConverterUInt64.write(value.expiresInSeconds, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterOptionalString.allocationSize(value.session) +
+ FfiConverterBool.allocationSize(value.implicit) +
+ FfiConverterTypeSessionLifecycleState.allocationSize(value.state) +
+ FfiConverterTypeSessionClientKindOutput.allocationSize(value.clientKind) +
+ FfiConverterTypeSessionTransportOutput.allocationSize(value.transport) +
+ FfiConverterBool.allocationSize(value.cursorVisible) +
+ FfiConverterBool.allocationSize(value.recordingActive) +
+ FfiConverterUInt64.allocationSize(value.idleSeconds) +
+ FfiConverterUInt64.allocationSize(value.expiresInSeconds);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export type ListSessionsOutput = {
+ sessions: Array<SessionOutput>,
+ nextCursor?: string
+}
+
+/**
+ * Generated factory for {@link ListSessionsOutput} record objects.
+ */
+export const ListSessionsOutput = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<ListSessionsOutput, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<ListSessionsOutput>,
+ });
+})();
+
+const FfiConverterTypeListSessionsOutput = (() => {
+ type TypeName = ListSessionsOutput;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ sessions: FfiConverterSequenceTypeSessionOutput.read(from),
+ nextCursor: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterSequenceTypeSessionOutput.write(value.sessions, into);
+ FfiConverterOptionalString.write(value.nextCursor, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterSequenceTypeSessionOutput.allocationSize(value.sessions) +
+ FfiConverterOptionalString.allocationSize(value.nextCursor);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export type MoveCursorInput = {
x: number,
y: number,
- scope: DesktopScope,
+ /**
+ * Preferred per-call target. New callers should set this field.
+ */
+ target?: ActionTarget,
+ /**
+ * Deprecated flat desktop target retained for wire compatibility.
+ */
+ scope?: DesktopScope,
/**
* Optional session id.
*/
@@ -1967,20 +2468,23 @@ const FfiConverterTypeMoveCursorInput = (() => {
return {
x: FfiConverterFloat64.read(from),
y: FfiConverterFloat64.read(from),
- scope: FfiConverterTypeDesktopScope.read(from),
+ target: FfiConverterOptionalTypeActionTarget.read(from),
+ scope: FfiConverterOptionalTypeDesktopScope.read(from),
session: FfiConverterOptionalString.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
FfiConverterFloat64.write(value.x, into);
FfiConverterFloat64.write(value.y, into);
- FfiConverterTypeDesktopScope.write(value.scope, into);
+ FfiConverterOptionalTypeActionTarget.write(value.target, into);
+ FfiConverterOptionalTypeDesktopScope.write(value.scope, into);
FfiConverterOptionalString.write(value.session, into);
}
allocationSize(value: TypeName): number {
return FfiConverterFloat64.allocationSize(value.x) +
FfiConverterFloat64.allocationSize(value.y) +
- FfiConverterTypeDesktopScope.allocationSize(value.scope) +
+ FfiConverterOptionalTypeActionTarget.allocationSize(value.target) +
+ FfiConverterOptionalTypeDesktopScope.allocationSize(value.scope) +
FfiConverterOptionalString.allocationSize(value.session);
}
@@ -2120,7 +2624,11 @@ const FfiConverterTypePredicateOutcome = (() => {
export type PressKeyInput = {
key: string,
- scope: DesktopScope,
+ target?: ActionTarget,
+ /**
+ * Deprecated flat desktop target retained for wire compatibility.
+ */
+ scope?: DesktopScope,
/**
* Optional session id.
*/
@@ -2150,20 +2658,23 @@ const FfiConverterTypePressKeyInput = (() => {
read(from: RustBuffer): TypeName {
return {
key: FfiConverterString.read(from),
- scope: FfiConverterTypeDesktopScope.read(from),
+ target: FfiConverterOptionalTypeActionTarget.read(from),
+ scope: FfiConverterOptionalTypeDesktopScope.read(from),
session: FfiConverterOptionalString.read(from),
modifiers: FfiConverterOptionalSequenceString.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
FfiConverterString.write(value.key, into);
- FfiConverterTypeDesktopScope.write(value.scope, into);
+ FfiConverterOptionalTypeActionTarget.write(value.target, into);
+ FfiConverterOptionalTypeDesktopScope.write(value.scope, into);
FfiConverterOptionalString.write(value.session, into);
FfiConverterOptionalSequenceString.write(value.modifiers, into);
}
allocationSize(value: TypeName): number {
return FfiConverterString.allocationSize(value.key) +
- FfiConverterTypeDesktopScope.allocationSize(value.scope) +
+ FfiConverterOptionalTypeActionTarget.allocationSize(value.target) +
+ FfiConverterOptionalTypeDesktopScope.allocationSize(value.scope) +
FfiConverterOptionalString.allocationSize(value.session) +
FfiConverterOptionalSequenceString.allocationSize(value.modifiers);
@@ -2240,7 +2751,11 @@ export type ScrollInput = {
x: number,
y: number,
direction: ScrollDirection,
- scope: DesktopScope,
+ target?: ActionTarget,
+ /**
+ * Deprecated flat desktop target retained for wire compatibility.
+ */
+ scope?: DesktopScope,
/**
* Optional session id.
*/
@@ -2273,7 +2788,8 @@ const FfiConverterTypeScrollInput = (() => {
x: FfiConverterFloat64.read(from),
y: FfiConverterFloat64.read(from),
direction: FfiConverterTypeScrollDirection.read(from),
- scope: FfiConverterTypeDesktopScope.read(from),
+ target: FfiConverterOptionalTypeActionTarget.read(from),
+ scope: FfiConverterOptionalTypeDesktopScope.read(from),
session: FfiConverterOptionalString.read(from),
by: FfiConverterOptionalTypeScrollBy.read(from),
amount: FfiConverterOptionalUInt64.read(from)
@@ -2283,7 +2799,8 @@ const FfiConverterTypeScrollInput = (() => {
FfiConverterFloat64.write(value.x, into);
FfiConverterFloat64.write(value.y, into);
FfiConverterTypeScrollDirection.write(value.direction, into);
- FfiConverterTypeDesktopScope.write(value.scope, into);
+ FfiConverterOptionalTypeActionTarget.write(value.target, into);
+ FfiConverterOptionalTypeDesktopScope.write(value.scope, into);
FfiConverterOptionalString.write(value.session, into);
FfiConverterOptionalTypeScrollBy.write(value.by, into);
FfiConverterOptionalUInt64.write(value.amount, into);
@@ -2292,7 +2809,8 @@ const FfiConverterTypeScrollInput = (() => {
return FfiConverterFloat64.allocationSize(value.x) +
FfiConverterFloat64.allocationSize(value.y) +
FfiConverterTypeScrollDirection.allocationSize(value.direction) +
- FfiConverterTypeDesktopScope.allocationSize(value.scope) +
+ FfiConverterOptionalTypeActionTarget.allocationSize(value.target) +
+ FfiConverterOptionalTypeDesktopScope.allocationSize(value.scope) +
FfiConverterOptionalString.allocationSize(value.session) +
FfiConverterOptionalTypeScrollBy.allocationSize(value.by) +
FfiConverterOptionalUInt64.allocationSize(value.amount);
@@ -2787,11 +3305,14 @@ const FfiConverterTypeSetWindowFrameInput = (() => {
export type StartSessionInput = {
/**
- * Stable session id for this run (e.g. "research-run-1").
+ * Optional stable public label for this run (e.g. "research-run-1").
+ * When omitted, the authenticated transport lease's implicit session is
+ * created or returned.
*/
- session: string,
+ session?: string,
/**
- * Per-session perception/action modality. auto starts window-only and requires explicit escalation before desktop tools; escalation permanently switches that session to desktop scope. To recover window scope, call end_session, then start_session with a new session id. window and desktop are strict. Immutable for the live session.
+ * Deprecated compatibility policy. New callers select window or desktop
+ * modality on each action instead of storing it on the session.
*/
captureScope?: CaptureScope,
/**
@@ -2822,18 +3343,18 @@ const FfiConverterTypeStartSessionInput = (() => {
class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
read(from: RustBuffer): TypeName {
return {
- session: FfiConverterString.read(from),
+ session: FfiConverterOptionalString.read(from),
captureScope: FfiConverterOptionalTypeCaptureScope.read(from),
cursorTheme: FfiConverterOptionalTypeCursorThemeSelection.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
- FfiConverterString.write(value.session, into);
+ FfiConverterOptionalString.write(value.session, into);
FfiConverterOptionalTypeCaptureScope.write(value.captureScope, into);
FfiConverterOptionalTypeCursorThemeSelection.write(value.cursorTheme, into);
}
allocationSize(value: TypeName): number {
- return FfiConverterString.allocationSize(value.session) +
+ return FfiConverterOptionalString.allocationSize(value.session) +
FfiConverterOptionalTypeCaptureScope.allocationSize(value.captureScope) +
FfiConverterOptionalTypeCursorThemeSelection.allocationSize(value.cursorTheme);
@@ -2980,7 +3501,11 @@ const FfiConverterTypeStatePredicate = (() => {
export type TypeTextInput = {
text: string,
- scope: DesktopScope,
+ target?: ActionTarget,
+ /**
+ * Deprecated flat desktop target retained for wire compatibility.
+ */
+ scope?: DesktopScope,
/**
* Optional session id.
*/
@@ -3009,18 +3534,21 @@ const FfiConverterTypeTypeTextInput = (() => {
read(from: RustBuffer): TypeName {
return {
text: FfiConverterString.read(from),
- scope: FfiConverterTypeDesktopScope.read(from),
+ target: FfiConverterOptionalTypeActionTarget.read(from),
+ scope: FfiConverterOptionalTypeDesktopScope.read(from),
session: FfiConverterOptionalString.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
FfiConverterString.write(value.text, into);
- FfiConverterTypeDesktopScope.write(value.scope, into);
+ FfiConverterOptionalTypeActionTarget.write(value.target, into);
+ FfiConverterOptionalTypeDesktopScope.write(value.scope, into);
FfiConverterOptionalString.write(value.session, into);
}
allocationSize(value: TypeName): number {
return FfiConverterString.allocationSize(value.text) +
- FfiConverterTypeDesktopScope.allocationSize(value.scope) +
+ FfiConverterOptionalTypeActionTarget.allocationSize(value.target) +
+ FfiConverterOptionalTypeDesktopScope.allocationSize(value.scope) +
FfiConverterOptionalString.allocationSize(value.session);
}
@@ -3042,7 +3570,8 @@ export type VerifyStateInput = {
*/
expect: Array<StatePredicate>,
/**
- * Optional session id for capture-scope and authorization continuity.
+ * Optional public session label for lifecycle continuity. It never selects
+ * capture modality or authorization.
*/
session?: string,
/**
@@ -3218,6 +3747,12 @@ const FfiConverterOptionalTypeActionEscalation = new FfiConverterOptional(FfiCon
// FfiConverter for number | undefined
const FfiConverterOptionalFloat64 = new FfiConverterOptional(FfiConverterFloat64);
+// FfiConverter for ActionTarget | undefined
+const FfiConverterOptionalTypeActionTarget = new FfiConverterOptional(FfiConverterTypeActionTarget);
+
+// FfiConverter for DesktopScope | undefined
+const FfiConverterOptionalTypeDesktopScope = new FfiConverterOptional(FfiConverterTypeDesktopScope);
+
// FfiConverter for string | undefined
const FfiConverterOptionalString = new FfiConverterOptional(FfiConverterString);
@@ -3239,6 +3774,9 @@ const FfiConverterOptionalBoolean = new FfiConverterOptional(FfiConverterBool);
// FfiConverter for CursorPointOutput | undefined
const FfiConverterOptionalTypeCursorPointOutput = new FfiConverterOptional(FfiConverterTypeCursorPointOutput);
+// FfiConverter for Array<SessionOutput>
+const FfiConverterSequenceTypeSessionOutput = new FfiConverterArray(FfiConverterTypeSessionOutput);
+
// FfiConverter for UnknownReason | undefined
const FfiConverterOptionalTypeUnknownReason = new FfiConverterOptional(FfiConverterTypeUnknownReason);
@@ -3304,6 +3842,7 @@ export default Object.freeze({
FfiConverterTypeActionEvidenceKind,
FfiConverterTypeActionResult,
FfiConverterTypeActionRoute,
+ FfiConverterTypeActionTarget,
FfiConverterTypeBoundsExpectation,
FfiConverterTypeCaptureScope,
FfiConverterTypeClickButton,
@@ -3333,9 +3872,12 @@ export default Object.freeze({
FfiConverterTypeGetCursorPositionInput,
FfiConverterTypeGetDesktopStateInput,
FfiConverterTypeGetScreenSizeInput,
+ FfiConverterTypeGetSessionInput,
FfiConverterTypeGetSessionStateInput,
FfiConverterTypeHotkeyInput,
FfiConverterTypeInvokeMenuInput,
+ FfiConverterTypeListSessionsInput,
+ FfiConverterTypeListSessionsOutput,
FfiConverterTypeMoveCursorInput,
FfiConverterTypePlatform,
FfiConverterTypePredicateOutcome,
@@ -3343,7 +3885,11 @@ export default Object.freeze({
FfiConverterTypeScrollBy,
FfiConverterTypeScrollDirection,
FfiConverterTypeScrollInput,
+ FfiConverterTypeSessionClientKindOutput,
+ FfiConverterTypeSessionLifecycleState,
+ FfiConverterTypeSessionOutput,
FfiConverterTypeSessionStateOutput,
+ FfiConverterTypeSessionTransportOutput,
FfiConverterTypeSetAgentCursorEnabledInput,
FfiConverterTypeSetAgentCursorEnabledOutput,
FfiConverterTypeSetAgentCursorMotionInput,
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 32cc75651f..b755bb57ec 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
@@ -473,6 +473,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_fn_method_cuadriver_get_session": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_fn_method_cuadriver_get_session_state": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -493,6 +498,16 @@ const DEFINITIONS = {
ret: FfiType.Int8,
hasRustCallStatus: true,
},
+ "uniffi_cua_driver_sdk_fn_method_cuadriver_list_host_sessions_json": {
+ args: [FfiType.Handle],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_fn_method_cuadriver_list_sessions": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_fn_method_cuadriver_list_tools_json": {
args: [FfiType.Handle],
ret: FfiType.Handle,
@@ -628,6 +643,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_get_session": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_fn_method_cuadriversession_get_session_state": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -643,6 +663,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_list_sessions": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_fn_method_cuadriversession_move_cursor": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -898,6 +923,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_checksum_method_cuadriver_get_session": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_checksum_method_cuadriver_get_session_state": {
args: [],
ret: FfiType.UInt16,
@@ -918,6 +948,16 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_checksum_method_cuadriver_list_host_sessions_json": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_driver_sdk_checksum_method_cuadriver_list_sessions": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json": {
args: [],
ret: FfiType.UInt16,
@@ -1053,6 +1093,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session_state": {
args: [],
ret: FfiType.UInt16,
@@ -1068,6 +1113,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_list_sessions": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor": {
args: [],
ret: FfiType.UInt16,
@@ -1331,10 +1381,13 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_fn_method_cuadriver_get_cursor_position(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriver_get_desktop_state(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriver_get_screen_size(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriver_get_session(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriver_get_session_state(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriver_hotkey(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriver_invoke_menu(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriver_is_available(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): number;
+ uniffi_cua_driver_sdk_fn_method_cuadriver_list_host_sessions_json(uniffiSelf: bigint): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriver_list_sessions(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriver_list_tools_json(uniffiSelf: bigint): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriver_metadata(uniffiSelf: bigint): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriver_move_cursor(uniffiSelf: bigint, input: Uint8Array): bigint;
@@ -1362,9 +1415,11 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_fn_method_cuadriversession_get_cursor_position(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriversession_get_desktop_state(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriversession_get_screen_size(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_get_session(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriversession_get_session_state(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriversession_hotkey(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriversession_invoke_menu(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_list_sessions(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriversession_move_cursor(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriversession_press_key(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriversession_scroll(uniffiSelf: bigint, input: Uint8Array): bigint;
@@ -1416,10 +1471,13 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_checksum_method_cuadriver_get_cursor_position(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_get_desktop_state(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_get_screen_size(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriver_get_session(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_get_session_state(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_hotkey(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_invoke_menu(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_is_available(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriver_list_host_sessions_json(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriver_list_sessions(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_metadata(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_move_cursor(): number;
@@ -1447,9 +1505,11 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_cursor_position(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_desktop_state(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_screen_size(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session_state(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriversession_hotkey(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriversession_invoke_menu(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_list_sessions(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriversession_press_key(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriversession_scroll(): number;
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 14f851059d..0dda3d795e 100644
--- a/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
+++ b/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
@@ -6,12 +6,12 @@
import nativeModule from "./cua_driver_sdk-ffi.js";
import { type UniffiRustFutureContinuationCallback, type UniffiForeignFutureDroppedCallback, type UniffiForeignFutureDroppedCallbackStruct, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverActivityObserver, type UniffiForeignFutureResultRustBuffer, type UniffiForeignFutureCompleterustBuffer, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost,
} from "./cua_driver_sdk-ffi.js";
-import { type ActionResult, type ClickInput, type ClipboardReadInput, type ClipboardWriteInput, type DragInput, type EndSessionInput, type EndSessionOutput, type EscalateSessionInput, type GetAgentCursorStateInput, type GetCursorPositionInput, type GetDesktopStateInput, type GetScreenSizeInput, type GetSessionStateInput, type HotkeyInput, type InvokeMenuInput, type MoveCursorInput, type PressKeyInput, type ScrollInput, type SessionStateOutput, type SetAgentCursorEnabledInput, type SetAgentCursorMotionInput, type SetAgentCursorThemeInput, type SetWindowFrameInput, type StartSessionInput, type StartSessionOutput, type TypeTextInput, type VerifyStateInput, type VerifyStateOutput,
+import { type ActionResult, type ClickInput, type ClipboardReadInput, type ClipboardWriteInput, type DragInput, type EndSessionInput, type EndSessionOutput, type EscalateSessionInput, type GetAgentCursorStateInput, type GetCursorPositionInput, type GetDesktopStateInput, type GetScreenSizeInput, type GetSessionInput, type GetSessionStateInput, type HotkeyInput, type InvokeMenuInput, type ListSessionsInput, type ListSessionsOutput, type MoveCursorInput, type PressKeyInput, type ScrollInput, type SessionOutput, type SessionStateOutput, type SetAgentCursorEnabledInput, type SetAgentCursorMotionInput, type SetAgentCursorThemeInput, type SetWindowFrameInput, type StartSessionInput, type StartSessionOutput, type TypeTextInput, type VerifyStateInput, type VerifyStateOutput,
} 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, uniffiTraitInterfaceCall, uniffiTraitInterfaceCallAsyncWithError, uniffiTypeNameSymbol, variantOrdinalSymbol,
} from "@ubjs/core";
import uniffiCuaDriverContractModule from "./cua_driver_contract.js";
-const { FfiConverterTypeActionResult, FfiConverterTypeClickInput, FfiConverterTypeClipboardReadInput, FfiConverterTypeClipboardWriteInput, FfiConverterTypeDragInput, FfiConverterTypeEndSessionInput, FfiConverterTypeEndSessionOutput, FfiConverterTypeEscalateSessionInput, FfiConverterTypeGetAgentCursorStateInput, FfiConverterTypeGetCursorPositionInput, FfiConverterTypeGetDesktopStateInput, FfiConverterTypeGetScreenSizeInput, FfiConverterTypeGetSessionStateInput, FfiConverterTypeHotkeyInput, FfiConverterTypeInvokeMenuInput, FfiConverterTypeMoveCursorInput, FfiConverterTypePressKeyInput, FfiConverterTypeScrollInput, FfiConverterTypeSessionStateOutput, FfiConverterTypeSetAgentCursorEnabledInput, FfiConverterTypeSetAgentCursorMotionInput, FfiConverterTypeSetAgentCursorThemeInput, FfiConverterTypeSetWindowFrameInput, FfiConverterTypeStartSessionInput, FfiConverterTypeStartSessionOutput, FfiConverterTypeTypeTextInput, FfiConverterTypeVerifyStateInput, FfiConverterTypeVerifyStateOutput } = uniffiCuaDriverContractModule.converters;
+const { FfiConverterTypeActionResult, FfiConverterTypeClickInput, FfiConverterTypeClipboardReadInput, FfiConverterTypeClipboardWriteInput, FfiConverterTypeDragInput, FfiConverterTypeEndSessionInput, FfiConverterTypeEndSessionOutput, FfiConverterTypeEscalateSessionInput, FfiConverterTypeGetAgentCursorStateInput, FfiConverterTypeGetCursorPositionInput, FfiConverterTypeGetDesktopStateInput, FfiConverterTypeGetScreenSizeInput, FfiConverterTypeGetSessionInput, FfiConverterTypeGetSessionStateInput, FfiConverterTypeHotkeyInput, FfiConverterTypeInvokeMenuInput, FfiConverterTypeListSessionsInput, FfiConverterTypeListSessionsOutput, FfiConverterTypeMoveCursorInput, FfiConverterTypePressKeyInput, FfiConverterTypeScrollInput, FfiConverterTypeSessionOutput, FfiConverterTypeSessionStateOutput, FfiConverterTypeSetAgentCursorEnabledInput, FfiConverterTypeSetAgentCursorMotionInput, FfiConverterTypeSetAgentCursorThemeInput, FfiConverterTypeSetWindowFrameInput, FfiConverterTypeStartSessionInput, FfiConverterTypeStartSessionOutput, FfiConverterTypeTypeTextInput, FfiConverterTypeVerifyStateInput, FfiConverterTypeVerifyStateOutput } = uniffiCuaDriverContractModule.converters;
const uniffiCaller = new UniffiRustCaller(() => ({ code: 0 }));
const uniffiIsDebug =
@@ -2547,10 +2547,18 @@ export interface CuaDriverLike {
getCursorPosition(input: GetCursorPositionInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
getDesktopState(input: GetDesktopStateInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
getScreenSize(input: GetScreenSizeInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
+ getSession(input: GetSessionInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SessionOutput>;
getSessionState(input: GetSessionStateInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SessionStateOutput>;
hotkey(input: HotkeyInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
invokeMenu(input: InvokeMenuInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
isAvailable(): boolean;
+/**
+ * Content-free lifecycle summaries for the trusted host's runtime or
+ * host-lease namespace. This is deliberately separate from the
+ * agent-facing `list_sessions` tool, whose view is transport scoped.
+ */
+ listHostSessionsJson(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;
+ listSessions(input: ListSessionsInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ListSessionsOutput>;
/**
* Canonical tool inventory for MCP and other protocol adapters.
*/
@@ -3216,6 +3224,38 @@ private constructor(pointer: UniffiHandle) {
}
}
+ async getSession(input: GetSessionInput, asyncOpts_?: { signal: AbortSignal }): Promise<SessionOutput> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_get_session(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeGetSessionInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSessionOutput.lift.bind(FfiConverterTypeSessionOutput),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
async getSessionState(input: GetSessionStateInput, asyncOpts_?: { signal: AbortSignal }): Promise<SessionStateOutput> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
@@ -3323,6 +3363,75 @@ private constructor(pointer: UniffiHandle) {
));
}
+/**
+ * Content-free lifecycle summaries for the trusted host's runtime or
+ * host-lease namespace. This is deliberately separate from the
+ * agent-facing `list_sessions` tool, whose view is transport scoped.
+ */
+ async listHostSessionsJson(asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_list_host_sessions_json(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
+ async listSessions(input: ListSessionsInput, asyncOpts_?: { signal: AbortSignal }): Promise<ListSessionsOutput> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_list_sessions(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeListSessionsInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeListSessionsOutput.lift.bind(FfiConverterTypeListSessionsOutput),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
/**
* Canonical tool inventory for MCP and other protocol adapters.
*/
@@ -3879,9 +3988,11 @@ export interface CuaDriverSessionLike {
getCursorPosition(input: GetCursorPositionInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
getDesktopState(input: GetDesktopStateInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
getScreenSize(input: GetScreenSizeInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
+ getSession(input: GetSessionInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SessionOutput>;
getSessionState(input: GetSessionStateInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<SessionStateOutput>;
hotkey(input: HotkeyInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
invokeMenu(input: InvokeMenuInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
+ listSessions(input: ListSessionsInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ListSessionsOutput>;
moveCursor(input: MoveCursorInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
pressKey(input: PressKeyInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
scroll(input: ScrollInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
@@ -4281,6 +4392,38 @@ private constructor(pointer: UniffiHandle) {
}
}
+ async getSession(input: GetSessionInput, asyncOpts_?: { signal: AbortSignal }): Promise<SessionOutput> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_get_session(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypeGetSessionInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeSessionOutput.lift.bind(FfiConverterTypeSessionOutput),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
async getSessionState(input: GetSessionStateInput, asyncOpts_?: { signal: AbortSignal }): Promise<SessionStateOutput> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
@@ -4377,6 +4520,38 @@ private constructor(pointer: UniffiHandle) {
}
}
+ async listSessions(input: ListSessionsInput, asyncOpts_?: { signal: AbortSignal }): Promise<ListSessionsOutput> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_list_sessions(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypeListSessionsInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeListSessionsOutput.lift.bind(FfiConverterTypeListSessionsOutput),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
async moveCursor(input: MoveCursorInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
@@ -5593,6 +5768,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_get_screen_size() !== 55616) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_get_screen_size");
}
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_get_session() !== 17834) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_get_session");
+ }
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_get_session_state() !== 49966) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_get_session_state");
}
@@ -5605,6 +5783,12 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_is_available() !== 42961) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_is_available");
}
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_list_host_sessions_json() !== 13193) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_list_host_sessions_json");
+ }
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_list_sessions() !== 40131) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_list_sessions");
+ }
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json() !== 33039) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_list_tools_json");
}
@@ -5686,6 +5870,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_screen_size() !== 9763) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_screen_size");
}
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session() !== 54666) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session");
+ }
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session_state() !== 55370) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_get_session_state");
}
@@ -5695,6 +5882,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_invoke_menu() !== 2742) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_invoke_menu");
}
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_list_sessions() !== 32840) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_list_sessions");
+ }
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor() !== 35768) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor");
}
diff --git a/libs/cua-driver/typescript/test/electron-main-fixture.mjs b/libs/cua-driver/typescript/test/electron-main-fixture.mjs
index dad16d5711..76a85e2575 100644
--- a/libs/cua-driver/typescript/test/electron-main-fixture.mjs
+++ b/libs/cua-driver/typescript/test/electron-main-fixture.mjs
@@ -27,7 +27,7 @@ const server = net.createServer(socket => {
const request = JSON.parse(buffer.split("\\n", 1)[0]);
const result = request.method === "metadata" ? {
driver_version: ${JSON.stringify(packageVersion)},
- contract_version: hostBundleId.endsWith(".failure") ? "incompatible" : "0.6.0",
+ contract_version: hostBundleId.endsWith(".failure") ? "incompatible" : "0.7.0",
tools_list_schema_version: "1",
capability_version: "1",
mcp_protocol_version: "2025-06-18",
diff --git a/libs/cua-driver/typescript/test/native-daemon-fixture.mjs b/libs/cua-driver/typescript/test/native-daemon-fixture.mjs
index a403c2c020..b127599ba7 100644
--- a/libs/cua-driver/typescript/test/native-daemon-fixture.mjs
+++ b/libs/cua-driver/typescript/test/native-daemon-fixture.mjs
@@ -18,7 +18,7 @@ const server = net.createServer((connection) => {
ok: true,
result: {
driver_version: "0.12.6",
- contract_version: "0.6.0",
+ contract_version: "0.7.0",
tools_list_schema_version: "1",
capability_version: "1",
mcp_protocol_version: "2025-06-18",
diff --git a/libs/cua-driver/typescript/test/native-loader.test.mjs b/libs/cua-driver/typescript/test/native-loader.test.mjs
index 7ffdf54f22..5557fd316b 100644
--- a/libs/cua-driver/typescript/test/native-loader.test.mjs
+++ b/libs/cua-driver/typescript/test/native-loader.test.mjs
@@ -53,7 +53,7 @@ const server = net.createServer(socket => {
const request = JSON.parse(buffer.split("\\n", 1)[0]);
const result = request.method === "metadata" ? {
driver_version: "0.10.0",
- contract_version: "0.6.0",
+ contract_version: "0.7.0",
tools_list_schema_version: "1",
capability_version: "1",
mcp_protocol_version: "2025-06-18",
@@ -148,6 +148,8 @@ test(
const expectedMethods = [
"startSession",
"escalateSession",
+ "getSession",
+ "listSessions",
"getSessionState",
"endSession",
"getDesktopState",
diff --git a/scripts/docs-generators/cua-driver.ts b/scripts/docs-generators/cua-driver.ts
index a7b5649825..20b4501486 100644
--- a/scripts/docs-generators/cua-driver.ts
+++ b/scripts/docs-generators/cua-driver.ts
@@ -73,10 +73,14 @@ export interface MCPInputSchema {
}
export interface MCPPropertyDoc {
- type: string | string[];
- description: string;
+ type?: string | string[];
+ description?: string;
items?: { type: string };
enum?: string[];
+ const?: unknown;
+ anyOf?: MCPPropertyDoc[];
+ oneOf?: MCPPropertyDoc[];
+ properties?: Record<string, MCPPropertyDoc>;
minItems?: number;
maxItems?: number;
minimum?: number;
@@ -726,7 +730,7 @@ export function generateMCPToolDoc(tool: MCPToolDoc): string[] {
const isRequired = required.has(propName);
const requiredLabel = isRequired ? 'required' : 'optional';
const typeLabel = formatPropertyType(prop);
- const description = escapeMdxText(prop.description ?? '');
+ const description = escapeMdxText(propertyDescription(prop));
const details: string[] = [];
if (prop.default !== undefined) details.push(`default: \`${JSON.stringify(prop.default)}\``);
if (prop.minimum !== undefined || prop.maximum !== undefined) {
@@ -785,11 +789,37 @@ function escapeMdxText(value: string): string {
}
function formatPropertyType(prop: MCPPropertyDoc): string {
+ const alternatives = prop.anyOf ?? prop.oneOf;
+ if (alternatives?.length) {
+ const labels = alternatives
+ .filter((alternative) => alternative.type !== 'null')
+ .flatMap((alternative) => {
+ if (alternative.oneOf?.length) {
+ return alternative.oneOf.map(discriminatedObjectLabel);
+ }
+ return [discriminatedObjectLabel(alternative)];
+ });
+ if (labels.length > 0) return [...new Set(labels)].join(' or ');
+ }
if (prop.type === 'array') {
const itemType = prop.items?.type ?? 'unknown';
return `array of ${itemType}`;
}
- return Array.isArray(prop.type) ? prop.type.join(' or ') : prop.type;
+ return Array.isArray(prop.type) ? prop.type.join(' or ') : (prop.type ?? 'unknown');
+}
+
+function discriminatedObjectLabel(schema: MCPPropertyDoc): string {
+ const kind = schema.properties?.kind?.const;
+ return typeof kind === 'string' ? `${kind} target` : (schema.type ?? 'object');
+}
+
+function propertyDescription(prop: MCPPropertyDoc): string {
+ if (prop.description) return prop.description;
+ for (const alternative of prop.anyOf ?? prop.oneOf ?? []) {
+ const nested = propertyDescription(alternative);
+ if (nested) return nested;
+ }
+ return '';
}
function syntheticExampleValue(name: string, prop: MCPPropertyDoc): unknown {