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 aggregate agent session telemetry

Francesco Bonacci3a5924640738
diff --git a/docs/content/docs/reference/cua-driver/telemetry.mdx b/docs/content/docs/reference/cua-driver/telemetry.mdx
index c6b3ba9a7b..d026b1189e 100644
--- a/docs/content/docs/reference/cua-driver/telemetry.mdx
+++ b/docs/content/docs/reference/cua-driver/telemetry.mdx
@@ -48,6 +48,8 @@ Set the same environment variable in your MCP server configuration to keep the u
```bash
cua-driver telemetry inspect cua_driver_mcp_session_started --json
cua-driver telemetry inspect cua_driver_mcp_tool_completed --json
+cua-driver telemetry inspect cua_driver_agent_session_started --json
+cua-driver telemetry inspect cua_driver_agent_session_ended --json
```
## Common client event properties
@@ -62,7 +64,7 @@ Every schema-v3 client event has this fixed envelope:
| `os_major` | Major operating-system version only |
| `arch` | Bounded CPU architecture |
| `is_ci` | Whether a recognized CI environment is present |
-| `transport` | `cli`, `mcp_stdio`, `mcp_http`, or `unknown` |
+| `transport` | `cli`, `daemon`, `mcp_stdio`, `mcp_http`, or `unknown` |
| `process_session_id` | Random ID created once per process and never persisted |
| `id_persisted` | Whether the installation ID came from durable local state |
@@ -72,17 +74,22 @@ The client does not send an IP address as an event property. PostHog derives a c
## Fixed events
-| Event | Additional bounded properties |
-| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
-| `cua_driver_installation_registered` | `install_channel` |
-| `cua_driver_release_installed` | `install_channel`, `product_version` |
-| `cua_driver_mcp` | None. Transitional process-start event emitted when `cua-driver mcp` starts; `transport` is `mcp_stdio` in the common envelope. |
-| `cua_driver_serve` | None. Transitional process-start event emitted when `cua-driver serve` starts; `transport` is `cli` in the common envelope. |
-| `cua_driver_cli_completed` | Completed finite CLI outcomes: fixed `command`, `success`, `exit_class`, and `duration_bucket` |
-| `cua_driver_mcp_session_started` | normalized MCP client and protocol, capability booleans, optional reported agent context |
-| `cua_driver_mcp_tool_completed` | allowlisted tool, success, error class, duration bucket, output type, output-size bucket |
-
-The transitional `cua_driver_mcp` and `cua_driver_serve` events carry the common event properties above and no additional properties. They do not contain MCP initialize data, command arguments, or process output.
+| Event | Additional bounded properties |
+| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `cua_driver_installation_registered` | `install_channel` |
+| `cua_driver_release_installed` | `install_channel`, `product_version` |
+| `cua_driver_serve` | None. Transitional process-start event for `cua-driver serve`; `transport` is `daemon` |
+| `cua_driver_cli_completed` | Fixed `command`, allowlisted tool for `call`, `success`, `exit_class`, and `duration_bucket` |
+| `cua_driver_mcp_startup_completed` | execution path, bounded daemon state, success, duration bucket, and `execution_mode` |
+| `cua_driver_mcp_session_started` | normalized MCP client and protocol, capability booleans, optional reported agent context, and `execution_mode` |
+| `cua_driver_mcp_tool_completed` | allowlisted tool, success, error class, duration bucket, output type, output-size bucket, and `execution_mode` |
+| `cua_driver_agent_session_started` | declaration kind, revival flag, concurrent-session bucket, entry transport, and `execution_mode` |
+| `cua_driver_agent_session_ended` | end reason, duration and count buckets, success flags, feature-family flags, multi-transport flag, and `execution_mode` |
+| `cua_driver_permissions_gate_started` | missing-permission booleans |
+| `cua_driver_permissions_gate_dismissed` | missing-permission booleans and duration bucket |
+| `cua_driver_permissions_gate_completed` | missing-permission booleans, panel and dismissal flags, fixed resolution, and duration bucket |
+
+The transitional `cua_driver_serve` event carries the common event properties and no additional properties. It does not contain command arguments or process output.
The legacy `cua_driver_install` event remains part of lifetime registration dashboards so existing installations are not registered a second time.
@@ -105,13 +112,23 @@ An MCP host can explicitly report agent context in the initialize request:
}
```
-These values are self-reported and normalized through allowlists. Unknown values become `custom` or `unknown`. Cua Driver does not infer a model from the MCP client name, does not use MCP Sampling to identify the parent model, and does not collect the complete initialize payload. This session event currently covers stdio MCP only; HTTP session telemetry remains disabled until Cua Driver implements explicit HTTP session semantics.
+These values are self-reported and normalized through allowlists. Unknown values become `custom` or `unknown`. Cua Driver does not infer a model from the MCP client name, does not use MCP Sampling to identify the parent model, and does not collect the complete initialize payload. Stdio emits once per process. A long-lived HTTP process emits once per normalized client category, so the event measures HTTP client-category adoption rather than every connection.
+
+## 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. 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.
+
+Computer-action success covers fixed pointer and keyboard capabilities, app launch and kill, window activation, and state-changing `page` operations. State reads, screenshots, health checks, update checks, and session lifecycle tools do not count as computer actions.
## Data that is never collected
Routine telemetry excludes task text, prompts, tool arguments, tool response bodies, typed text, screenshots, accessibility trees, window titles, application names, file paths, URLs, arbitrary MCP metadata, and raw error messages.
-Tool-completion events retain only coarse result shape: text, image, mixed, empty, or unknown; a size bucket; a duration bucket; and a fixed error class. The content itself never crosses the telemetry observer boundary.
+Tool-completion events retain only coarse result shape: text, image, mixed, empty, or unknown; a size bucket; a duration bucket; and a fixed error class. The content itself never crosses the telemetry observer boundary. A proxy and daemon negotiate one completion-event owner. Mixed-version pairs retain proxy ownership, which prevents duplicate events during upgrades.
## Region and deletion controls
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs
index 17b317321a..7fc9391464 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
@@ -226,6 +226,11 @@ pub async fn run(registry: Arc<ToolRegistry>) -> anyhow::Result<()> {
let initialize_metadata = (!session_observed)
.then(|| req.initialize_metadata())
.flatten();
+ let session_context = session_tool_context(
+ &req,
+ &registry,
+ crate::session::SessionTransport::McpStdio,
+ );
let tool_timer = tool_observation_timer(
&req,
|name| name == "type_text_chars" || registry.get_def(name).is_some(),
@@ -241,7 +246,11 @@ pub async fn run(registry: Arc<ToolRegistry>) -> anyhow::Result<()> {
session_observed = true;
}
if let Some(timer) = tool_timer {
- notify_tool_completed(timer.finish(&response));
+ let outcome = timer.finish(&response);
+ if let Some(context) = session_context {
+ context.complete(&outcome);
+ }
+ notify_tool_completed(outcome);
}
response
}
@@ -293,6 +302,22 @@ pub fn tool_observation_timer(
))
}
+/// Build a private aggregate-session context from a valid, known tool call.
+/// Only the public `session` argument is considered; reserved fallback keys
+/// and all other arguments remain outside the observer seam.
+pub fn session_tool_context(
+ req: &Request,
+ registry: &ToolRegistry,
+ transport: crate::session::SessionTransport,
+) -> Option<crate::session::SessionToolContext> {
+ if req.method != "tools/call" {
+ return None;
+ }
+ let call = req.tool_call().ok()?;
+ let known_tool = call.name == "type_text_chars" || registry.get_def(&call.name).is_some();
+ crate::session::begin_tool_call(&call.name, &call.args, known_tool, transport)
+}
+
fn notify_session_started(metadata: InitializeMetadata) {
if let Some(observer) = STDIO_OBSERVER.get() {
observer.on_session_started(metadata);
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 b9a66e4f63..2b894de3eb 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
@@ -19,11 +19,86 @@
//! reverse coupling from core into the platform crates.
use std::collections::{HashMap, HashSet};
-use std::sync::{Mutex, OnceLock};
+use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};
type SessionEndHook = Box<dyn Fn(&str) + Send + Sync>;
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SessionDeclaration {
+ StartSession,
+ ImplicitFirstAction,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SessionEndReason {
+ Explicit,
+ IdleTimeout,
+ ProcessExit,
+ Unknown,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SessionTransport {
+ Cli,
+ Daemon,
+ McpStdio,
+ McpHttp,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct SessionStartObservation {
+ pub declaration: SessionDeclaration,
+ pub revived: bool,
+ pub transport: SessionTransport,
+}
+
+/// Process-local sink for bounded session telemetry.
+///
+/// `session_id` is supplied only so an observer can update private in-memory
+/// state. Implementations must never serialize, hash, log, or otherwise export
+/// it. The observation structs and completion outcome contain the complete
+/// allowlisted telemetry boundary.
+pub trait SessionObserver: Send + Sync + 'static {
+ fn on_session_started(&self, session_id: &str, observation: SessionStartObservation);
+ fn on_tool_completed(
+ &self,
+ session_id: &str,
+ transport: SessionTransport,
+ computer_action: bool,
+ outcome: &crate::server::ToolCompletionObservation,
+ );
+ fn on_session_ended(&self, session_id: &str, reason: SessionEndReason);
+}
+
+static SESSION_OBSERVER: OnceLock<Arc<dyn SessionObserver>> = OnceLock::new();
+
+pub fn set_session_observer(observer: Arc<dyn SessionObserver>) -> bool {
+ SESSION_OBSERVER.set(observer).is_ok()
+}
+
+/// 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.
+pub struct SessionToolContext {
+ session_id: String,
+ transport: SessionTransport,
+ computer_action: bool,
+}
+
+impl SessionToolContext {
+ pub fn complete(self, outcome: &crate::server::ToolCompletionObservation) {
+ if let Some(observer) = SESSION_OBSERVER.get() {
+ observer.on_tool_completed(
+ &self.session_id,
+ self.transport,
+ self.computer_action,
+ outcome,
+ );
+ }
+ }
+}
+
static SESSION_END_HOOKS: OnceLock<Mutex<Vec<SessionEndHook>>> = OnceLock::new();
/// Last-activity timestamp per live session id. A session is "touched" every
@@ -44,6 +119,78 @@ fn is_trackable(id: &str) -> bool {
!id.is_empty() && id != "default"
}
+fn is_computer_action(tool_name: &str, args: &serde_json::Value) -> bool {
+ if tool_name == "page" {
+ return matches!(
+ args.get("action").and_then(serde_json::Value::as_str),
+ Some(
+ "click_element"
+ | "insert_text"
+ | "type_keystrokes"
+ | "enable_javascript_apple_events"
+ )
+ );
+ }
+ crate::tool::default_capabilities_for(tool_name)
+ .iter()
+ .any(|capability| {
+ capability.starts_with("input.pointer.")
+ || capability.starts_with("input.keyboard.")
+ || matches!(
+ capability.as_str(),
+ "app.launch" | "app.kill" | "window.activate"
+ )
+ })
+}
+
+/// Begin bounded observation for a known tool call carrying a public,
+/// caller-declared `session`. Reserved `_session_id` fallbacks and anonymous
+/// identities are deliberately ignored.
+pub fn begin_tool_call(
+ tool_name: &str,
+ args: &serde_json::Value,
+ known_tool: bool,
+ transport: SessionTransport,
+) -> Option<SessionToolContext> {
+ if !known_tool {
+ return None;
+ }
+ let session_id = args
+ .get("session")
+ .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 revived = is_start && is_session_ended(session_id);
+ if is_session_ended(session_id) && !is_start {
+ return None;
+ }
+
+ touch_session(session_id);
+ if !is_end {
+ if let Some(observer) = SESSION_OBSERVER.get() {
+ observer.on_session_started(
+ session_id,
+ SessionStartObservation {
+ declaration: if is_start {
+ SessionDeclaration::StartSession
+ } else {
+ SessionDeclaration::ImplicitFirstAction
+ },
+ revived,
+ transport,
+ },
+ );
+ }
+ }
+
+ SESSION_OBSERVER.get().map(|_| SessionToolContext {
+ session_id: session_id.to_owned(),
+ transport,
+ computer_action: is_computer_action(tool_name, args),
+ })
+}
+
/// 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
@@ -76,20 +223,23 @@ pub fn register_session_end_hook(hook: impl Fn(&str) + Send + Sync + 'static) {
/// arm. Idempotent: the FIRST fire for a given `session_id` runs every hook; any
/// later fire for the same id is a no-op. This dedupes the EOF path against a
/// stray legacy `session_end` (mixed-version rollout) so cursor-remove +
-/// recording-stop run exactly once. No-op when no hooks are registered.
-pub fn fire_session_end(session_id: &str) {
+/// recording-stop run exactly once. Returns `true` only for that first fire;
+/// 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; // already ended — idempotent no-op.
+ return false; // already ended — idempotent no-op.
}
}
for hook in hooks().lock().unwrap().iter() {
hook(session_id);
}
+ true
}
/// Whether `fire_session_end` has already run for this `session_id`. The
@@ -136,11 +286,19 @@ pub fn touch_session(session_id: &str) {
/// (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) {
+ end_session_with_reason(session_id, SessionEndReason::Explicit);
+}
+
+fn end_session_with_reason(session_id: &str, reason: SessionEndReason) {
if !is_trackable(session_id) {
return;
}
activity().lock().unwrap().remove(session_id);
- fire_session_end(session_id);
+ if fire_session_end(session_id) {
+ if let Some(observer) = SESSION_OBSERVER.get() {
+ observer.on_session_ended(session_id, reason);
+ }
+ }
}
/// End every session whose last activity is older than `ttl`, returning the ids
@@ -159,7 +317,7 @@ pub fn evict_idle(ttl: Duration) -> Vec<String> {
.collect()
};
for id in &stale {
- end_session(id);
+ end_session_with_reason(id, SessionEndReason::IdleTimeout);
}
stale
}
@@ -175,6 +333,40 @@ mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
+ #[derive(Default)]
+ struct ProbeObserver {
+ starts: Mutex<Vec<(String, SessionStartObservation)>>,
+ ends: Mutex<Vec<(String, SessionEndReason)>>,
+ }
+
+ impl SessionObserver for ProbeObserver {
+ fn on_session_started(&self, id: &str, observation: SessionStartObservation) {
+ self.starts.lock().unwrap().push((id.to_owned(), observation));
+ }
+ fn on_tool_completed(
+ &self,
+ _: &str,
+ _: SessionTransport,
+ _: bool,
+ _: &crate::server::ToolCompletionObservation,
+ ) {
+ }
+ fn on_session_ended(&self, id: &str, reason: SessionEndReason) {
+ self.ends.lock().unwrap().push((id.to_owned(), reason));
+ }
+ }
+
+ fn probe_observer() -> Arc<ProbeObserver> {
+ static PROBE: OnceLock<Arc<ProbeObserver>> = OnceLock::new();
+ PROBE
+ .get_or_init(|| {
+ let probe = Arc::new(ProbeObserver::default());
+ let _ = set_session_observer(probe.clone());
+ probe
+ })
+ .clone()
+ }
+
#[test]
fn fire_session_end_is_idempotent_per_id() {
// Distinct, test-local ids so we don't collide with other tests that
@@ -255,4 +447,136 @@ mod tests {
assert!(!revive_session("default"));
assert!(!revive_session(""));
}
+
+ #[test]
+ fn tool_context_requires_a_public_session_and_uses_fixed_action_classes() {
+ let _ = probe_observer();
+ assert!(begin_tool_call(
+ "click",
+ &serde_json::json!({"_session_id": "private-fallback"}),
+ true,
+ SessionTransport::McpStdio,
+ )
+ .is_none());
+ assert!(begin_tool_call(
+ "click",
+ &serde_json::json!({"session": "default"}),
+ true,
+ SessionTransport::McpStdio,
+ )
+ .is_none());
+
+ let pointer = begin_tool_call(
+ "click",
+ &serde_json::json!({"session": "test-action-pointer-AB12"}),
+ true,
+ SessionTransport::McpStdio,
+ )
+ .unwrap();
+ assert!(pointer.computer_action);
+
+ let page_write = begin_tool_call(
+ "page",
+ &serde_json::json!({
+ "session": "test-action-page-write-CD34",
+ "action": "insert_text",
+ "text": "not retained"
+ }),
+ true,
+ SessionTransport::McpHttp,
+ )
+ .unwrap();
+ assert!(page_write.computer_action);
+ assert!(!format!("{}", page_write.computer_action).contains("not retained"));
+
+ let page_read = begin_tool_call(
+ "page",
+ &serde_json::json!({
+ "session": "test-action-page-read-EF56",
+ "action": "query_dom",
+ "selector": "private selector"
+ }),
+ true,
+ SessionTransport::McpHttp,
+ )
+ .unwrap();
+ assert!(!page_read.computer_action);
+
+ let state_read = begin_tool_call(
+ "get_window_state",
+ &serde_json::json!({"session": "test-action-read-GH78"}),
+ true,
+ SessionTransport::Daemon,
+ )
+ .unwrap();
+ assert!(!state_read.computer_action);
+ }
+
+ #[test]
+ fn observer_distinguishes_explicit_idle_revival_and_control_cleanup() {
+ let probe = probe_observer();
+ let explicit = "test-observer-explicit-IJ90";
+ begin_tool_call(
+ "start_session",
+ &serde_json::json!({"session": explicit}),
+ true,
+ SessionTransport::McpStdio,
+ )
+ .unwrap();
+ end_session(explicit);
+
+ let idle = "test-observer-idle-KL12";
+ begin_tool_call(
+ "click",
+ &serde_json::json!({"session": idle}),
+ true,
+ SessionTransport::McpHttp,
+ )
+ .unwrap();
+ end_session_with_reason(idle, SessionEndReason::IdleTimeout);
+
+ let revived = "test-observer-revived-MN34";
+ touch_session(revived);
+ end_session(revived);
+ begin_tool_call(
+ "start_session",
+ &serde_json::json!({"session": revived}),
+ true,
+ SessionTransport::Daemon,
+ )
+ .unwrap();
+
+ let control = "test-observer-control-OP56";
+ begin_tool_call(
+ "click",
+ &serde_json::json!({"session": control}),
+ true,
+ SessionTransport::McpStdio,
+ )
+ .unwrap();
+ fire_session_end(control);
+
+ let starts = probe.starts.lock().unwrap();
+ assert!(starts.iter().any(|(id, observation)| {
+ id == explicit
+ && observation.declaration == SessionDeclaration::StartSession
+ && !observation.revived
+ }));
+ assert!(starts.iter().any(|(id, observation)| {
+ id == idle
+ && observation.declaration == SessionDeclaration::ImplicitFirstAction
+ && observation.transport == SessionTransport::McpHttp
+ }));
+ assert!(starts.iter().any(|(id, observation)| id == revived && observation.revived));
+ drop(starts);
+
+ let ends = probe.ends.lock().unwrap();
+ assert!(ends.iter().any(|(id, reason)| {
+ id == explicit && *reason == SessionEndReason::Explicit
+ }));
+ assert!(ends.iter().any(|(id, reason)| {
+ id == idle && *reason == SessionEndReason::IdleTimeout
+ }));
+ assert!(!ends.iter().any(|(id, _)| id == control));
+ }
}
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 1ffc13b347..d4756d01cf 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
@@ -1553,11 +1553,31 @@ pub fn run_call(
.expect("tokio runtime");
let args = json_args.unwrap_or(serde_json::Value::Object(serde_json::Map::new()));
+ let session_context = cua_driver_core::session::begin_tool_call(
+ tool,
+ &args,
+ true,
+ cua_driver_core::session::SessionTransport::Cli,
+ );
+ let observation_timer = cua_driver_core::server::ToolObservationTimer::start(
+ tool.to_owned(),
+ true,
+ true,
+ cua_driver_core::server::StdioExecutionPath::InProcess,
+ );
let tool_name = tool.to_string();
let out_path = screenshot_out_file;
let is_error = rt.block_on(async move {
let result = registry.invoke(&tool_name, args).await;
let is_err = result.is_error.unwrap_or(false);
+ if let Ok(value) = serde_json::to_value(&result) {
+ let response = cua_driver_core::protocol::Response::ok(serde_json::Value::Null, value);
+ let outcome = observation_timer.finish(&response);
+ if let Some(context) = session_context {
+ context.complete(&outcome);
+ }
+ crate::telemetry::capture_tool_completed(outcome, crate::telemetry::Transport::Cli);
+ }
// Emit content.
let mut has_printed = false;
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 1108d515fb..8b49d049b2 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
@@ -22,7 +22,9 @@ use std::net::SocketAddr;
use std::sync::Arc;
use cua_driver_core::protocol::{Request, Response};
-use cua_driver_core::server::{handle_request, tool_observation_timer, StdioExecutionPath};
+use cua_driver_core::server::{
+ handle_request, session_tool_context, tool_observation_timer, StdioExecutionPath,
+};
use cua_driver_core::tool::ToolRegistry;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
@@ -113,15 +115,21 @@ async fn dispatch(body: &[u8], registry: &Arc<ToolRegistry>) -> Option<String> {
return None; // notification
}
let initialize_metadata = req.initialize_metadata();
+ let session_context = session_tool_context(
+ &req,
+ registry,
+ cua_driver_core::session::SessionTransport::McpHttp,
+ );
let id = req.id.clone().unwrap_or(serde_json::Value::Null);
apply_session_identity(&mut req);
let timer = http_tool_observation_timer(&req, registry);
let response = handle_request(req, id, registry).await;
if let Some(timer) = timer {
- crate::telemetry::capture_tool_completed(
- timer.finish(&response),
- crate::telemetry::Transport::McpHttp,
- );
+ let outcome = timer.finish(&response);
+ if let Some(context) = session_context {
+ context.complete(&outcome);
+ }
+ crate::telemetry::capture_tool_completed(outcome, crate::telemetry::Transport::McpHttp);
}
if let Some(metadata) = initialize_metadata {
crate::telemetry::capture_mcp_session_started(
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 e05916c3e3..4013538a77 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs
@@ -135,6 +135,19 @@ pub async fn run_proxy(socket_path: String) -> anyhow::Result<()> {
let initialize_metadata = (!session_observed)
.then(|| req.initialize_metadata())
.flatten();
+ let session_context = (!daemon_observes_tool_calls)
+ .then(|| {
+ req.tool_call().ok().and_then(|call| {
+ let known_tool = proxy_knows_tool(&cached_tools_list, &call.name);
+ cua_driver_core::session::begin_tool_call(
+ &call.name,
+ &call.args,
+ known_tool,
+ cua_driver_core::session::SessionTransport::McpStdio,
+ )
+ })
+ })
+ .flatten();
let tool_timer = (!daemon_observes_tool_calls)
.then(|| {
tool_observation_timer(
@@ -159,7 +172,11 @@ pub async fn run_proxy(socket_path: String) -> anyhow::Result<()> {
session_observed = true;
}
if let Some(timer) = tool_timer {
- observe_proxy_tool_completed(timer.finish(&response));
+ let outcome = timer.finish(&response);
+ if let Some(context) = session_context {
+ context.complete(&outcome);
+ }
+ observe_proxy_tool_completed(outcome);
}
response
}
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 b145f05e62..223fda49ea 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
@@ -337,13 +337,18 @@ fn observe_daemon_result(
cua_driver_core::server::ToolObservationTimer,
crate::telemetry::Transport,
)>,
+ session_context: Option<cua_driver_core::session::SessionToolContext>,
result: serde_json::Value,
) -> serde_json::Value {
let Some((timer, transport)) = observation else {
return result;
};
let response = cua_driver_core::protocol::Response::ok(serde_json::Value::Null, result);
- crate::telemetry::capture_tool_completed(timer.finish(&response), transport);
+ let outcome = timer.finish(&response);
+ if let Some(context) = session_context {
+ context.complete(&outcome);
+ }
+ crate::telemetry::capture_tool_completed(outcome, transport);
match response.body {
cua_driver_core::protocol::ResponseBody::Result { result } => result,
cua_driver_core::protocol::ResponseBody::Error { .. } => unreachable!("constructed ok response"),
@@ -421,6 +426,24 @@ async fn invoke_daemon_tool(
return DaemonResponse::err(format!("Unknown tool: {tool_name}"), 64);
}
+ let session_context = observation_transport.and_then(|transport| {
+ let transport = match transport {
+ crate::telemetry::Transport::McpStdio => {
+ cua_driver_core::session::SessionTransport::McpStdio
+ }
+ crate::telemetry::Transport::McpHttp => {
+ cua_driver_core::session::SessionTransport::McpHttp
+ }
+ crate::telemetry::Transport::Cli => {
+ cua_driver_core::session::SessionTransport::Cli
+ }
+ crate::telemetry::Transport::Daemon => {
+ cua_driver_core::session::SessionTransport::Daemon
+ }
+ };
+ cua_driver_core::session::begin_tool_call(&tool_name, &args, true, transport)
+ });
+
let result = registry.invoke(&tool_name, args).await;
let is_error = result.is_error.unwrap_or(false);
let content: Vec<serde_json::Value> = result
@@ -442,7 +465,7 @@ async fn invoke_daemon_tool(
if let Some(structured) = result.structured_content {
result_value["structuredContent"] = structured;
}
- DaemonResponse::ok(observe_daemon_result(observation, result_value))
+ DaemonResponse::ok(observe_daemon_result(observation, session_context, result_value))
}
// ── Client ────────────────────────────────────────────────────────────────────
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 35f7636c4f..a68087e33e 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs
@@ -13,7 +13,7 @@
use serde::Serialize;
use serde_json::{Map, Value};
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use std::fs::{File, OpenOptions, TryLockError};
use std::io::Write;
use std::path::{Path, PathBuf};
@@ -61,6 +61,8 @@ pub mod event {
pub const MCP_SESSION_STARTED: &str = "cua_driver_mcp_session_started";
pub const MCP_TOOL_COMPLETED: &str = "cua_driver_mcp_tool_completed";
pub const MCP_STARTUP_COMPLETED: &str = "cua_driver_mcp_startup_completed";
+ pub const AGENT_SESSION_STARTED: &str = "cua_driver_agent_session_started";
+ pub const AGENT_SESSION_ENDED: &str = "cua_driver_agent_session_ended";
pub const PERMISSIONS_GATE_STARTED: &str = "cua_driver_permissions_gate_started";
pub const PERMISSIONS_GATE_DISMISSED: &str = "cua_driver_permissions_gate_dismissed";
pub const PERMISSIONS_GATE_COMPLETED: &str = "cua_driver_permissions_gate_completed";
@@ -74,6 +76,8 @@ const INSPECTABLE_EVENTS: &[&str] = &[
event::MCP_SESSION_STARTED,
event::MCP_TOOL_COMPLETED,
event::MCP_STARTUP_COMPLETED,
+ event::AGENT_SESSION_STARTED,
+ event::AGENT_SESSION_ENDED,
event::PERMISSIONS_GATE_STARTED,
event::PERMISSIONS_GATE_DISMISSED,
event::PERMISSIONS_GATE_COMPLETED,
@@ -254,6 +258,28 @@ pub fn inspect_event(event_name: &str) -> Result<Value, String> {
("duration_bucket", Value::String("lt_100ms".into())),
("execution_mode", Value::String(execution_mode().into())),
]),
+ event::AGENT_SESSION_STARTED => bounded_properties(&[
+ ("declaration", Value::String("start_session".into())),
+ ("revived", Value::Bool(false)),
+ ("concurrent_sessions_bucket", Value::String("1".into())),
+ ("entry_transport", Value::String("mcp_stdio".into())),
+ ("execution_mode", Value::String(execution_mode().into())),
+ ]),
+ event::AGENT_SESSION_ENDED => bounded_properties(&[
+ ("end_reason", Value::String("explicit".into())),
+ ("duration_bucket", Value::String("lt_10s".into())),
+ ("tool_count_bucket", Value::String("1_4".into())),
+ ("computer_action_count_bucket", Value::String("1_4".into())),
+ ("error_count_bucket", Value::String("0".into())),
+ ("had_successful_tool", Value::Bool(true)),
+ ("had_successful_computer_action", Value::Bool(true)),
+ ("used_page", Value::Bool(false)),
+ ("used_cursor_tools", Value::Bool(false)),
+ ("used_recording", Value::Bool(false)),
+ ("used_config_write", Value::Bool(false)),
+ ("observed_multiple_transports", Value::Bool(false)),
+ ("execution_mode", Value::String(execution_mode().into())),
+ ]),
event::PERMISSIONS_GATE_STARTED => bounded_properties(&[
("missing_accessibility", Value::Bool(true)),
("missing_screen_recording", Value::Bool(true)),
@@ -274,7 +300,11 @@ pub fn inspect_event(event_name: &str) -> Result<Value, String> {
_ => Map::new(),
};
let transport = match event_name {
- event::MCP_SESSION_STARTED | event::MCP_TOOL_COMPLETED | event::MCP_STARTUP_COMPLETED => {
+ event::MCP_SESSION_STARTED
+ | event::MCP_TOOL_COMPLETED
+ | event::MCP_STARTUP_COMPLETED
+ | event::AGENT_SESSION_STARTED
+ | event::AGENT_SESSION_ENDED => {
Transport::McpStdio
}
event::SERVE_START_LEGACY
@@ -296,6 +326,7 @@ pub fn capture_start(event_name: &'static str, transport: Transport) {
pub fn register_stdio_observer() {
let _ = cua_driver_core::server::set_stdio_observer(Arc::new(TelemetryObserver));
+ let _ = cua_driver_core::session::set_session_observer(Arc::new(TelemetryObserver));
}
fn execution_mode() -> &'static str {
@@ -318,6 +349,244 @@ impl cua_driver_core::server::StdioObserver for TelemetryObserver {
}
}
+const MAX_TRACKED_AGENT_SESSIONS: usize = 256;
+static AGENT_SESSIONS: OnceLock<Mutex<HashMap<String, AgentSessionState>>> = OnceLock::new();
+
+struct AgentSessionState {
+ started: std::time::Instant,
+ entry_transport: Transport,
+ transport_bits: u8,
+ tool_count: u64,
+ computer_action_count: u64,
+ error_count: u64,
+ had_successful_tool: bool,
+ had_successful_computer_action: bool,
+ used_page: bool,
+ used_cursor_tools: bool,
+ used_recording: bool,
+ used_config_write: bool,
+}
+
+impl AgentSessionState {
+ fn new(entry_transport: Transport) -> Self {
+ Self {
+ started: std::time::Instant::now(),
+ entry_transport,
+ transport_bits: transport_bit(entry_transport),
+ tool_count: 0,
+ computer_action_count: 0,
+ error_count: 0,
+ had_successful_tool: false,
+ had_successful_computer_action: false,
+ used_page: false,
+ used_cursor_tools: false,
+ used_recording: false,
+ used_config_write: false,
+ }
+ }
+
+ fn observe(
+ &mut self,
+ transport: Transport,
+ computer_action: bool,
+ outcome: &cua_driver_core::server::ToolCompletionObservation,
+ ) {
+ self.transport_bits |= transport_bit(transport);
+ let tool_name = outcome.tool_name.as_str();
+ if matches!(tool_name, "start_session" | "end_session") {
+ return;
+ }
+ self.tool_count = self.tool_count.saturating_add(1);
+ self.computer_action_count = self
+ .computer_action_count
+ .saturating_add(u64::from(computer_action));
+ self.error_count = self.error_count.saturating_add(u64::from(!outcome.success));
+ self.had_successful_tool |= outcome.success;
+ self.had_successful_computer_action |= outcome.success && computer_action;
+ self.used_page |= tool_name == "page";
+ self.used_cursor_tools |= matches!(
+ tool_name,
+ "set_agent_cursor_enabled"
+ | "set_agent_cursor_motion"
+ | "set_agent_cursor_style"
+ | "get_agent_cursor_state"
+ );
+ self.used_recording |= matches!(
+ tool_name,
+ "start_recording" | "stop_recording" | "replay_trajectory"
+ );
+ self.used_config_write |= tool_name == "set_config";
+ }
+
+ fn ended_properties(
+ &self,
+ reason: cua_driver_core::session::SessionEndReason,
+ ) -> Map<String, Value> {
+ use cua_driver_core::session::SessionEndReason;
+ let end_reason = match reason {
+ SessionEndReason::Explicit => "explicit",
+ SessionEndReason::IdleTimeout => "idle_timeout",
+ SessionEndReason::ProcessExit => "process_exit",
+ SessionEndReason::Unknown => "unknown",
+ };
+ bounded_properties(&[
+ ("end_reason", Value::String(end_reason.into())),
+ ("duration_bucket", Value::String(agent_session_duration_bucket(self.started.elapsed()).into())),
+ ("tool_count_bucket", Value::String(agent_session_count_bucket(self.tool_count).into())),
+ ("computer_action_count_bucket", Value::String(agent_session_count_bucket(self.computer_action_count).into())),
+ ("error_count_bucket", Value::String(agent_session_error_bucket(self.error_count).into())),
+ ("had_successful_tool", Value::Bool(self.had_successful_tool)),
+ ("had_successful_computer_action", Value::Bool(self.had_successful_computer_action)),
+ ("used_page", Value::Bool(self.used_page)),
+ ("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)),
+ ("observed_multiple_transports", Value::Bool(self.transport_bits.count_ones() > 1)),
+ ("execution_mode", Value::String(execution_mode().into())),
+ ])
+ }
+}
+
+fn transport_bit(transport: Transport) -> u8 {
+ match transport {
+ Transport::Cli => 1,
+ Transport::Daemon => 2,
+ Transport::McpStdio => 4,
+ Transport::McpHttp => 8,
+ }
+}
+
+fn session_transport(transport: cua_driver_core::session::SessionTransport) -> Transport {
+ match transport {
+ cua_driver_core::session::SessionTransport::Cli => Transport::Cli,
+ cua_driver_core::session::SessionTransport::Daemon => Transport::Daemon,
+ cua_driver_core::session::SessionTransport::McpStdio => Transport::McpStdio,
+ cua_driver_core::session::SessionTransport::McpHttp => Transport::McpHttp,
+ }
+}
+
+fn concurrent_sessions_bucket(count: usize) -> &'static str {
+ match count {
+ 0 | 1 => "1",
+ 2 => "2",
+ 3..=5 => "3_5",
+ _ => "gte_6",
+ }
+}
+
+fn agent_session_duration_bucket(duration: Duration) -> &'static str {
+ match duration.as_secs() {
+ 0..=9 => "lt_10s",
+ 10..=59 => "10_59s",
+ 60..=299 => "1_4min",
+ 300..=1799 => "5_29min",
+ _ => "gte_30min",
+ }
+}
+
+fn agent_session_count_bucket(count: u64) -> &'static str {
+ match count {
+ 0 => "0",
+ 1..=4 => "1_4",
+ 5..=19 => "5_19",
+ 20..=99 => "20_99",
+ _ => "gte_100",
+ }
+}
+
+fn agent_session_error_bucket(count: u64) -> &'static str {
+ match count {
+ 0 => "0",
+ 1 => "1",
+ 2..=4 => "2_4",
+ _ => "gte_5",
+ }
+}
+
+impl cua_driver_core::session::SessionObserver for TelemetryObserver {
+ fn on_session_started(
+ &self,
+ session_id: &str,
+ observation: cua_driver_core::session::SessionStartObservation,
+ ) {
+ let sessions = AGENT_SESSIONS.get_or_init(|| Mutex::new(HashMap::new()));
+ if !is_enabled() {
+ sessions.lock().unwrap().remove(session_id);
+ return;
+ }
+ let transport = session_transport(observation.transport);
+ let concurrent = {
+ let mut sessions = sessions.lock().unwrap();
+ if let Some(existing) = sessions.get_mut(session_id) {
+ existing.transport_bits |= transport_bit(transport);
+ return;
+ }
+ if sessions.len() >= MAX_TRACKED_AGENT_SESSIONS {
+ return;
+ }
+ sessions.insert(session_id.to_owned(), AgentSessionState::new(transport));
+ sessions.len()
+ };
+ let declaration = match observation.declaration {
+ cua_driver_core::session::SessionDeclaration::StartSession => "start_session",
+ cua_driver_core::session::SessionDeclaration::ImplicitFirstAction => {
+ "implicit_first_action"
+ }
+ };
+ capture_bounded(
+ event::AGENT_SESSION_STARTED,
+ bounded_properties(&[
+ ("declaration", Value::String(declaration.into())),
+ ("revived", Value::Bool(observation.revived)),
+ ("concurrent_sessions_bucket", Value::String(concurrent_sessions_bucket(concurrent).into())),
+ ("entry_transport", Value::String(transport.as_str().into())),
+ ("execution_mode", Value::String(execution_mode().into())),
+ ]),
+ transport,
+ );
+ }
+
+ fn on_tool_completed(
+ &self,
+ session_id: &str,
+ transport: cua_driver_core::session::SessionTransport,
+ computer_action: bool,
+ outcome: &cua_driver_core::server::ToolCompletionObservation,
+ ) {
+ let sessions = AGENT_SESSIONS.get_or_init(|| Mutex::new(HashMap::new()));
+ let mut sessions = sessions.lock().unwrap();
+ if !is_enabled() {
+ sessions.remove(session_id);
+ return;
+ }
+ if let Some(state) = sessions.get_mut(session_id) {
+ state.observe(session_transport(transport), computer_action, outcome);
+ }
+ }
+
+ fn on_session_ended(
+ &self,
+ session_id: &str,
+ reason: cua_driver_core::session::SessionEndReason,
+ ) {
+ let state = AGENT_SESSIONS
+ .get_or_init(|| Mutex::new(HashMap::new()))
+ .lock()
+ .unwrap()
+ .remove(session_id);
+ if !is_enabled() {
+ return;
+ }
+ let Some(state) = state else { return; };
+ let transport = state.entry_transport;
+ capture_bounded(
+ event::AGENT_SESSION_ENDED,
+ state.ended_properties(reason),
+ transport,
+ );
+ }
+}
+
static MCP_SESSION_OBSERVED: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
fn mcp_session_observation_key(transport: Transport, mcp_client: &str) -> String {
@@ -1971,6 +2240,151 @@ mod tests {
);
}
+ #[test]
+ fn execution_mode_requires_the_exact_embedded_sentinel() {
+ let _guard = ENV_LOCK.lock().unwrap();
+ let name = cua_driver_core::EMBEDDED_ENV;
+ let original = std::env::var_os(name);
+ unsafe {
+ std::env::remove_var(name);
+ }
+ assert_eq!(execution_mode(), "standalone");
+ unsafe {
+ std::env::set_var(name, "1");
+ }
+ assert_eq!(execution_mode(), "embedded");
+ unsafe {
+ std::env::set_var(name, "true");
+ }
+ assert_eq!(execution_mode(), "standalone");
+ unsafe {
+ match original {
+ Some(value) => std::env::set_var(name, value),
+ None => std::env::remove_var(name),
+ }
+ }
+ }
+
+ #[test]
+ fn agent_session_aggregate_is_bounded_content_free_and_multi_transport() {
+ use cua_driver_core::server::{
+ DurationBucket, OutputSizeBucket, OutputType, ToolCompletionObservation,
+ ToolErrorClass,
+ };
+
+ let mut state = AgentSessionState::new(Transport::McpStdio);
+ state.started = std::time::Instant::now() - Duration::from_secs(75);
+ state.observe(
+ Transport::McpHttp,
+ true,
+ &ToolCompletionObservation {
+ tool_name: "click".into(),
+ success: true,
+ error_class: ToolErrorClass::None,
+ duration_bucket: DurationBucket::Under10Ms,
+ output_type: OutputType::Text,
+ output_size_bucket: OutputSizeBucket::Under1KiB,
+ },
+ );
+ state.observe(
+ Transport::McpHttp,
+ false,
+ &ToolCompletionObservation {
+ tool_name: "page".into(),
+ success: false,
+ error_class: ToolErrorClass::InternalError,
+ duration_bucket: DurationBucket::Ms50To249,
+ output_type: OutputType::Empty,
+ output_size_bucket: OutputSizeBucket::Empty,
+ },
+ );
+ let properties = state.ended_properties(
+ cua_driver_core::session::SessionEndReason::Explicit,
+ );
+ assert_eq!(properties["duration_bucket"], "1_4min");
+ assert_eq!(properties["tool_count_bucket"], "1_4");
+ assert_eq!(properties["computer_action_count_bucket"], "1_4");
+ assert_eq!(properties["error_count_bucket"], "1");
+ assert_eq!(properties["had_successful_tool"], true);
+ assert_eq!(properties["had_successful_computer_action"], true);
+ assert_eq!(properties["used_page"], true);
+ assert_eq!(properties["observed_multiple_transports"], true);
+
+ let serialized = serde_json::to_string(&properties).unwrap().to_ascii_lowercase();
+ for forbidden in [
+ "private-session-id",
+ "arguments",
+ "selector",
+ "typed_text",
+ "screenshot",
+ "window_title",
+ "file_path",
+ "raw_error",
+ ] {
+ assert!(!serialized.contains(forbidden), "aggregate contains {forbidden}: {serialized}");
+ }
+ }
+
+ #[test]
+ fn agent_session_buckets_have_fixed_boundaries() {
+ for (count, expected) in [
+ (0, "0"), (1, "1_4"), (4, "1_4"), (5, "5_19"),
+ (19, "5_19"), (20, "20_99"), (99, "20_99"), (100, "gte_100"),
+ ] {
+ assert_eq!(agent_session_count_bucket(count), expected);
+ }
+ for (count, expected) in [
+ (0, "0"), (1, "1"), (2, "2_4"), (4, "2_4"), (5, "gte_5"),
+ ] {
+ assert_eq!(agent_session_error_bucket(count), expected);
+ }
+ }
+
+ #[test]
+ fn agent_session_inspect_samples_expose_only_the_contract() {
+ for event_name in [event::AGENT_SESSION_STARTED, event::AGENT_SESSION_ENDED] {
+ let payload = inspect_event(event_name).unwrap();
+ assert_eq!(payload["properties"]["telemetry_schema_version"], 3);
+ let properties = payload["properties"].as_object().unwrap();
+ for forbidden_key in ["session", "session_id", "agent_session_id", "cursor_id"] {
+ assert!(!properties.contains_key(forbidden_key));
+ }
+ let serialized = serde_json::to_string(&payload).unwrap().to_ascii_lowercase();
+ for forbidden in [
+ "arguments", "result_text", "file_path", "socket", "raw_error", "$ip",
+ ] {
+ assert!(!serialized.contains(forbidden), "inspect payload contains {forbidden}: {serialized}");
+ }
+ }
+ }
+
+ #[test]
+ fn disabled_agent_session_observation_creates_no_state_or_identity() {
+ use cua_driver_core::session::{
+ SessionDeclaration, SessionObserver, SessionStartObservation, SessionTransport,
+ };
+
+ let _guard = ENV_LOCK.lock().unwrap();
+ with_isolated_home(|_| {
+ set_enabled(false).unwrap();
+ let session_id = "private-disabled-session-telemetry-test";
+ TelemetryObserver.on_session_started(
+ session_id,
+ SessionStartObservation {
+ declaration: SessionDeclaration::StartSession,
+ revived: false,
+ transport: SessionTransport::McpStdio,
+ },
+ );
+ assert!(!AGENT_SESSIONS
+ .get_or_init(|| Mutex::new(HashMap::new()))
+ .lock()
+ .unwrap()
+ .contains_key(session_id));
+ assert!(read_install_id().is_none());
+ });
+ }
+
#[test]
fn http_tool_completion_reaches_the_final_payload_as_mcp_http() {
use cua_driver_core::server::{