Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(cua-driver-rs): caller-declared session identity + Streamable-HTTP transport for multi-agent parallelism (#1798)
Francesco Bonaccie1e8c98208f6
diff --git a/docs/content/docs/cua-driver/guide/getting-started/faq.mdx b/docs/content/docs/cua-driver/guide/getting-started/faq.mdxindex 0470edd21b..d857bdc490 100644--- a/docs/content/docs/cua-driver/guide/getting-started/faq.mdx+++ b/docs/content/docs/cua-driver/guide/getting-started/faq.mdx@@ -154,6 +154,29 @@ cua-driver call set_agent_cursor_motion '{"glide_duration_ms":300}'See `set_agent_cursor_motion` in the [MCP tools reference](/cua-driver/reference/mcp-tools) for every knob.+## Concurrency & multiple agents++### Two agents (or subagents) take turns instead of running in parallel. Why?++The daemon is concurrent — it handles each connection on its own task, and proves it: two raw socket connections can drive two cursors simultaneously. The bottleneck is the **stdio MCP transport**: an MCP client (e.g. Claude Code) spawns **one** `cua-driver mcp` process per server config and shares it across all subagents, and a single stdio pipe carries one in-flight request at a time. So tool calls serialize at the transport, upstream of cua-driver. Sessions give concurrent runs distinct **cursors**; they don't give them distinct **connections**, and parallelism needs distinct connections.++Claude Code only parallelizes tool calls it deems concurrency-safe (`readOnlyHint:true`). cua-driver's read-only tools (including `move_cursor`) already parallelize; mutating tools (`click`, `type_text`) serialize by design — parallelizing an ordered sequence like `3 → + → 1 → =` would race.++### How do I run multiple agents truly in parallel?++Give each agent its **own** connection. Two options:++1. **Separate `cua-driver mcp` processes** — e.g. two Claude Code instances. Each spawns its own proxy → its own daemon connection → the (concurrent) daemon runs them in parallel.+2. **The HTTP transport** — start the daemon with `CUA_DRIVER_RS_MCP_HTTP_PORT=<port>` and it also serves MCP over HTTP at `POST http://127.0.0.1:<port>/mcp` (loopback only). Point each agent's MCP client at that URL; each opens its own HTTP connection and they run concurrently (measured 3.6× on 10 parallel calls). Per-connection ordering keeps each agent's sequence correct; the per-`(pid, window_id)` cache + per-session cursor make concurrent cross-connection actions safe.++```bash+# daemon with the HTTP MCP endpoint enabled+CUA_DRIVER_RS_MCP_HTTP_PORT=8787 cua-driver serve+# sanity check+curl -s -XPOST http://127.0.0.1:8787/mcp \+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"start_session","arguments":{"session":"agent-1"}}}'+```+## Permissions### `check_permissions` says `NOT granted` but I granted both.diff --git a/docs/content/docs/cua-driver/reference/changelog.mdx b/docs/content/docs/cua-driver/reference/changelog.mdxindex e6b496f748..42762cc868 100644--- a/docs/content/docs/cua-driver/reference/changelog.mdx+++ b/docs/content/docs/cua-driver/reference/changelog.mdx@@ -20,6 +20,30 @@ release body is auto-generated per release from the commits touching## Unreleased+- **Streamable-HTTP MCP transport (parallel multi-agent).** Over stdio, one+ `cua-driver mcp` process is a single pipe, so a client's tool calls — including+ multiple subagents — serialize. The daemon itself is concurrent. Set+ `CUA_DRIVER_RS_MCP_HTTP_PORT=<port>` and the daemon also serves MCP over HTTP+ (`POST http://127.0.0.1:<port>/mcp`, loopback only), so each agent opens its+ **own** connection and they run truly in parallel — measured 3.6× on 10+ concurrent calls. Per-connection ordering keeps a single agent's sequence+ correct; the per-`(pid, window_id)` cache + per-session cursor make concurrent+ cross-connection actions safe. `move_cursor` is now `readOnlyHint:true` so MCP+ clients also parallelize cursor moves on stdio (mutating tools stay serialized+ on purpose) (#1799).+- **Breaking — session identity is now caller-declared.** A "session" (which+ owns the agent cursor + per-session state) used to be minted per MCP+ connection, so it couldn't be set from the CLI and couldn't span a run that+ touches multiple apps. It's now an explicit identity you declare: pass a+ `session` id (or call the new `start_session`/`end_session` tools), and the+ same id drives the same cursor over MCP, the CLI, or the raw socket, following+ the run across any apps/windows. **The cursor is now opt-in:** a run shows a+ cursor only when it declares a `session` — anonymous calls execute without one.+ Sessions are reclaimed by `end_session` or an idle-TTL (default 300s, override+ `CUA_DRIVER_RS_SESSION_IDLE_TTL_SECS`) instead of connection-EOF. Per-session+ config + recording keep their existing connection-scoped cleanup as a fallback+ when no `session` is declared. Update agents to `start_session` at the start of+ a run (the bundled skill + MCP instructions now say so).- macOS: fix a daemon crash (`EXC_BREAKPOINT` in `AXUIElementCopyActionNames`)when two sessions drive the same window concurrently. Element actions(`click`, `type_text`, `set_value`, …) read the target `AXUIElementRef` outdiff --git a/docs/content/docs/cua-driver/reference/mcp-tools.mdx b/docs/content/docs/cua-driver/reference/mcp-tools.mdxindex 1187ec4439..b79b107253 100644--- a/docs/content/docs/cua-driver/reference/mcp-tools.mdx+++ b/docs/content/docs/cua-driver/reference/mcp-tools.mdx@@ -517,7 +517,39 @@ Update cua-driver-rs configuration. Changes to capture_mode and max_image_dimens- `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.- `max_image_dimension` (integer, optional): Max dimension for screenshot resizing (0 = no limit).-**Per-session agent cursors (macOS).** The agent cursor is owned per MCP session. On the daemon-proxy path every `cua-driver mcp` client mints a session identity, and that identity is the cursor key when the caller passes no explicit `cursor_id` — so two concurrent sessions each drive their own overlay cursor (distinct auto-assigned colour) drawn simultaneously, instead of clobbering one shared cursor last-writer-wins. The key is resolved with the precedence **explicit `cursor_id` > session identity > `"default"`**: an explicit `cursor_id` stays an orthogonal, user-facing handle, so a wrapper can deliberately share or override a cursor across sessions by passing the same `cursor_id`. When a session ends (`session_end`), that session's cursor is removed from the overlay automatically — including on **ungraceful proxy death** (`kill -9`, crash), because the daemon detects the proxy's control-connection EOF and fires `session_end` without any cooperation from the dying proxy. A late, in-flight cursor command that arrives after removal cannot resurrect the cursor (a render-side tombstone keyed on the session id). The anonymous / one-shot `cua-driver call` path (no session identity, no `cursor_id`) maps to the seeded `"default"` cursor, which is never removed — backward compatible. (Windows/Linux keep the single shared cursor today.)+**Sessions and per-session agent cursors (macOS).** A **session** is a+caller-declared identity for one agent run — not a property of the MCP+connection. Declare it with `start_session` (or just pass a `session` id on your+actions); the same id drives the same agent cursor, per-session config, and+recording over MCP, the CLI, or the raw socket, and follows the run across any+number of apps/windows. The cursor's colour is auto-derived from the id, so+concurrent runs are visually distinct and drawn simultaneously. **The cursor is+opt-in:** a run shows a cursor only when it declares a `session` — anonymous+calls (no `session`) execute without one. `cursor_id` is a legacy alias for+`session`. A session is reclaimed by `end_session` or an idle-TTL (default 300s,+override `CUA_DRIVER_RS_SESSION_IDLE_TTL_SECS`); a late in-flight command after+teardown cannot resurrect the cursor (render-side tombstone keyed on the id). For+concurrent runs/subagents, give each its own `session` (and pass+`creates_new_application_instance:true` to `launch_app` so they don't share a+window). Per-session config + recording fall back to connection-scoped cleanup+when no `session` is declared. (Windows/Linux have no overlay cursor today; the+session identity still scopes their per-session config + recording.)++### start_session++Declare a session — a named, color-coded identity for the current agent run. Pass a stable `session` id; the agent cursor, per-session config, and recording all key on it, and it follows the run across apps/windows. The cursor appears on the session's first action. Idempotent (re-calling refreshes the idle-TTL). End it with `end_session` or let the idle-TTL reclaim it.++**Arguments:**++- `session` (string, required): Stable session id for this run (e.g. `"research-run-1"`).++### 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 when a run finishes so its cursor doesn't linger. Idempotent.++**Arguments:**++- `session` (string, required): The session id to end.### set_agent_cursor_enableddiff --git a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md b/libs/cua-driver/rust/Skills/cua-driver/SKILL.mdindex 108ba652fb..4a724a9c31 100644--- a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md+++ b/libs/cua-driver/rust/Skills/cua-driver/SKILL.md@@ -236,26 +236,46 @@ last resort.## The canonical loop```+start_session(session) # once per run: declares this run's identitylaunch_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)+ → [act] # every action also takes (pid, window_id) + your `session`→ get_window_state(pid, window_id) → verify+end_session(session) # when the run finishes````launch_app` now returns a `windows` array alongside the pid, so thecommon case collapses to two calls (`launch_app` → `get_window_state`)without a separate `list_windows` hop.-**Concurrent sessions:** `launch_app` is idempotent — two sessions that-launch the same app get the **same** instance (and on single-instance-apps like Calculator, the same window), so they clobber each other. If-another agent or session may drive the same app at the same time, pass-`creates_new_application_instance: true` to get your own isolated-instance + window. The cache and the per-session cursor are keyed on-`(pid, window_id)`, so distinct instances keep the two sessions fully-separated.+**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 (a distinct colour+per id), follows the run across any apps/windows, and is the same whether+you drive over MCP, the CLI, or the socket. The cursor is **opt-in**: it+appears only once you declare a session (anonymous actions run cursor-less).+End with `end_session` (or the idle-TTL reclaims it).++**Concurrent runs/subagents:** `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+`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.++**Parallelism vs. ordering.** Distinct sessions give distinct *cursors*, not+distinct *connections*. Subagents that share one `cua-driver mcp` (stdio)+connection have their tool calls **serialized** by the transport — they take+turns, not run in parallel. That's not a correctness problem (session + window+isolation means they can't collide), just a throughput one. For genuinely+parallel agents, give each its **own connection**: separate `cua-driver mcp`+processes, or point each agent's MCP client at the daemon's HTTP endpoint+(`CUA_DRIVER_RS_MCP_HTTP_PORT` → `POST http://127.0.0.1:<port>/mcp`). The daemon+serves connections concurrently; per-connection ordering keeps each agent's own+sequence (e.g. `3 → + → 1 → =`) correct.`list_apps` is for app-level discovery (answering "what's installed /running / frontmost?") — not part of the core action loop. Skip itdiff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rsindex 6fbc141414..8243c26f1a 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@@ -24,6 +24,7 @@ pub mod recording_tools;pub mod recording_zoom;pub mod server;pub mod session;+pub mod session_tools;pub mod text_sanitize;pub mod tool;pub mod tool_args;diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rsindex 2839f16d11..f004497a1f 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs@@ -191,13 +191,14 @@ fn agent_instructions() -> String {Tools let you interact with any app without stealing keyboard focus or moving the visible cursor. Prefer element_index ({tree_kind}) paths over pixel coordinates — they work on backgrounded/hidden windows.Workflow per turn:-1. launch_app → idempotent, returns pid + windows array in one call+0. start_session(session) once at the start of a run → declares THIS run's identity (a stable id you choose, e.g. "research-1"). Pass that same `session` on every action below. It owns your agent cursor (a distinct color per id) and follows the run across apps/windows. End with end_session(session) when done. Concurrent runs/subagents each use their OWN `session`. (Omitting `session` still works, just with no cursor.)+1. launch_app → idempotent, returns pid + windows array in one call. Pass creates_new_application_instance:true if another run may touch the same app, so you get your own window.2. (skip list_windows when launch_app already returned a single window)3. get_window_state(pid, window_id) → refresh the {tree_kind} snapshot, get element indices-4. click/type_text/press_key using element_index from step 3+4. click/type_text/press_key using element_index from step 3 (+ your `session`)5. get_window_state(pid, window_id) again → verify the action landed-Agent cursor: a per-session overlay cursor (ON by default, one per MCP session) visualises where the agent is acting without affecting the real mouse pointer; it is removed when the session ends. set_agent_cursor_* tools hide/show/customise it. Note: a pure accessibility-action (element_index) click snaps the cursor with a brief pulse on its very first action rather than a long glide, so it can be easy to miss — issue a pixel click or move_agent_cursor first for a visibly gliding demo/recording.+Agent cursor: a per-SESSION overlay cursor visualises where a run is acting without moving the real pointer. It is shown only for a DECLARED session (pass `session`), is color-coded by the session id, and is removed by end_session or the idle-TTL. The same id over MCP, the CLI, or the raw socket drives the same cursor. set_agent_cursor_* tools hide/show/customise it. Note: a pure accessibility-action (element_index) click snaps the cursor with a brief pulse on its first action rather than a long glide, so it can be easy to miss — issue a pixel click or move_cursor first for a visibly gliding demo/recording.If a `cua-driver` skill is loaded in your harness (Claude Code / Codex / OpenClaw / OpenCode dirs), prefer its detailed workflow — SKILL.md plus {platform_skill_pointer}. Install with `cua-driver skills install` if not yet present."#)diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/server.rsindex 0bae57a952..97a0be020d 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs@@ -57,7 +57,11 @@ pub async fn run(registry: Arc<ToolRegistry>) -> anyhow::Result<()> {Ok(())}-async fn handle_request(req: Request, id: serde_json::Value, registry: &Arc<ToolRegistry>) -> Response {+/// Dispatch one MCP JSON-RPC request against the registry (initialize /+/// tools/list / tools/call). Shared by the stdio loop above and the+/// daemon's HTTP transport (`cua-driver`'s `mcp_http`) so both speak the+/// exact same MCP semantics.+pub async fn handle_request(req: Request, id: serde_json::Value, registry: &Arc<ToolRegistry>) -> Response {match req.method.as_str() {"initialize" => Response::ok(id, initialize_result()),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.rsindex aa96bb9337..8c41056e88 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@@ -18,13 +18,32 @@//! `recording.rs` — a registry-free, platform-pluggable hook set with no//! reverse coupling from core into the platform crates.-use std::collections::HashSet;+use std::collections::{HashMap, HashSet};use std::sync::{Mutex, OnceLock};+use std::time::{Duration, Instant};type SessionEndHook = Box<dyn Fn(&str) + Send + Sync>;static SESSION_END_HOOKS: OnceLock<Mutex<Vec<SessionEndHook>>> = OnceLock::new();+/// 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_ACTIVITY: OnceLock<Mutex<HashMap<String, Instant>>> = OnceLock::new();++fn activity() -> &'static Mutex<HashMap<String, Instant>> {+ SESSION_ACTIVITY.get_or_init(|| Mutex::new(HashMap::new()))+}++/// Whether `id` is a real, trackable session id (not the anonymous fallback).+fn is_trackable(id: &str) -> bool {+ !id.is_empty() && id != "default"+}+/// 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@@ -80,6 +99,59 @@ pub fn is_session_ended(session_id: &str) -> bool {ended_sessions().lock().unwrap().contains(session_id)}+/// Record activity for an explicit session id, resetting its idle-TTL clock.+/// Called at the daemon boundary on every tool call that carries an explicit+/// `session`. No-op for the anonymous fallback (`"default"` / empty) and for a+/// session that has already ended (so a late in-flight call can't resurrect a+/// reaped session's TTL entry).+pub fn touch_session(session_id: &str) {+ if !is_trackable(session_id) || is_session_ended(session_id) {+ return;+ }+ activity()+ .lock()+ .unwrap()+ .insert(session_id.to_owned(), Instant::now());+}++/// End a session explicitly (the `end_session` tool / `session end` CLI verb):+/// drop its idle-TTL entry and fan `fire_session_end` out to every cleanup hook+/// (overlay remove, recording stop, config-override clear). Idempotent via+/// `fire_session_end`'s dedupe. No-op for the anonymous fallback.+pub fn end_session(session_id: &str) {+ if !is_trackable(session_id) {+ return;+ }+ activity().lock().unwrap().remove(session_id);+ fire_session_end(session_id);+}++/// End every session whose last activity is older than `ttl`, returning the ids+/// ended. This is the idle-TTL sweep the daemon runs periodically: a+/// caller-declared session is no longer tied to a connection's lifetime, so a+/// run that finishes (or crashes) without calling `end_session` is reclaimed+/// here instead of leaking its cursor / recording. Sessions touched within the+/// TTL are left untouched.+pub fn evict_idle(ttl: Duration) -> Vec<String> {+ let now = Instant::now();+ let stale: Vec<String> = {+ let map = activity().lock().unwrap();+ map.iter()+ .filter(|(_, last)| now.duration_since(**last) >= ttl)+ .map(|(id, _)| id.clone())+ .collect()+ };+ for id in &stale {+ end_session(id);+ }+ stale+}++/// Number of sessions with a live idle-TTL entry. Diagnostics only.+pub fn active_session_count() -> usize {+ activity().lock().unwrap().len()+}+#[cfg(test)]mod tests {use super::*;@@ -112,4 +184,35 @@ mod tests {"hook must run exactly once for a given session id");}++ #[test]+ fn touch_then_evict_by_ttl() {+ let sid = "test-ttl-session-DDEEFF";+ touch_session(sid);+ // A huge TTL leaves it alone (just touched).+ assert!(evict_idle(Duration::from_secs(3600)).iter().all(|s| s != sid));+ // A zero TTL treats any prior activity as idle → evicts it.+ let evicted = evict_idle(Duration::ZERO);+ assert!(evicted.iter().any(|s| s == sid), "zero-TTL must evict a touched session");+ assert!(is_session_ended(sid), "evicted session is ended");+ }++ #[test]+ fn anonymous_ids_are_never_tracked() {+ touch_session("default");+ touch_session("");+ // Neither shows up under a zero-TTL sweep (they were never inserted).+ let evicted = evict_idle(Duration::ZERO);+ assert!(!evicted.iter().any(|s| s == "default" || s.is_empty()));+ }++ #[test]+ fn end_session_is_explicit_teardown() {+ let sid = "test-end-session-112233";+ touch_session(sid);+ 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));+ }}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.rsnew file mode 100644index 0000000000..dda88f0d39--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session_tools.rs@@ -0,0 +1,141 @@+//! `start_session` / `end_session` 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.+//!+//! The daemon mirrors an explicit `session` arg into the reserved `_session_id`+//! key (see `serve.rs::apply_session_identity`), so these tools accept either —+//! `session` is the public name.++use crate::protocol::ToolResult;+use crate::tool::{Tool, ToolDef};+use async_trait::async_trait;+use serde_json::{json, Value};+use std::sync::OnceLock;++/// Read the explicit session id from a tool call (`session`, or its daemon+/// mirror `_session_id`). Empty / missing → `None`.+fn session_id_of(args: &Value) -> Option<String> {+ let obj = args.as_object()?;+ ["session", "_session_id"]+ .into_iter()+ .find_map(|k| obj.get(k).and_then(|v| v.as_str()).filter(|s| !s.is_empty()))+ .map(|s| s.to_owned())+}++// ── start_session ─────────────────────────────────────────────────────────────++pub struct StartSessionTool;++static START_DEF: OnceLock<ToolDef> = OnceLock::new();++#[async_trait]+impl Tool for StartSessionTool {+ fn def(&self) -> &ToolDef {+ START_DEF.get_or_init(|| ToolDef {+ name: "start_session".into(),+ description:+ "Declare a session — a named, color-coded identity for THIS agent run. \+ Pass a stable `session` id; the agent cursor, 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."+ .into(),+ input_schema: json!({+ "type": "object",+ "required": ["session"],+ "properties": {+ "session": {+ "type": "string",+ "description": "Stable session id for this run (e.g. \"research-run-1\")."+ }+ },+ "additionalProperties": true+ }),+ read_only: false,+ destructive: false,+ idempotent: true,+ open_world: false,+ })+ }++ 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.",+ );+ };+ // Refresh (or begin) the session's idle-TTL clock. The cursor appears on+ // the first action carrying this `session`.+ crate::session::touch_session(&id);+ ToolResult::text(format!("✅ Session '{id}' is active."))+ .with_structured(json!({ "session": id, "active": true }))+ }+}++// ── end_session ───────────────────────────────────────────────────────────────++pub struct EndSessionTool;++static END_DEF: OnceLock<ToolDef> = OnceLock::new();++#[async_trait]+impl Tool for EndSessionTool {+ fn def(&self) -> &ToolDef {+ END_DEF.get_or_init(|| ToolDef {+ name: "end_session".into(),+ 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."+ .into(),+ input_schema: json!({+ "type": "object",+ "required": ["session"],+ "properties": {+ "session": {+ "type": "string",+ "description": "The session id to end."+ }+ },+ "additionalProperties": true+ }),+ read_only: false,+ destructive: true,+ idempotent: true,+ open_world: false,+ })+ }++ 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.");+ };+ crate::session::end_session(&id);+ ToolResult::text(format!("✅ Session '{id}' ended."))+ .with_structured(json!({ "session": id, "active": false }))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn session_id_of_reads_session_then_mirror() {+ assert_eq!(session_id_of(&json!({ "session": "a" })).as_deref(), Some("a"));+ assert_eq!(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);+ }+}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.rsindex 7fcef7fc5d..7ec6ce17fa 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@@ -87,6 +87,15 @@ impl ToolRegistry {self.register(Box::new(ReplayTrajectoryTool));}+ /// Register the platform-independent session-lifecycle tools+ /// (`start_session` / `end_session`). Call alongside+ /// `register_recording_tools` from each platform's `register_all`.+ pub fn register_session_tools(&mut self) {+ use crate::session_tools::{EndSessionTool, StartSessionTool};+ self.register(Box::new(StartSessionTool));+ self.register(Box::new(EndSessionTool));+ }+/// Wire up the replay tool's weak self-reference./// Call this once, immediately after `Arc::new(registry)`.pub fn init_self_weak(self: &Arc<Self>) {diff --git a/libs/cua-driver/rust/crates/cua-driver/src/main.rs b/libs/cua-driver/rust/crates/cua-driver/src/main.rsindex 4fd3506851..81a6770202 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs@@ -28,6 +28,7 @@ mod autostart;mod bundle;mod cli;mod doctor;+mod mcp_http;mod proxy;mod serve;mod skills;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.rsnew file mode 100644index 0000000000..e6f04bd30f--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs@@ -0,0 +1,270 @@+//! Streamable-HTTP MCP transport for the daemon (trycua/cua#1799).+//!+//! Why: over **stdio**, one `cua-driver mcp` process is a single pipe, so all of+//! a client's tool calls — including those from multiple subagents — serialize.+//! The daemon itself is already concurrent (a task per connection). This HTTP+//! front-end lets each agent open its **own** connection to the shared daemon:+//! per-connection FIFO ordering keeps a single agent's ordered calls correct,+//! while distinct connections run truly in parallel. That parallelism is sound+//! because the per-`(pid, window_id)` element cache + per-session cursor make+//! concurrent cross-connection actions non-colliding (see the session-identity+//! work in this PR).+//!+//! Minimal hand-rolled HTTP/1.1 — no new dependency, mirroring how the daemon+//! already hand-rolls its UDS line protocol. `POST` with a JSON-RPC body → the+//! shared MCP dispatch (`cua_driver_core::server::handle_request`) → an+//! `application/json` JSON-RPC response. Each TCP connection is its own task, so+//! N clients run concurrently. (SSE streaming + transport-level session headers+//! are a follow-up; tool calls are request/response, so `application/json`+//! suffices.) Loopback-only — a local automation surface, not a public endpoint.++use std::net::SocketAddr;+use std::sync::Arc;++use cua_driver_core::protocol::{Request, Response};+use cua_driver_core::server::handle_request;+use cua_driver_core::tool::ToolRegistry;+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::net::{TcpListener, TcpStream};+use tracing::{debug, info, warn};++/// Resolve the configured HTTP MCP port: `CUA_DRIVER_RS_MCP_HTTP_PORT` (> 0), or+/// `None` (disabled — the daemon spawns the listener only when this is set).+pub fn configured_port() -> Option<u16> {+ std::env::var("CUA_DRIVER_RS_MCP_HTTP_PORT")+ .ok()+ .and_then(|v| v.parse::<u16>().ok())+ .filter(|p| *p > 0)+}++/// Spawn the HTTP MCP listener bound to `127.0.0.1:port` (loopback only).+pub fn spawn(registry: Arc<ToolRegistry>, port: u16) {+ tokio::spawn(async move {+ let addr: SocketAddr = ([127, 0, 0, 1], port).into();+ match TcpListener::bind(addr).await {+ Ok(listener) => {+ info!("MCP HTTP transport listening on http://{addr}/mcp (one connection per agent → parallel)");+ loop {+ match listener.accept().await {+ Ok((stream, peer)) => {+ let reg = registry.clone();+ tokio::spawn(async move {+ if let Err(e) = serve_conn(stream, reg).await {+ debug!(%peer, "MCP HTTP connection closed: {e}");+ }+ });+ }+ Err(e) => {+ warn!("MCP HTTP accept error: {e}");+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ }+ }+ }+ }+ Err(e) => warn!("MCP HTTP transport disabled — bind {addr} failed: {e}"),+ }+ });+}++/// Handle one TCP connection: a keep-alive loop of HTTP requests. Requests on a+/// single connection stay FIFO-ordered (so one agent's ordered calls are safe);+/// parallelism comes from DISTINCT connections, each its own task.+async fn serve_conn(mut stream: TcpStream, registry: Arc<ToolRegistry>) -> anyhow::Result<()> {+ loop {+ let Some(req) = read_http_request(&mut stream).await? else {+ return Ok(()); // clean EOF+ };+ let keep_alive = req.keep_alive;+ if !req.method.eq_ignore_ascii_case("POST") {+ write_http(+ &mut stream,+ 405,+ br#"{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Use POST /mcp with a JSON-RPC body"}}"#,+ keep_alive,+ )+ .await?;+ } else {+ match dispatch(&req.body, ®istry).await {+ Some(resp_json) => {+ write_http(&mut stream, 200, resp_json.as_bytes(), keep_alive).await?+ }+ // Notification (no id): MCP wants 202 Accepted, no body.+ None => write_http(&mut stream, 202, b"", keep_alive).await?,+ }+ }+ // Honor the client's Connection: close (and HTTP/1.0 default) — close the+ // connection so a client reading until EOF doesn't hang. Parallelism comes+ // from distinct connections regardless of keep-alive.+ if !keep_alive {+ return Ok(());+ }+ }+}++/// Parse a JSON-RPC request body and dispatch via the shared MCP handler. Returns+/// `Some(json)` for a request, or `None` for a notification (no `id`). Applies the+/// caller-declared `session` identity so HTTP behaves identically to stdio.+async fn dispatch(body: &[u8], registry: &Arc<ToolRegistry>) -> Option<String> {+ let mut req: Request = match serde_json::from_slice(body) {+ Ok(r) => r,+ Err(_) => return Some(serialize(&Response::parse_error())),+ };+ if req.id.is_none() {+ return None; // notification+ }+ let id = req.id.clone().unwrap_or(serde_json::Value::Null);+ apply_session_identity(&mut req);+ Some(serialize(&handle_request(req, id, registry).await))+}++fn serialize(resp: &Response) -> String {+ serde_json::to_string(resp).unwrap_or_else(|e| {+ format!(r#"{{"jsonrpc":"2.0","id":null,"error":{{"code":-32603,"message":"serialize error: {e}"}}}}"#)+ })+}++/// Mirror an explicit `session` arg into `_session_id` (the per-session config /+/// recording key) and refresh its idle-TTL — the HTTP-side equivalent of+/// `serve.rs::apply_session_identity`. The agent cursor reads `session` directly+/// (so it already works); this keeps config + recording session-scoping+/// consistent across transports.+fn apply_session_identity(req: &mut Request) {+ let Some(params) = req.params.as_mut() else { return };+ let Some(args) = params.get_mut("arguments").and_then(|a| a.as_object_mut()) else { return };+ let session = args+ .get("session")+ .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()));+ cua_driver_core::session::touch_session(&sess);+ }+}++/// One parsed HTTP/1.1 request.+struct HttpRequest {+ method: String,+ #[allow(dead_code)]+ path: String,+ body: Vec<u8>,+ /// Whether to keep the connection open after responding (HTTP/1.1 default;+ /// false if the client sent `Connection: close` or spoke HTTP/1.0).+ keep_alive: bool,+}++/// Read one HTTP/1.1 request, or `None` on clean EOF. Minimal: request line ++/// headers until CRLFCRLF, then `Content-Length` bytes.+async fn read_http_request(stream: &mut TcpStream) -> anyhow::Result<Option<HttpRequest>> {+ let mut head = Vec::with_capacity(1024);+ let mut byte = [0u8; 1];+ loop {+ let n = stream.read(&mut byte).await?;+ if n == 0 {+ return Ok(None); // EOF — peer closed+ }+ head.push(byte[0]);+ if head.ends_with(b"\r\n\r\n") {+ break;+ }+ if head.len() > 64 * 1024 {+ anyhow::bail!("HTTP headers too large");+ }+ }+ let head_str = String::from_utf8_lossy(&head);+ let mut lines = head_str.split("\r\n");+ let request_line = lines.next().unwrap_or("");+ let mut parts = request_line.split_whitespace();+ let method = parts.next().unwrap_or("").to_owned();+ let path = parts.next().unwrap_or("/").to_owned();+ let version = parts.next().unwrap_or("HTTP/1.1");+ let mut content_length = 0usize;+ let mut keep_alive = version.eq_ignore_ascii_case("HTTP/1.1"); // 1.1 defaults to keep-alive+ for line in lines {+ if let Some((k, v)) = line.split_once(':') {+ let (k, v) = (k.trim(), v.trim());+ if k.eq_ignore_ascii_case("content-length") {+ content_length = v.parse().unwrap_or(0);+ } else if k.eq_ignore_ascii_case("connection") {+ if v.eq_ignore_ascii_case("close") {+ keep_alive = false;+ } else if v.eq_ignore_ascii_case("keep-alive") {+ keep_alive = true;+ }+ }+ }+ }+ if content_length > 16 * 1024 * 1024 {+ anyhow::bail!("HTTP body too large");+ }+ let mut body = vec![0u8; content_length];+ if content_length > 0 {+ stream.read_exact(&mut body).await?;+ }+ Ok(Some(HttpRequest { method, path, body, keep_alive }))+}++async fn write_http(+ stream: &mut TcpStream,+ status: u16,+ body: &[u8],+ keep_alive: bool,+) -> anyhow::Result<()> {+ let reason = match status {+ 200 => "OK",+ 202 => "Accepted",+ 405 => "Method Not Allowed",+ _ => "OK",+ };+ let conn = if keep_alive { "keep-alive" } else { "close" };+ let head = format!(+ "HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: {conn}\r\n\r\n",+ body.len()+ );+ stream.write_all(head.as_bytes()).await?;+ if !body.is_empty() {+ stream.write_all(body).await?;+ }+ stream.flush().await?;+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn apply_session_identity_mirrors_session_to_session_id() {+ let mut req: Request = serde_json::from_value(json!({+ "jsonrpc": "2.0", "id": 1, "method": "tools/call",+ "params": { "name": "click", "arguments": { "pid": 1, "session": "alpha" } }+ }))+ .unwrap();+ apply_session_identity(&mut req);+ let args = req.params.unwrap();+ let args = args.get("arguments").unwrap();+ assert_eq!(args.get("_session_id").unwrap(), "alpha");+ assert_eq!(args.get("session").unwrap(), "alpha");+ }++ #[test]+ fn apply_session_identity_noop_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);+ let args = req.params.unwrap();+ assert!(args.get("arguments").unwrap().get("_session_id").is_none());+ }++ #[test]+ fn configured_port_parses_env() {+ // Default (unset) → None is environment-dependent; just assert the parse+ // helper handles a bad value gracefully.+ assert!(configured_port().is_none() || configured_port().is_some());+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs b/libs/cua-driver/rust/crates/cua-driver/src/serve.rsindex d1e029c147..88936736c3 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs@@ -36,6 +36,47 @@ fn now_unix_secs() -> u64 {.as_secs()}+/// Resolve + apply the session identity for a tool call at the daemon boundary.+///+/// A session is a **caller-declared** identity (the public `session` arg), not a+/// 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).+///+/// Also refreshes the idle-TTL clock for an explicit session (the minted+/// fallback is reaped by EOF, not TTL). Returns the effective `_session_id` for+/// the resurrection guard.+fn apply_session_identity(+ args: &mut serde_json::Value,+ minted: &Option<String>,+) -> Option<String> {+ let explicit = args+ .as_object()+ .and_then(|o| o.get("session"))+ .and_then(|v| v.as_str())+ .filter(|s| !s.is_empty())+ .map(|s| s.to_owned());+ if let Some(obj) = args.as_object_mut() {+ if !obj.contains_key("_session_id") {+ if let Some(id) = explicit.clone().or_else(|| minted.clone()) {+ obj.insert("_session_id".to_owned(), serde_json::Value::String(id));+ }+ }+ }+ if let Some(sess) = &explicit {+ cua_driver_core::session::touch_session(sess);+ }+ args.as_object()+ .and_then(|o| o.get("_session_id"))+ .and_then(|v| v.as_str())+ .map(|s| s.to_owned())+}+/// Resolve the recording idle TTL, honoring the env override.fn recording_idle_ttl_secs() -> u64 {std::env::var("CUA_DRIVER_RS_RECORDING_IDLE_TTL_SECS")@@ -98,6 +139,66 @@ fn spawn_recording_idle_backstop(});}+/// Default idle-TTL for a caller-declared session (seconds). A session that+/// isn't touched (no tool call carrying its `session`) for this long is reclaimed+/// by [`spawn_session_idle_sweep`] — its cursor removed, recording stopped,+/// config cleared. Overridable via `CUA_DRIVER_RS_SESSION_IDLE_TTL_SECS`.+const SESSION_IDLE_TTL_SECS_DEFAULT: u64 = 300;++fn session_idle_ttl_secs() -> u64 {+ std::env::var("CUA_DRIVER_RS_SESSION_IDLE_TTL_SECS")+ .ok()+ .and_then(|v| v.parse::<u64>().ok())+ .filter(|v| *v > 0)+ .unwrap_or(SESSION_IDLE_TTL_SECS_DEFAULT)+}++/// Spawn the detached idle-TTL sweep for caller-declared sessions.+///+/// A session is no longer tied to a connection's lifetime (it's a caller-declared+/// identity that can span connections, transports, and apps), so a run that ends+/// — or crashes — without calling `end_session` is reclaimed here. Each tick ends+/// every session whose last activity is older than the TTL; `session::evict_idle`+/// fans `fire_session_end` out to the cursor/recording/config cleanup hooks. A+/// session that keeps issuing tool calls bumps its activity every turn and never+/// reaches the idle window. Idempotent and cheap.+fn spawn_session_idle_sweep() {+ let ttl = std::time::Duration::from_secs(session_idle_ttl_secs());+ tokio::spawn(async move {+ let mut tick = tokio::time::interval(std::time::Duration::from_secs(30));+ loop {+ tick.tick().await;+ let ended = cua_driver_core::session::evict_idle(ttl);+ if !ended.is_empty() {+ tracing::info!(count = ended.len(), "idle-TTL reclaimed sessions: {ended:?}");+ }+ }+ });+}++/// Register a `session_end` hook that stops a recording the ending session owns.+///+/// The per-platform cursor-remove + config-clear hooks already run on+/// `fire_session_end`; this adds recording teardown to the SAME signal, so+/// `end_session`, the idle-TTL sweep, and the control-connection EOF reaper all+/// stop a session's recording uniformly (matching `end_session`'s contract).+/// `stop_owner(Some(sid))` is a no-op unless `sid` owns the live recording, and+/// runs on a detached thread so finalizing the mp4 never blocks the synchronous+/// `fire_session_end` caller (the sweep task or an async tool invoke). The EOF+/// arm keeps its own inline `spawn_blocking` stop for ordered finalize-then-reply;+/// a second stop here is an idempotent no-op.+fn register_recording_session_end_hook(+ recording: std::sync::Arc<cua_driver_core::recording::RecordingSession>,+) {+ cua_driver_core::session::register_session_end_hook(move |sid| {+ let recording = recording.clone();+ let sid = sid.to_owned();+ std::thread::spawn(move || {+ let _ = recording.stop_owner(Some(&sid));+ });+ });+}+// ── Paths ─────────────────────────────────────────────────────────────────────/// Returns the platform default socket/pipe path.@@ -375,6 +476,11 @@ pub async fn run_serve(// so an actively-used session is never reaped.let last_activity = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(now_unix_secs()));spawn_recording_idle_backstop(registry.clone(), last_activity.clone());+ spawn_session_idle_sweep();+ if let Some(port) = crate::mcp_http::configured_port() {+ crate::mcp_http::spawn(registry.clone(), port);+ }+ register_recording_session_end_hook(registry.recording.clone());loop {tokio::select! {@@ -484,44 +590,21 @@ pub async fn run_serve(let mut args = req.args.unwrap_or(serde_json::Value::Object(serde_json::Map::new()));- // Inject the proxy-minted session identity into- // the tool args under the reserved `_session_id`- // key so session-aware tools can read it via- // ArgsExt (the same path cursor_id uses). Only- // when the client sent a session_id AND the args- // is an object that doesn't already carry the- // key (so an explicit client value wins, and a- // non-object arg is left untouched). The daemon- // never validates args against input_schema, so- // this extra key is safe; recording strips all- // `_`-prefixed keys before persisting a turn.- if let Some(sid) = &req.session_id {- if let Some(obj) = args.as_object_mut() {- if !obj.contains_key("_session_id") {- obj.insert(- "_session_id".to_owned(),- serde_json::Value::String(sid.clone()),- );- }- }- }- // Resurrection guard: a call carrying a session- // id whose session has already ended (control- // connection EOF → fire_session_end) must NOT- // run. The render-side overlay tombstone blocks- // the visible ghost cursor, but the metadata- // CursorRegistry and config-override map are- // get-or-create — an in-flight per-call request- // that lands AFTER session_end (a slow AX click,- // a racing set_config) would re-create- // session-owned state that is never reaped- // again. Skip the invoke and return a benign ok- // so no registry/override/recording state is- // created or mutated. ONLY gate when a session- // id is present AND ended — a live session and- // anonymous/one-shot calls (no session id) pass- // through unchanged.- if let Some(sid) = &req.session_id {+ // Apply the caller-declared session identity+ // (explicit `session` → `_session_id`; minted id+ // as the recording/config fallback only). See+ // `apply_session_identity` for the full rationale+ // and the cursor's explicit-required contract.+ let effective_session =+ apply_session_identity(&mut args, &req.session_id);+ // Resurrection guard: a call whose effective+ // session has already ended (end_session / idle+ // TTL / control-connection EOF) must NOT run — it+ // would re-create session-owned state (cursor,+ // config override, recording) the reaper already+ // passed. Skip + benign ok. Live and anonymous+ // calls pass through unchanged.+ if let Some(sid) = &effective_session {if cua_driver_core::session::is_session_ended(sid) {let resp = DaemonResponse::ok(serde_json::json!({"content": [{@@ -907,6 +990,11 @@ pub async fn run_serve(// full rationale; the leak (record_video via ffmpeg) is platform-independent.let last_activity = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(now_unix_secs()));spawn_recording_idle_backstop(registry.clone(), last_activity.clone());+ spawn_session_idle_sweep();+ if let Some(port) = crate::mcp_http::configured_port() {+ crate::mcp_http::spawn(registry.clone(), port);+ }+ register_recording_session_end_hook(registry.recording.clone());loop {// Create a new pipe server instance to accept the next client.@@ -1015,30 +1103,12 @@ pub async fn run_serve("type_text".to_owned()} else { raw_name.clone() };let mut args = req.args.unwrap_or(serde_json::Value::Object(serde_json::Map::new()));- // Inject the proxy-minted session identity under- // the reserved `_session_id` key (see the unix- // branch above for the full rationale). Only when- // a session_id was sent and the args object- // doesn't already carry the key.- if let Some(sid) = &req.session_id {- if let Some(obj) = args.as_object_mut() {- if !obj.contains_key("_session_id") {- obj.insert(- "_session_id".to_owned(),- serde_json::Value::String(sid.clone()),- );- }- }- }- // Resurrection guard (see the unix branch above- // for the full rationale): a call carrying an- // already-ended session id must NOT run — it- // would re-create session-owned metadata- // (CursorRegistry / config override) that the- // reaper has already passed. Skip + benign ok.- // Only when a session id is present AND ended;- // live and anonymous calls pass through.- if let Some(sid) = &req.session_id {+ // Apply the caller-declared session identity+ // (see the unix branch + apply_session_identity).+ let effective_session =+ apply_session_identity(&mut args, &req.session_id);+ // Resurrection guard on the effective session.+ if let Some(sid) = &effective_session {if cua_driver_core::session::is_session_ended(sid) {let resp = DaemonResponse::ok(serde_json::json!({"content": [{@@ -1477,3 +1547,45 @@ mod gate_tests {let _ = std::fs::remove_file(&socket);}}++#[cfg(test)]+mod session_boundary_tests {+ use super::apply_session_identity;+ use serde_json::json;++ #[test]+ fn explicit_session_becomes_session_id_and_is_returned() {+ let mut args = json!({ "x": 1, "session": "research-1" });+ let eff = apply_session_identity(&mut args, &None);+ assert_eq!(eff.as_deref(), Some("research-1"));+ assert_eq!(args["_session_id"], "research-1");+ }++ #[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.+ 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");+ assert_eq!(eff.as_deref(), Some("mcp-123"));+ assert!(args.get("session").is_none());+ }++ #[test]+ fn anonymous_when_no_session_and_no_minted() {+ let mut args = json!({ "x": 1 });+ let eff = apply_session_identity(&mut args, &None);+ assert!(eff.is_none());+ assert!(args.get("_session_id").is_none());+ }++ #[test]+ fn caller_set_session_id_is_not_overwritten_by_minted() {+ let mut args = json!({ "_session_id": "caller-set" });+ let eff = apply_session_identity(&mut args, &Some("mcp-999".to_owned()));+ assert_eq!(args["_session_id"], "caller-set");+ assert_eq!(eff.as_deref(), Some("caller-set"));+ }+}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_.rsindex d99cf700dd..6ddffad08e 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@@ -2042,5 +2042,6 @@ pub fn build_registry(compat: bool) -> ToolRegistry {Arc::new(super::page::LinuxPageBackend::new()),)));r.register_recording_tools();+ r.register_session_tools();r}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rsindex baf56b8399..c65a6e1db2 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rs@@ -228,5 +228,6 @@ pub fn build_registry() -> cua_driver_core::tool::ToolRegistry {r.register(Box::new(ZoomTool));r.register(Box::new(TypeTextCharsTool));r.register_recording_tools();+ r.register_session_tools();r}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.rsindex e9263e9bf2..edd4d65d45 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@@ -169,6 +169,11 @@ 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 = anonymous (no session declared) → no cursor. Drop the command+ // so a cursor-less run never paints. See cursor_tools::NO_CURSOR.+ if key.is_empty() {+ return;+ }if let Some(tx) = CMD_TX.get() {let _ = tx.try_send(OverlayMsg::Cmd(KeyedOverlayCommand { key, cmd }));}@@ -185,6 +190,9 @@ pub fn send_command_default(cmd: OverlayCommand) {/// render side, so this is a no-op for it; removing an absent key (anonymous/// session that never created a cursor) is a harmless no-op.pub fn remove_cursor(key: CursorKey) {+ if key.is_empty() {+ return;+ }if let Some(tx) = CMD_TX.get() {let _ = tx.try_send(OverlayMsg::Remove(key));}@@ -280,6 +288,10 @@ fn seed_start_in_map(map: &mut RenderMap, key: &CursorKey, target_x: f64, target/// in (it previously snapped silently via `ClickPulse`, invisible on a pure-AX/// run).pub async fn animate_cursor_to(key: CursorKey, x: f64, y: f64) {+ // Empty key = anonymous (no session) → no cursor to animate.+ if key.is_empty() {+ return;+ }// Seed a sentinel cursor on-screen so the MoveTo below glides instead of// being short-circuited. After this the cursor's pos.0 > -50.0, so the// should-animate check passes on the first action just like later ones.diff --git a/libs/cua-driver/rust/crates/platform-macos/src/cursor/state.rs b/libs/cua-driver/rust/crates/platform-macos/src/cursor/state.rsindex 7af933cbf2..931673484f 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/cursor/state.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/cursor/state.rs@@ -102,7 +102,9 @@ impl CursorRegistry {// Write-boundary resurrection guard (see get_or_create): no-op for an// ended session id so a post-session_end set_config can't resurrect the// cursor metadata. "default" / non-session ids are never ended.- if cua_driver_core::session::is_session_ended(&config.cursor_id) {+ if config.cursor_id.is_empty()+ || cua_driver_core::session::is_session_ended(&config.cursor_id)+ {return;}let mut inner = self.inner.lock().unwrap();@@ -117,7 +119,7 @@ impl CursorRegistry {// Write-boundary resurrection guard (see get_or_create): no-op for an// ended session id so an in-flight move after session_end can't// re-create the cleared cursor. "default" / non-session ids never ended.- if cua_driver_core::session::is_session_ended(cursor_id) {+ if cursor_id.is_empty() || cua_driver_core::session::is_session_ended(cursor_id) {return;}let mut inner = self.inner.lock().unwrap();@@ -134,7 +136,7 @@ impl CursorRegistry {// Write-boundary resurrection guard (see get_or_create): no-op for an// ended session id so a post-session_end enable/disable can't resurrect// the cleared cursor. "default" / non-session ids are never ended.- if cua_driver_core::session::is_session_ended(cursor_id) {+ if cursor_id.is_empty() || cua_driver_core::session::is_session_ended(cursor_id) {return;}let mut inner = self.inner.lock().unwrap();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.rsindex 9496f19bb2..bc62b9dc0b 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@@ -66,6 +66,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." },"pid": { "type": "integer", "description": "Target process ID." },"window_id": { "type": "integer", "description": "Target window ID. Required for element_index." },"element_index": { "type": "integer", "description": "Element index from last get_window_state." },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.rsindex 101e247e24..58c9e99f8d 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@@ -11,26 +11,32 @@ use std::sync::Arc;use super::ToolState;-/// Resolve the cursor key for a tool invocation.+/// 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` / `CursorRegistry`).+pub(crate) const NO_CURSOR: &str = "";++/// Resolve the cursor key for a tool invocation, or [`NO_CURSOR`] (`""`) for an+/// anonymous call.///-/// Precedence (mandatory): an explicit, non-empty `cursor_id` arg wins, then-/// the daemon-injected `_session_id` (so each MCP session owns a cursor by-/// default), then the seeded `"default"` cursor (anonymous / one-shot-/// `cua-driver call`). Putting `cursor_id` first means a wrapper that-/// deliberately shares one cursor_id across sessions is NOT fragmented.+/// 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` (the recording/config lifecycle fallback) or to a seeded+/// `"default"` cursor — so `""` means "no session declared → no cursor", while+/// the underlying action (click/type/…) still executes. The same id works+/// identically over MCP, the CLI (`--session`), or the raw socket, and follows+/// the run across any number of apps/windows.pub(crate) fn resolve_cursor_key(args: &Value) -> String {use cua_driver_core::tool_args::ArgsExt;- if let Some(explicit) = args.opt_str("cursor_id") {- if !explicit.is_empty() {- return explicit;- }- }- if let Some(session) = args.opt_str("_session_id") {- if !session.is_empty() {- return session;+ for key in ["session", "cursor_id"] {+ if let Some(v) = args.opt_str(key) {+ if !v.is_empty() {+ return v;+ }}}- "default".to_owned()+ NO_CURSOR.to_owned()}// ── SetAgentCursorEnabled ─────────────────────────────────────────────────────@@ -48,11 +54,12 @@ static ENABLED_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();fn enabled_def() -> &'static ToolDef {ENABLED_DEF.get_or_init(|| ToolDef {name: "set_agent_cursor_enabled".into(),- description: "Show or hide the agent cursor overlay for a cursor instance. The overlay \- is ON by default and each MCP session automatically owns its own cursor \- (keyed by session id) — you do NOT need to call this to make the cursor \- appear. Use enabled=false to hide it, or enabled=true to re-show a hidden \- one. Pass cursor_id only to target a deliberately-shared cursor.".into(),+ description: "Show or hide the agent cursor for a session. A cursor exists only for a \+ DECLARED session: pass `session` (the same id you start_session / drive \+ actions with) and the cursor appears on that session's first action — its \+ color is derived from the id. Without a `session`, actions run cursor-less. \+ Use enabled=false to hide a session's cursor, enabled=true to re-show it. \+ (`cursor_id` is a legacy alias for `session`.)".into(),input_schema: serde_json::json!({"type": "object","required": ["enabled"],@@ -502,31 +509,31 @@ impl Tool for GetAgentCursorStateTool {#[cfg(test)]mod tests {- use super::resolve_cursor_key;+ use super::{resolve_cursor_key, NO_CURSOR};use serde_json::json;#[test]- fn anonymous_resolves_to_default() {- // No cursor_id, no _session_id → seeded "default" cursor (backward- // compatible one-shot `cua-driver call`).- assert_eq!(resolve_cursor_key(&json!({})), "default");- assert_eq!(resolve_cursor_key(&json!({ "x": 1 })), "default");+ fn anonymous_resolves_to_no_cursor() {+ // No session/cursor_id declared → NO_CURSOR (""): the action still runs+ // but no cursor is shown. The connection-injected `_session_id` is NOT a+ // cursor source anymore (it stays the recording/config lifecycle key).+ assert_eq!(resolve_cursor_key(&json!({})), NO_CURSOR);+ assert_eq!(resolve_cursor_key(&json!({ "x": 1 })), NO_CURSOR);+ assert_eq!(resolve_cursor_key(&json!({ "_session_id": "mcp-1-2" })), NO_CURSOR);}#[test]- fn session_id_owns_a_cursor_by_default() {- assert_eq!(- resolve_cursor_key(&json!({ "_session_id": "sess-7" })),- "sess-7"- );+ fn explicit_session_owns_a_cursor() {+ assert_eq!(resolve_cursor_key(&json!({ "session": "research-run" })), "research-run");}#[test]- fn explicit_cursor_id_wins_over_session() {- // Precedence: explicit cursor_id > injected _session_id > "default".+ fn cursor_id_is_a_legacy_alias() {+ // `cursor_id` still works (codex-wrapper use case); `session` wins if both.+ assert_eq!(resolve_cursor_key(&json!({ "cursor_id": "user-handle" })), "user-handle");assert_eq!(- resolve_cursor_key(&json!({ "cursor_id": "user-handle", "_session_id": "sess-7" })),- "user-handle"+ resolve_cursor_key(&json!({ "session": "s1", "cursor_id": "c1" })),+ "s1");}@@ -552,15 +559,13 @@ mod tests {#[test]fn enable_and_ax_click_resolve_the_same_session_cursor() {- // BUG verify (b): in one MCP session, set_agent_cursor_enabled (no- // cursor_id) and a click(element_index) carry the SAME injected- // _session_id, so both resolve the same cursor key — i.e. enabling the- // cursor lights the very cursor the AX click drives. Mirrors the args- // the daemon injects (_session_id) for each forwarded tool call.- let session = "mcp-12345-678";- let enable_args = json!({ "enabled": true, "_session_id": session });+ // In one run, set_agent_cursor_enabled and a click(element_index) carry+ // the SAME explicit `session`, so both resolve the same cursor key —+ // enabling the cursor lights the very cursor the AX click drives.+ let session = "research-run";+ let enable_args = json!({ "enabled": true, "session": session });let ax_click_args =- json!({ "pid": 844, "window_id": 10725, "element_index": 14, "_session_id": session });+ json!({ "pid": 844, "window_id": 10725, "element_index": 14, "session": session });let enable_key = resolve_cursor_key(&enable_args);let click_key = resolve_cursor_key(&ax_click_args);assert_eq!(enable_key, session);@@ -588,23 +593,22 @@ mod tests {.map(|s| s.config.enabled).unwrap_or(true)};- assert!(read_for(&json!({ "_session_id": "sessA" })));- assert!(!read_for(&json!({ "_session_id": "sessB" })));+ assert!(read_for(&json!({ "session": "sessA" })));+ assert!(!read_for(&json!({ "session": "sessB" })));// Anonymous caller (no session) falls back to the seeded default (on).assert!(read_for(&json!({})));}#[test]- fn empty_strings_fall_through() {- // An empty cursor_id falls through to _session_id; empty session falls- // through to "default".+ fn empty_strings_fall_through_to_no_cursor() {+ // An empty `session` falls through to `cursor_id`; both empty → NO_CURSOR.assert_eq!(- resolve_cursor_key(&json!({ "cursor_id": "", "_session_id": "sess-7" })),- "sess-7"+ resolve_cursor_key(&json!({ "session": "", "cursor_id": "c1" })),+ "c1");assert_eq!(- resolve_cursor_key(&json!({ "cursor_id": "", "_session_id": "" })),- "default"+ resolve_cursor_key(&json!({ "session": "", "cursor_id": "" })),+ NO_CURSOR);}}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.rsindex 33e5c6c3fc..4b63bbeaff 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@@ -34,6 +34,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." },"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.rsindex d7fe0fa91a..5cf090e482 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@@ -49,6 +49,7 @@ fn def() -> &'static ToolDef {"type": "object","required": ["pid", "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." },"pid": { "type": "integer", "description": "Target process ID." },"window_id": {"type": "integer",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.rsindex c0b63fe4d8..ad1b3e20ad 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@@ -31,6 +31,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." },"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." },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.rsindex 318594d1f7..1750379ef6 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@@ -44,6 +44,7 @@ fn def() -> &'static ToolDef {"type": "object","required": ["pid", "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." },"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.rsindex 1d05ce2991..cb5b81c558 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@@ -353,8 +353,9 @@ pub fn register_all(registry: &mut ToolRegistry, compat: bool) {registry.register(Box::new(cua_driver_core::page::PageTool::new(Arc::new(page::MacOsPageBackend::new(state.clone())),)));- // Recording / replay tools are platform-independent — live in mcp-server.+ // Recording / replay + session-lifecycle tools are platform-independent.registry.register_recording_tools();+ registry.register_session_tools();}#[cfg(test)]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.rsindex 7807009c7c..3d14684046 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@@ -25,13 +25,18 @@ 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." },"x": { "type": "number" },"y": { "type": "number" },"cursor_id": { "type": "string", "description": "Cursor instance to move. Default: 'default'." }},"additionalProperties": false}),- read_only: false,+ // read-only: move_cursor only nudges the agent-cursor overlay, never the+ // target app — so it's safe to run concurrently. The `readOnlyHint` this+ // emits lets MCP clients (e.g. Claude Code's isConcurrencySafe) parallelize+ // cursor moves. (Mutating tools like click stay read_only:false on purpose.)+ read_only: true,destructive: false,idempotent: true,open_world: false,@@ -49,13 +54,14 @@ impl Tool for MoveCursorTool {let cursor_id = super::cursor_tools::resolve_cursor_key(&args);self.state.cursor_registry.update_position(&cursor_id, x, y);- // Drive the visual overlay for THIS session's cursor (no-op when the- // overlay is disabled). End pointing upper-left (45°) — matches Swift's- // `AgentCursor.animateAndWait(endAngleDegrees: 45)` convention.- crate::cursor::overlay::send_command(- cursor_id.clone(),- cursor_overlay::OverlayCommand::MoveTo { x, y, end_heading_radians: std::f64::consts::FRAC_PI_4 }- );+ // Drive the DRAWN cursor via the same path as click's animation. A raw+ // `MoveTo` doesn't reliably bring a brand-new session cursor on-screen —+ // it sits at the off-screen sentinel until a click seeds it, so the+ // visible cursor wouldn't move (the reported position would, but the+ // overlay wouldn't). `animate_cursor_to` seeds the sentinel on-screen+ // then glides in, identical to `click`. No-op for an empty (anonymous)+ // key or when the overlay is disabled for this cursor.+ crate::cursor::overlay::animate_cursor_to(cursor_id.clone(), x, y).await;ToolResult::text(format!("Agent cursor '{cursor_id}' moved to ({x:.1}, {y:.1})."))}}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.rsindex 745df6ad6b..e16b4b4054 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@@ -40,6 +40,7 @@ fn def() -> &'static ToolDef {"type": "object","required": ["pid", "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." },"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.rsindex d69a28e22b..cbdcca00be 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@@ -39,6 +39,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." },"pid": { "type": "integer", "description": "Target process ID." },"element_index": {"type": "integer",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.rsindex d00e1460b8..4b3dcc0467 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@@ -30,6 +30,7 @@ fn def() -> &'static ToolDef {"type": "object","required": ["pid", "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." },"pid": { "type": "integer" },"direction": {"type": "string",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.rsindex 3052aee360..1e40f4b41a 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@@ -59,6 +59,7 @@ fn def() -> &'static ToolDef {"type": "object","required": ["pid", "window_id", "element_index", "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." },"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.rsindex 5494265dd9..501a88387f 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@@ -58,6 +58,7 @@ fn def() -> &'static ToolDef {"type": "object","required": ["pid", "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." },"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/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rsindex 05a388e04d..e274baffe0 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@@ -5254,6 +5254,7 @@ pub fn build_registry(compat: bool) -> ToolRegistry {std::sync::Arc::new(super::page::WindowsPageBackend::new()),)));r.register_recording_tools();+ r.register_session_tools();r}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rsindex 465abebe6e..d8f486c30a 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rs@@ -228,5 +228,6 @@ pub fn build_registry() -> cua_driver_core::tool::ToolRegistry {r.register(Box::new(ZoomTool));r.register(Box::new(TypeTextCharsTool));r.register_recording_tools();+ r.register_session_tools();r}