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.

37.2 KB
Raw Blame
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Cua AI, Inc.

//! Private platform-runtime composition behind the public SDK boundary.
//!
//! This is deliberately not a second public interface. Both imported SDK
//! objects and the daemon host construct the same runtime here; transport
//! adapters are downstream consumers of `CuaDriver`.

use crate::{DriverActivityEvent, DriverActivityKind, DriverActivityObserver};
use cua_driver_core::{
    authorization::PermissionMode,
    protocol::ToolResult as CoreToolResult,
    recording::StopBy,
    session_authorization::{
        AuthenticatedActionConnection, DelegatedSessionRequest, EffectiveAuthorizationContext,
        SessionAuthorizationError, SessionAuthorizationRegistry, SessionModeCeiling,
        TrustedHostLease,
    },
    session_manifest::SessionManifest,
    tool::ToolRegistry,
};
use cursor_overlay::CursorConfig;
use serde_json::Value;
use std::sync::{
    atomic::{AtomicU64, AtomicU8, Ordering},
    Arc, Mutex,
};

const RECORDING_IDLE_TTL_SECS_DEFAULT: u64 = 300;
const SESSION_IDLE_TTL_SECS_DEFAULT: u64 = 300;
#[cfg(test)]
// A tokio mutex: the async tests hold it across awaits to serialize runtime
// ownership, and it does not poison the remaining tests when one fails.
pub(crate) static TEST_RUNTIME_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub(crate) enum RuntimeCreateError {
    #[allow(dead_code)]
    #[error(
        "runtime_already_exists: one direct Cua Driver runtime is already active in this process"
    )]
    AlreadyExists,
    #[error("invalid runtime authorization configuration: {0}")]
    Authorization(String),
    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
    #[error("runtime_unavailable: {0}")]
    Unavailable(String),
}

#[derive(Clone)]
pub(crate) struct RuntimeOptions {
    pub cursor: CursorConfig,
    /// Whether the importing/embedding host owns macOS permission UX. Such a
    /// runtime may inspect TCC state but must never raise Cua-owned prompts.
    pub host_owns_permission_ux: bool,
    pub host_bundle_id: Option<String>,
    pub compatibility_mode: bool,
    #[cfg_attr(
        not(all(target_os = "linux", not(target_env = "musl"))),
        allow(dead_code)
    )]
    pub prepare_desktop_environment: bool,
    pub register_host_tools: Option<fn(&mut ToolRegistry)>,
    pub authorization_ceiling: Option<SessionModeCeiling>,
    pub compatibility_authorization: Option<(PermissionMode, Option<Arc<SessionManifest>>)>,
    /// Constructor-only authorization host. This object is never reachable from
    /// public tool arguments or transport metadata.
    pub authorization_host: Option<Arc<dyn cua_driver_core::consent::ProtectedConsentProvider>>,
    pub activity_observer: Option<Arc<dyn DriverActivityObserver>>,
}

impl RuntimeOptions {
    pub(crate) fn embedded(compatibility_mode: bool) -> Self {
        Self {
            cursor: CursorConfig {
                enabled: false,
                ..CursorConfig::default()
            },
            host_owns_permission_ux: true,
            host_bundle_id: None,
            compatibility_mode,
            prepare_desktop_environment: true,
            register_host_tools: None,
            authorization_ceiling: None,
            compatibility_authorization: None,
            authorization_host: None,
            activity_observer: None,
        }
    }

    pub(crate) fn embedded_with_ceiling(
        compatibility_mode: bool,
        authorization_ceiling: SessionModeCeiling,
        compatibility_permission_mode: PermissionMode,
        compatibility_manifest: Option<Arc<SessionManifest>>,
    ) -> Self {
        Self {
            authorization_ceiling: Some(authorization_ceiling),
            compatibility_authorization: Some((
                compatibility_permission_mode,
                compatibility_manifest,
            )),
            ..Self::embedded(compatibility_mode)
        }
    }
}

pub(crate) struct RuntimeSession {
    runtime: Arc<DriverRuntime>,
    authorization_registry: Arc<SessionAuthorizationRegistry>,
    host: TrustedHostLease,
    connection: AuthenticatedActionConnection,
    context: Arc<EffectiveAuthorizationContext>,
    public_session: String,
}

impl RuntimeSession {
    pub(crate) async fn invoke(&self, name: &str, mut args: Value) -> Option<CoreToolResult> {
        if let Some(refusal) = self.runtime.permissions_pending_refusal() {
            return Some(refusal);
        }
        cua_driver_core::tool_args::sanitize_reserved_args(&mut args);
        let Some(arguments) = args.as_object_mut() else {
            return Some(permission_denied_result(
                "session-bound actions require an object argument".to_owned(),
            ));
        };
        if arguments
            .get("session")
            .and_then(Value::as_str)
            .is_some_and(|session| session != self.public_session)
        {
            return Some(permission_denied_result(
                "public session substitution does not match the bound authorization context"
                    .to_owned(),
            ));
        }
        arguments.insert(
            "session".to_owned(),
            Value::String(self.public_session.clone()),
        );
        let result = self
            .runtime
            .invoke_with_context(name, args, self.context.clone())
            .await;
        if name == "end_session"
            && result
                .as_ref()
                .is_some_and(|result| result.is_error != Some(true))
        {
            self.authorization_registry
                .revoke_connection(&self.connection);
        }
        result
    }
}

impl Drop for RuntimeSession {
    fn drop(&mut self) {
        self.authorization_registry
            .revoke_connection(&self.connection);
        self.authorization_registry.revoke_host(&self.host);
    }
}

/// Whether the runtime accepts tool calls. `Closed` is terminal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
enum Admission {
    Open = 0,
    /// The host's permission gate has not confirmed its grants yet. Inventory
    /// and lifecycle diagnostics stay reachable; no tool runs.
    AwaitingPermissions = 1,
    Closed = 2,
}

impl Admission {
    fn from_u8(value: u8) -> Self {
        match value {
            0 => Self::Open,
            1 => Self::AwaitingPermissions,
            _ => Self::Closed,
        }
    }
}

const PERMISSIONS_PENDING: &str = "permissions_pending: macOS Accessibility or Screen Recording permission is still pending; no action started, retry after the permission gate completes";

pub(crate) struct DriverRuntime {
    registry: Arc<ToolRegistry>,
    authorization_registry: Arc<SessionAuthorizationRegistry>,
    compatibility_context: Arc<EffectiveAuthorizationContext>,
    admission: AtomicU8,
    last_activity: AtomicU64,
    /// Calls hold a read guard; shutdown takes the write guard after closing
    /// admission. Therefore shutdown is idempotent and does not return while a
    /// previously admitted operation is still executing.
    lifecycle: tokio::sync::RwLock<()>,
    lifecycle_maintenance: Mutex<Option<LifecycleMaintenance>>,
    activity_observer: Option<Arc<dyn DriverActivityObserver>>,
}

struct LifecycleMaintenance {
    shutdown: std::sync::mpsc::Sender<()>,
    thread: std::thread::JoinHandle<()>,
}

impl DriverRuntime {
    pub(crate) fn create(options: RuntimeOptions) -> Result<Arc<Self>, RuntimeCreateError> {
        #[cfg(target_os = "windows")]
        if let Err(reason) = platform_windows::diagnostics::interactive_desktop_check() {
            return Err(RuntimeCreateError::Unavailable(format!(
                "Cua Driver requires an interactive Windows user session: {reason}"
            )));
        }
        let authorization_registry = Arc::new(match options.authorization_ceiling.clone() {
            Some(ceiling) => SessionAuthorizationRegistry::with_ceiling(ceiling),
            None => SessionAuthorizationRegistry::process()
                .map_err(RuntimeCreateError::Authorization)?,
        });
        let compatibility_context = match options.compatibility_authorization.clone() {
            Some((mode, manifest)) => authorization_registry
                .compatibility_context(mode, manifest)
                .map_err(RuntimeCreateError::Authorization)?,
            None => authorization_registry
                .legacy_context()
                .map_err(RuntimeCreateError::Authorization)?,
        };
        let registry = Arc::new(cua_driver_core::tool::with_runtime_scope(
            compatibility_context.runtime_scope_key(),
            || build_registry(&options),
        ));
        registry.init_self_weak();
        let runtime = Arc::new(Self {
            registry,
            authorization_registry,
            compatibility_context,
            admission: AtomicU8::new(Admission::Open as u8),
            last_activity: AtomicU64::new(now_unix_secs()),
            lifecycle: tokio::sync::RwLock::new(()),
            lifecycle_maintenance: Mutex::new(None),
            activity_observer: options.activity_observer.clone(),
        });
        *runtime.lifecycle_maintenance.lock().unwrap() =
            Some(spawn_lifecycle_maintenance(&runtime));
        Ok(runtime)
    }

    fn admission(&self) -> Admission {
        Admission::from_u8(self.admission.load(Ordering::Acquire))
    }

    pub(crate) fn is_running(&self) -> bool {
        self.admission() != Admission::Closed
    }

    /// Hold or release tool calls for the host's permission gate. A closed
    /// runtime stays closed.
    pub(crate) fn set_awaiting_permissions(&self, awaiting: bool) {
        let (from, to) = if awaiting {
            (Admission::Open, Admission::AwaitingPermissions)
        } else {
            (Admission::AwaitingPermissions, Admission::Open)
        };
        let _ = self.admission.compare_exchange(
            from as u8,
            to as u8,
            Ordering::AcqRel,
            Ordering::Acquire,
        );
    }

    /// The refusal every tool call gets while the permission gate is pending.
    /// It answers before any other refusal.
    pub(crate) fn permissions_pending_refusal(&self) -> Option<CoreToolResult> {
        (self.admission() == Admission::AwaitingPermissions)
            .then(|| refusal_result("permissions_pending", PERMISSIONS_PENDING.to_owned()))
    }

    pub(crate) fn runtime_scope_key(&self) -> String {
        self.compatibility_context.runtime_scope_key()
    }

    pub(crate) async fn shutdown(&self) {
        self.admission
            .store(Admission::Closed as u8, Ordering::Release);
        let _drained = self.lifecycle.write().await;
        self.stop_lifecycle_maintenance();
        self.authorization_registry.revoke_all();
        let runtime_prefix = format!(
            "__cua_runtime_{}:",
            self.compatibility_context.runtime_scope_key()
        );
        cua_driver_core::session::revoke_sessions_with_prefix(&runtime_prefix);
        cua_driver_core::session::forget_ended_sessions_with_prefix(&runtime_prefix);
        cua_driver_core::session::forget_suspended_runtime_scope(
            &self.compatibility_context.runtime_scope_key(),
        );
        cua_driver_core::snapshot_store::retire_runtime_scope(
            &self.compatibility_context.runtime_scope_key(),
        );
        let recording = self.registry.recording.clone();
        let _ = tokio::task::spawn_blocking(move || recording.stop(StopBy::Anyone)).await;
    }

    fn stop_lifecycle_maintenance(&self) {
        if let Some(maintenance) = self.lifecycle_maintenance.lock().unwrap().take() {
            let _ = maintenance.shutdown.send(());
            if maintenance.thread.thread().id() != std::thread::current().id() {
                let _ = maintenance.thread.join();
            }
        }
    }

    pub(crate) fn tools_list(&self) -> Option<Value> {
        self.is_running().then(|| self.registry.tools_list())
    }

    pub(crate) fn is_known_tool(&self, name: &str) -> bool {
        self.is_running() && self.registry.is_known_tool(name)
    }

    pub(crate) fn history(&self) -> Option<Arc<cua_driver_core::history::HistoryManager>> {
        self.is_running().then(|| self.registry.history()).flatten()
    }

    pub(crate) async fn invoke(&self, name: &str, args: Value) -> Option<CoreToolResult> {
        self.invoke_with_context(name, args, self.compatibility_context.clone())
            .await
    }

    pub(crate) async fn invoke_from_trusted_adapter(
        &self,
        name: &str,
        mut args: Value,
    ) -> Option<CoreToolResult> {
        let evidence =
            cua_driver_core::tool::TrustedInvocationEvidence::extract_from_adapter_args(&mut args);
        self.invoke_with_context_and_evidence(
            name,
            args,
            self.compatibility_context.clone(),
            evidence,
        )
        .await
    }

    async fn invoke_with_context(
        &self,
        name: &str,
        args: Value,
        context: Arc<EffectiveAuthorizationContext>,
    ) -> Option<CoreToolResult> {
        self.invoke_with_context_and_evidence(
            name,
            args,
            context,
            cua_driver_core::tool::TrustedInvocationEvidence::default(),
        )
        .await
    }

    async fn invoke_with_context_and_evidence(
        &self,
        name: &str,
        args: Value,
        context: Arc<EffectiveAuthorizationContext>,
        evidence: cua_driver_core::tool::TrustedInvocationEvidence,
    ) -> Option<CoreToolResult> {
        if let Some(refusal) = self.permissions_pending_refusal() {
            return Some(refusal);
        }
        if !self.is_running() {
            return None;
        }
        self.last_activity.store(now_unix_secs(), Ordering::Relaxed);
        let _operation = self.lifecycle.read().await;
        if !self.is_running() {
            return None;
        }
        let ending_session = (name == "end_session")
            .then(|| {
                args.get("session")
                    .and_then(Value::as_str)
                    .map(|session| context.runtime_session_key(session))
            })
            .flatten();
        let public_session = args
            .get("session")
            .and_then(Value::as_str)
            .filter(|value| !value.is_empty())
            .map(str::to_owned);
        let risk = cua_driver_core::authorization::classify_tool_call(name, &args);
        let adapters = cua_driver_core::authorization::enforcement_adapters_for_call(name, &args)
            .into_iter()
            .map(|adapter| adapter.id.to_owned())
            .collect::<Vec<_>>();
        let result = self
            .registry
            .invoke_with_context_and_evidence(name, args, context, evidence)
            .await;
        if let Some(observer) = self.activity_observer.as_ref() {
            let refusal_code = result
                .structured_content
                .as_ref()
                .and_then(|value| value.pointer("/refusal/code"))
                .and_then(Value::as_str)
                .map(str::to_owned);
            let success = result.is_error != Some(true);
            observer.on_activity(DriverActivityEvent {
                kind: if success {
                    DriverActivityKind::AuthorizedAction
                } else if refusal_code.is_some() {
                    DriverActivityKind::AuthorizationRefused
                } else {
                    DriverActivityKind::ActionFailed
                },
                unix_ms: now_unix_ms(),
                tool_name: name.to_owned(),
                adapter_ids: adapters.clone(),
                risk_class: risk.class.as_str().to_owned(),
                public_session: public_session.clone(),
                refusal_code,
            });
            if success && name == "start_session" {
                observer.on_activity(activity_lifecycle_event(
                    DriverActivityKind::SessionStarted,
                    name,
                    public_session.clone(),
                ));
            }
            if success
                && adapters
                    .iter()
                    .any(|adapter| adapter == "browser_prepare.existing_profile")
            {
                observer.on_activity(activity_lifecycle_event(
                    DriverActivityKind::GrantIssued,
                    name,
                    public_session.clone(),
                ));
            }
            if success && name == "end_session" {
                observer.on_activity(activity_lifecycle_event(
                    DriverActivityKind::GrantRevoked,
                    name,
                    public_session.clone(),
                ));
                observer.on_activity(activity_lifecycle_event(
                    DriverActivityKind::SessionEnded,
                    name,
                    public_session,
                ));
            }
        }
        if let Some(session) = ending_session {
            // `end_session` is a lifecycle boundary: do not report completion
            // until any recording owned by the session has finalized.
            let recording = self.registry.recording.clone();
            let _ =
                tokio::task::spawn_blocking(move || recording.stop(StopBy::Owner(&session))).await;
        }
        Some(result)
    }

    pub(crate) fn create_trusted_session(
        self: &Arc<Self>,
        request: DelegatedSessionRequest,
    ) -> Result<Arc<RuntimeSession>, SessionAuthorizationError> {
        if !self.is_running() {
            return Err(SessionAuthorizationError::RuntimeUnavailable);
        }
        let public_session = request.public_session.clone();
        let transport_session = request.transport_session.clone();
        let (host, connection) = self.authorization_registry.trusted_in_process_binding();
        self.authorization_registry
            .bind_delegated_session(&host, &connection, request)?;
        let context = self.authorization_registry.resolve_delegated(
            &connection,
            &public_session,
            &transport_session,
        )?;
        Ok(Arc::new(RuntimeSession {
            runtime: self.clone(),
            authorization_registry: self.authorization_registry.clone(),
            host,
            connection,
            context,
            public_session,
        }))
    }
}

fn now_unix_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis()
        .try_into()
        .unwrap_or(u64::MAX)
}

fn activity_lifecycle_event(
    kind: DriverActivityKind,
    tool_name: &str,
    public_session: Option<String>,
) -> DriverActivityEvent {
    DriverActivityEvent {
        kind,
        unix_ms: now_unix_ms(),
        tool_name: tool_name.to_owned(),
        adapter_ids: Vec::new(),
        risk_class: "r0".to_owned(),
        public_session,
        refusal_code: None,
    }
}

impl Drop for DriverRuntime {
    fn drop(&mut self) {
        let was_running = self
            .admission
            .swap(Admission::Closed as u8, Ordering::AcqRel)
            != Admission::Closed as u8;
        self.stop_lifecycle_maintenance();
        self.authorization_registry.revoke_all();
        let runtime_scope = self.compatibility_context.runtime_scope_key();
        let runtime_prefix = format!("__cua_runtime_{runtime_scope}:");
        cua_driver_core::session::revoke_sessions_with_prefix(&runtime_prefix);
        cua_driver_core::session::forget_ended_sessions_with_prefix(&runtime_prefix);
        cua_driver_core::session::forget_suspended_runtime_scope(&runtime_scope);
        cua_driver_core::snapshot_store::retire_runtime_scope(&runtime_scope);
        // Explicit `shutdown()` drains work and finalizes recordings. Drop is
        // runtime-scoped and non-blocking so a retained binding cannot affect
        // another generation.
        if was_running {
            let recording = self.registry.recording.clone();
            let _ = recording.stop(StopBy::Anyone);
        }
    }
}

fn permission_denied_result(message: String) -> CoreToolResult {
    refusal_result("permission_denied", message)
}

fn refusal_result(code: &str, message: String) -> CoreToolResult {
    CoreToolResult::error(message.clone()).with_structured(serde_json::json!({
        "status": "refused",
        "refusal": {
            "code": code,
            "message": message,
        }
    }))
}

fn configured_ttl(name: &str, fallback: u64) -> u64 {
    std::env::var(name)
        .ok()
        .and_then(|value| value.parse::<u64>().ok())
        .filter(|value| *value > 0)
        .unwrap_or(fallback)
}

fn now_unix_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

fn spawn_lifecycle_maintenance(runtime: &Arc<DriverRuntime>) -> LifecycleMaintenance {
    let runtime = Arc::downgrade(runtime);
    let (shutdown, shutdown_rx) = std::sync::mpsc::channel();
    let recording_ttl = configured_ttl(
        "CUA_DRIVER_RS_RECORDING_IDLE_TTL_SECS",
        RECORDING_IDLE_TTL_SECS_DEFAULT,
    );
    let session_ttl = std::time::Duration::from_secs(configured_ttl(
        "CUA_DRIVER_RS_SESSION_IDLE_TTL_SECS",
        SESSION_IDLE_TTL_SECS_DEFAULT,
    ));
    let thread = std::thread::spawn(move || loop {
        if shutdown_rx
            .recv_timeout(std::time::Duration::from_secs(30))
            .is_ok()
        {
            break;
        }
        let Some(runtime) = runtime.upgrade() else {
            break;
        };
        if !runtime.is_running() {
            break;
        }
        let ended = cua_driver_core::session::evict_idle_with_prefix(
            session_ttl,
            &format!(
                "__cua_runtime_{}:",
                runtime.compatibility_context.runtime_scope_key()
            ),
        );
        if !ended.is_empty() {
            tracing::info!(
                count = ended.len(),
                "idle-TTL reclaimed runtime-owned sessions"
            );
        }
        let idle = now_unix_secs().saturating_sub(runtime.last_activity.load(Ordering::Relaxed));
        if idle < recording_ttl {
            continue;
        }
        if let Some(generation) = runtime.registry.recording.current_state().generation {
            tracing::warn!("recording idle {idle}s ≥ {recording_ttl}s TTL; auto-stopping");
            let _ = runtime
                .registry
                .recording
                .stop(StopBy::Generation(generation));
        }
    });
    LifecycleMaintenance { shutdown, thread }
}

/// Build the canonical SDK tool inventory without acquiring runtime ownership.
///
/// This metadata-only path cannot dispatch actions and therefore remains
/// available when the host has no interactive desktop (for example Windows
/// Session 0). Finite CLI inspection commands use it to preserve their
/// desktop-free compatibility contract without weakening runtime admission.
pub(crate) fn tool_inventory(options: RuntimeOptions) -> Value {
    build_registry(&options).tools_list()
}

fn build_registry(options: &RuntimeOptions) -> ToolRegistry {
    #[cfg(target_os = "macos")]
    let mut registry = {
        platform_macos::register_tools_with_cursor_and_provider(
            options.authorization_host.clone(),
            options.cursor.clone(),
            options.compatibility_mode,
            options.host_owns_permission_ux,
            options.host_bundle_id.clone(),
        )
    };

    #[cfg(target_os = "windows")]
    let mut registry = {
        platform_windows::register_tools_with_cursor_and_provider(
            options.authorization_host.clone(),
            options.cursor.clone(),
            options.compatibility_mode,
        )
    };

    #[cfg(all(target_os = "linux", not(target_env = "musl")))]
    let mut registry = {
        configure_linux_runtime(options.prepare_desktop_environment);
        platform_linux::register_tools_with_cursor_and_provider(
            options.authorization_host.clone(),
            options.cursor.clone(),
            options.compatibility_mode,
        )
    };

    #[cfg(not(any(
        target_os = "macos",
        target_os = "windows",
        all(target_os = "linux", not(target_env = "musl"))
    )))]
    let mut registry = {
        let _ = options;
        ToolRegistry::new()
    };

    if let Some(register_host_tools) = options.register_host_tools {
        register_host_tools(&mut registry);
    }
    let perception_registered = registry.tools_list()["tools"]
        .as_array()
        .is_some_and(|tools| {
            tools.iter().any(|tool| {
                tool.get("name").and_then(Value::as_str) == Some("parse_visual_regions")
            })
        });
    if !perception_registered {
        registry.register_perception_tool(crate::configured_perception_client());
    }
    let recording = Arc::downgrade(&registry.recording);
    let recording_session_end = cua_driver_core::session::register_scoped_fallible_session_end_hook(
        "recording",
        move |session| {
            let Some(recording) = recording.upgrade() else {
                return Ok(());
            };
            recording
                .stop(StopBy::Owner(session))
                .map_err(|error| error.to_string())
        },
    );
    registry.retain_session_end_hook(recording_session_end);
    registry
}

#[cfg(all(target_os = "linux", not(target_env = "musl")))]
fn configure_linux_runtime(prepare_desktop_environment: bool) {
    if prepare_desktop_environment {
        platform_linux::xauth::ensure_xauthority_discovered();
        platform_linux::session_bus::ensure_session_bus_discovered();
        if std::env::var_os("NO_AT_BRIDGE").as_deref() != Some(std::ffi::OsStr::new("1")) {
            platform_linux::a11y::ensure_chromium_accessibility_enabled();
            if let Err(error) = platform_linux::atspi::ensure_listener_active() {
                tracing::warn!("could not activate the persistent AT-SPI listener: {error}");
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use cua_driver_core::consent::{
        ConsentAction, ConsentRequest, ProtectedConsentProvider, ProviderDecision,
    };
    use std::time::Duration;

    struct TestProtectedHost;

    #[async_trait]
    impl ProtectedConsentProvider for TestProtectedHost {
        fn provider_id(&self) -> &'static str {
            "test.runtime-protected-host"
        }

        async fn request_consent(
            &self,
            request: &ConsentRequest,
        ) -> Result<ProviderDecision, String> {
            Ok(ProviderDecision {
                action: ConsentAction::Accept,
                request_digest: request.request_digest.clone(),
            })
        }
    }

    fn standard_options() -> RuntimeOptions {
        let ceiling = SessionModeCeiling::for_trusted_sessions(
            [PermissionMode::Standard],
            false,
            Duration::from_secs(60),
            Duration::from_secs(30),
        )
        .unwrap();
        let mut options =
            RuntimeOptions::embedded_with_ceiling(false, ceiling, PermissionMode::Standard, None);
        options.authorization_host = Some(Arc::new(TestProtectedHost));
        options
    }

    #[test]
    fn every_registered_tool_schema_matches_the_dispatch_argument_check() {
        let registry = build_registry(&RuntimeOptions::embedded(false));
        // These schemas declare `additionalProperties: true`.
        let open = [
            "get_browser_state",
            "browser_prepare",
            "browser_navigate",
            "browser_click",
            "browser_type",
            "browser_dialog",
            "browser_set_input_files",
            "browser_download",
            "browser_pointer",
            "start_session",
            "escalate_session",
            "get_session",
            "list_sessions",
            "get_session_state",
            "end_session",
        ];
        let violations = registry.input_conformance_violations(&open);
        assert!(violations.is_empty(), "{violations:#?}");
    }

    #[test]
    fn canonical_inventory_advertises_unavailable_perception_tool() {
        let inventory = tool_inventory(RuntimeOptions::embedded(false));
        let tools = inventory["tools"].as_array().unwrap();
        assert_eq!(
            tools
                .iter()
                .filter(|tool| tool["name"] == "parse_visual_regions")
                .count(),
            1
        );
    }

    #[test]
    fn host_perception_registration_is_not_duplicated_in_inventory() {
        fn register(registry: &mut ToolRegistry) {
            registry.register_perception_tool(
                cua_driver_core::perception_client::PerceptionClient::unavailable(),
            );
        }
        let mut options = RuntimeOptions::embedded(false);
        options.register_host_tools = Some(register);
        let inventory = tool_inventory(options);
        assert_eq!(
            inventory["tools"]
                .as_array()
                .unwrap()
                .iter()
                .filter(|tool| tool["name"] == "parse_visual_regions")
                .count(),
            1
        );
    }

    #[tokio::test]
    async fn authorized_dispatch_refreshes_only_the_runtime_private_activity_key() {
        let _runtime_test = TEST_RUNTIME_LOCK.lock().await;
        let runtime = DriverRuntime::create(standard_options()).unwrap();
        let public = "runtime-activity-refresh";
        let internal = runtime.compatibility_context.runtime_session_key(public);
        let prefix = format!(
            "__cua_runtime_{}:",
            runtime.compatibility_context.runtime_scope_key()
        );

        runtime
            .invoke(
                "start_session",
                serde_json::json!({"session": public, "capture_scope": "auto"}),
            )
            .await
            .unwrap();
        assert!(cua_driver_core::session::has_session_activity(&internal));
        assert!(!cua_driver_core::session::has_session_activity(public));

        std::thread::sleep(Duration::from_millis(20));
        let idle_before_refresh =
            cua_driver_core::session::session_idle_duration(&internal).unwrap();
        runtime
            .invoke("start_session", serde_json::json!({"session": public}))
            .await
            .unwrap();
        let idle_after_refresh =
            cua_driver_core::session::session_idle_duration(&internal).unwrap();
        assert!(
            idle_after_refresh < idle_before_refresh,
            "authorized traffic must reset the private idle clock: before={idle_before_refresh:?} after={idle_after_refresh:?} ended={}",
            cua_driver_core::session::is_session_ended(&internal)
        );
        let evicted =
            cua_driver_core::session::evict_idle_with_prefix(idle_before_refresh, &prefix);
        assert!(
            !evicted.contains(&internal),
            "continuous authorized traffic must refresh the private idle clock"
        );

        runtime.shutdown().await;
    }

    #[tokio::test]
    async fn idle_eviction_finalizes_the_owning_runtime_recording() {
        let _runtime_test = TEST_RUNTIME_LOCK.lock().await;
        let runtime = DriverRuntime::create(standard_options()).unwrap();
        let public = "runtime-recording-idle";
        let internal = runtime.compatibility_context.runtime_session_key(public);
        let prefix = format!(
            "__cua_runtime_{}:",
            runtime.compatibility_context.runtime_scope_key()
        );
        runtime
            .invoke(
                "start_session",
                serde_json::json!({"session": public, "capture_scope": "auto"}),
            )
            .await
            .unwrap();
        let output = tempfile::tempdir().unwrap();
        let started = runtime
            .invoke(
                "start_recording",
                serde_json::json!({
                    "session": public,
                    "output_dir": output.path(),
                    "record_video": false,
                }),
            )
            .await
            .unwrap();
        assert_ne!(started.is_error, Some(true));
        assert!(runtime.registry.recording.current_state().enabled);

        let evicted = cua_driver_core::session::evict_idle_with_prefix(Duration::ZERO, &prefix);
        assert!(evicted.contains(&internal));
        for _ in 0..100 {
            if !runtime.registry.recording.current_state().enabled {
                break;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        assert!(
            !runtime.registry.recording.current_state().enabled,
            "session-end hook must finalize recording after idle eviction"
        );

        runtime.shutdown().await;
    }

    #[tokio::test]
    async fn incomplete_end_keeps_trusted_authorization_live_for_cleanup_retry() {
        let _runtime_test = TEST_RUNTIME_LOCK.lock().await;
        let runtime = DriverRuntime::create(standard_options()).unwrap();
        let public_session = "runtime-end-cleanup-retry";
        let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let attempts_for_hook = attempts.clone();
        let _hook = cua_driver_core::session::register_scoped_fallible_session_end_hook(
            "runtime-end-cleanup-retry-test",
            move |_| {
                if attempts_for_hook.fetch_add(1, Ordering::SeqCst) == 0 {
                    Err("synthetic first-attempt failure".into())
                } else {
                    Ok(())
                }
            },
        );
        let session = runtime
            .create_trusted_session(DelegatedSessionRequest {
                public_session: public_session.into(),
                transport_session: "runtime-end-cleanup-retry-transport".into(),
                mode: PermissionMode::Standard,
                ttl: Duration::from_secs(60),
                idle_ttl: Duration::from_secs(30),
                capability_manifest: None,
            })
            .unwrap();

        let started = session
            .invoke("start_session", serde_json::json!({}))
            .await
            .unwrap();
        assert_ne!(started.is_error, Some(true));
        let runtime_prefix = format!(
            "__cua_runtime_{}:",
            runtime.compatibility_context.runtime_scope_key()
        );
        let started_sessions = cua_driver_core::session::list_session_snapshots_with_prefix(
            &runtime_prefix,
            Duration::from_secs(300),
        );
        assert_eq!(started_sessions.len(), 1, "{started_sessions:?}");

        let first_end = session
            .invoke("end_session", serde_json::json!({}))
            .await
            .unwrap();
        assert_eq!(
            first_end.is_error,
            Some(true),
            "result={first_end:?} started={started_sessions:?} attempts={}",
            attempts.load(Ordering::SeqCst)
        );
        assert_eq!(attempts.load(Ordering::SeqCst), 1);

        let retried_end = session
            .invoke("end_session", serde_json::json!({}))
            .await
            .unwrap();
        assert_ne!(retried_end.is_error, Some(true));
        assert_eq!(attempts.load(Ordering::SeqCst), 2);

        let after_end = session
            .invoke("health_report", serde_json::json!({}))
            .await
            .unwrap();
        assert_eq!(
            after_end
                .structured_content
                .as_ref()
                .and_then(|value| value.pointer("/refusal/code"))
                .and_then(Value::as_str),
            Some("authorization_revoked")
        );

        runtime.shutdown().await;
    }

    #[tokio::test]
    async fn awaiting_permissions_refuses_before_dispatch_and_never_reopens_a_closed_runtime() {
        let _runtime_test = TEST_RUNTIME_LOCK.lock().await;
        let runtime = DriverRuntime::create(standard_options()).unwrap();
        runtime.set_awaiting_permissions(true);
        let pending = runtime
            .invoke("get_config", serde_json::json!({}))
            .await
            .expect("an awaiting runtime answers");
        assert_eq!(
            pending
                .structured_content
                .as_ref()
                .and_then(|value| value.pointer("/refusal/code")),
            Some(&serde_json::json!("permissions_pending"))
        );
        assert!(runtime.is_running(), "awaiting is not closed");
        assert!(runtime.tools_list().is_some(), "inventory stays reachable");

        runtime.shutdown().await;
        runtime.set_awaiting_permissions(false);
        assert!(!runtime.is_running());
        assert!(runtime
            .invoke("get_config", serde_json::json!({}))
            .await
            .is_none());
    }

    #[tokio::test]
    async fn shutdown_stops_lifecycle_maintenance() {
        let _runtime_test = TEST_RUNTIME_LOCK.lock().await;
        let runtime = DriverRuntime::create(standard_options()).unwrap();
        // The maintenance thread owns the only receiver, so sends fail once it
        // exits. This proves the thread stopped; it cannot distinguish the join
        // from the thread's own prompt exit after the stop signal.
        let probe = runtime
            .lifecycle_maintenance
            .lock()
            .unwrap()
            .as_ref()
            .expect("runtime creation starts lifecycle maintenance")
            .shutdown
            .clone();

        runtime.shutdown().await;

        assert!(runtime.lifecycle_maintenance.lock().unwrap().is_none());
        assert!(
            probe.send(()).is_err(),
            "lifecycle maintenance is still running after shutdown"
        );
    }
}