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): capture embedded startup diagnostics (#3281)

injaneityccc478a8b2d2
diff --git a/libs/cua-driver/python/README.md b/libs/cua-driver/python/README.md
index 59ae448583..69adabf354 100644
--- a/libs/cua-driver/python/README.md
+++ b/libs/cua-driver/python/README.md
@@ -175,6 +175,15 @@ new connection. `wait_for_exit(connection.generation)` observes unexpected
termination. Dropping the host closes its parent-liveness pipe and kills the
child as a fallback, but orderly applications should still await `stop()`.
+For startup troubleshooting, construct the host with
+`EmbeddedCuaDriverHost.with_options()` and set `capture_stderr=True`. After a
+failed start, `last_diagnostics()` returns the generation-scoped final 65,536
+bytes, exit code, and truncation state; a successful start clears the previous
+diagnostics. Captured text is raw child stderr and can contain application data,
+so do not place secrets in daemon stderr or forward diagnostics to telemetry.
+When `inherit_stderr` is also enabled, the host tees output on a bounded
+best-effort path so a blocked terminal cannot stop diagnostic collection.
+
## Binary wrapper
The package also exposes the bundled executable:
diff --git a/libs/cua-driver/python/src/cua_driver/__init__.py b/libs/cua-driver/python/src/cua_driver/__init__.py
index c58e3cef07..dc5bbcfab7 100644
--- a/libs/cua-driver/python/src/cua_driver/__init__.py
+++ b/libs/cua-driver/python/src/cua_driver/__init__.py
@@ -41,6 +41,7 @@ from ._native import (
ForeignDriverResponseEnvelope,
EmbeddedCuaDriverHost,
EmbeddedDriverConnection,
+ EmbeddedDriverDiagnostics,
EmbeddedDriverError,
EmbeddedDriverExit,
EmbeddedDriverHostOptions,
@@ -338,6 +339,7 @@ __all__ = [
"ForeignDriverResponseEnvelope",
"EmbeddedCuaDriverHost",
"EmbeddedDriverConnection",
+ "EmbeddedDriverDiagnostics",
"EmbeddedDriverError",
"EmbeddedDriverExit",
"EmbeddedDriverHostOptions",
diff --git a/libs/cua-driver/python/src/cua_driver/_native.py b/libs/cua-driver/python/src/cua_driver/_native.py
index 829ecf0ef3..91e2301fde 100644
--- a/libs/cua-driver/python/src/cua_driver/_native.py
+++ b/libs/cua-driver/python/src/cua_driver/_native.py
@@ -702,6 +702,8 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_connection() != 44467:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_last_diagnostics() != 57979:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_restart() != 27248:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_start() != 16011:
@@ -1756,6 +1758,11 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_connection.argt
ctypes.POINTER(_UniffiRustCallStatus),
)
_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_connection.restype = _UniffiRustBuffer
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_last_diagnostics.argtypes = (
+ ctypes.c_uint64,
+ ctypes.POINTER(_UniffiRustCallStatus),
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_last_diagnostics.restype = _UniffiRustBuffer
_UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_restart.argtypes = (
ctypes.c_uint64,
)
@@ -2160,6 +2167,9 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_with
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_connection.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_connection.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_last_diagnostics.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_last_diagnostics.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_restart.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_restart.restype = ctypes.c_uint16
@@ -5371,6 +5381,54 @@ class _UniffiFfiConverterOptionalInt32(_UniffiConverterRustBuffer):
else:
raise InternalError("Unexpected flag byte for optional type")
+@dataclass
+class EmbeddedDriverDiagnostics:
+ def __init__(self, *, lifecycle_phase:str, exit_code:typing.Optional[int], stderr_tail:str, stderr_truncated:bool):
+ self.lifecycle_phase = lifecycle_phase
+ self.exit_code = exit_code
+ self.stderr_tail = stderr_tail
+ self.stderr_truncated = stderr_truncated
+
+
+
+
+ def __str__(self):
+ return "EmbeddedDriverDiagnostics(lifecycle_phase={}, exit_code={}, stderr_tail={}, stderr_truncated={})".format(self.lifecycle_phase, self.exit_code, self.stderr_tail, self.stderr_truncated)
+ def __eq__(self, other):
+ if self.lifecycle_phase != other.lifecycle_phase:
+ return False
+ if self.exit_code != other.exit_code:
+ return False
+ if self.stderr_tail != other.stderr_tail:
+ return False
+ if self.stderr_truncated != other.stderr_truncated:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeEmbeddedDriverDiagnostics(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return EmbeddedDriverDiagnostics(
+ lifecycle_phase=_UniffiFfiConverterString.read(buf),
+ exit_code=_UniffiFfiConverterOptionalInt32.read(buf),
+ stderr_tail=_UniffiFfiConverterString.read(buf),
+ stderr_truncated=_UniffiFfiConverterBoolean.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.lifecycle_phase)
+ _UniffiFfiConverterOptionalInt32.check_lower(value.exit_code)
+ _UniffiFfiConverterString.check_lower(value.stderr_tail)
+ _UniffiFfiConverterBoolean.check_lower(value.stderr_truncated)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.lifecycle_phase, buf)
+ _UniffiFfiConverterOptionalInt32.write(value.exit_code, buf)
+ _UniffiFfiConverterString.write(value.stderr_tail, buf)
+ _UniffiFfiConverterBoolean.write(value.stderr_truncated, buf)
+
@dataclass
class EmbeddedDriverExit:
def __init__(self, *, generation:str, code:typing.Optional[int], success:bool):
@@ -5513,7 +5571,7 @@ class _UniffiFfiConverterOptionalTypeEmbeddedPermissionMode(_UniffiConverterRust
@dataclass
class EmbeddedDriverHostOptions:
- def __init__(self, *, binary_path:str, host_bundle_id:str, socket_path:typing.Optional[str], startup_timeout_ms:typing.Optional[int], shutdown_timeout_ms:typing.Optional[int], permission_mode:typing.Optional[EmbeddedPermissionMode], capability_manifest_path:typing.Optional[str] = _DEFAULT, approve_capability_manifest:bool = False, session_policy_path:typing.Optional[str], approve_session_policy:bool, dangerously_bypass_approvals:bool, environment:typing.List[EmbeddedEnvironmentVariable], inherit_stderr:bool, no_overlay:bool = False):
+ def __init__(self, *, binary_path:str, host_bundle_id:str, socket_path:typing.Optional[str], startup_timeout_ms:typing.Optional[int], shutdown_timeout_ms:typing.Optional[int], permission_mode:typing.Optional[EmbeddedPermissionMode], capability_manifest_path:typing.Optional[str] = _DEFAULT, approve_capability_manifest:bool = False, session_policy_path:typing.Optional[str], approve_session_policy:bool, dangerously_bypass_approvals:bool, environment:typing.List[EmbeddedEnvironmentVariable], inherit_stderr:bool, no_overlay:bool = False, capture_stderr:bool = False):
self.binary_path = binary_path
self.host_bundle_id = host_bundle_id
self.socket_path = socket_path
@@ -5531,12 +5589,13 @@ class EmbeddedDriverHostOptions:
self.environment = environment
self.inherit_stderr = inherit_stderr
self.no_overlay = no_overlay
+ self.capture_stderr = capture_stderr
def __str__(self):
- return "EmbeddedDriverHostOptions(binary_path={}, host_bundle_id={}, socket_path={}, startup_timeout_ms={}, shutdown_timeout_ms={}, permission_mode={}, capability_manifest_path={}, approve_capability_manifest={}, session_policy_path={}, approve_session_policy={}, dangerously_bypass_approvals={}, environment={}, inherit_stderr={}, no_overlay={})".format(self.binary_path, self.host_bundle_id, self.socket_path, self.startup_timeout_ms, self.shutdown_timeout_ms, self.permission_mode, self.capability_manifest_path, self.approve_capability_manifest, self.session_policy_path, self.approve_session_policy, self.dangerously_bypass_approvals, self.environment, self.inherit_stderr, self.no_overlay)
+ return "EmbeddedDriverHostOptions(binary_path={}, host_bundle_id={}, socket_path={}, startup_timeout_ms={}, shutdown_timeout_ms={}, permission_mode={}, capability_manifest_path={}, approve_capability_manifest={}, session_policy_path={}, approve_session_policy={}, dangerously_bypass_approvals={}, environment={}, inherit_stderr={}, no_overlay={}, capture_stderr={})".format(self.binary_path, self.host_bundle_id, self.socket_path, self.startup_timeout_ms, self.shutdown_timeout_ms, self.permission_mode, self.capability_manifest_path, self.approve_capability_manifest, self.session_policy_path, self.approve_session_policy, self.dangerously_bypass_approvals, self.environment, self.inherit_stderr, self.no_overlay, self.capture_stderr)
def __eq__(self, other):
if self.binary_path != other.binary_path:
return False
@@ -5566,6 +5625,8 @@ class EmbeddedDriverHostOptions:
return False
if self.no_overlay != other.no_overlay:
return False
+ if self.capture_stderr != other.capture_stderr:
+ return False
return True
class _UniffiFfiConverterTypeEmbeddedDriverHostOptions(_UniffiConverterRustBuffer):
@@ -5586,6 +5647,7 @@ class _UniffiFfiConverterTypeEmbeddedDriverHostOptions(_UniffiConverterRustBuffe
environment=_UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.read(buf),
inherit_stderr=_UniffiFfiConverterBoolean.read(buf),
no_overlay=_UniffiFfiConverterBoolean.read(buf),
+ capture_stderr=_UniffiFfiConverterBoolean.read(buf),
)
@staticmethod
@@ -5604,6 +5666,7 @@ class _UniffiFfiConverterTypeEmbeddedDriverHostOptions(_UniffiConverterRustBuffe
_UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.check_lower(value.environment)
_UniffiFfiConverterBoolean.check_lower(value.inherit_stderr)
_UniffiFfiConverterBoolean.check_lower(value.no_overlay)
+ _UniffiFfiConverterBoolean.check_lower(value.capture_stderr)
@staticmethod
def write(value, buf):
@@ -5621,6 +5684,7 @@ class _UniffiFfiConverterTypeEmbeddedDriverHostOptions(_UniffiConverterRustBuffe
_UniffiFfiConverterSequenceTypeEmbeddedEnvironmentVariable.write(value.environment, buf)
_UniffiFfiConverterBoolean.write(value.inherit_stderr, buf)
_UniffiFfiConverterBoolean.write(value.no_overlay, buf)
+ _UniffiFfiConverterBoolean.write(value.capture_stderr, buf)
@dataclass
class ForeignDriverChannelIdentity:
@@ -10113,11 +10177,38 @@ class _UniffiFfiConverterOptionalTypeEmbeddedDriverConnection(_UniffiConverterRu
else:
raise InternalError("Unexpected flag byte for optional type")
+class _UniffiFfiConverterOptionalTypeEmbeddedDriverDiagnostics(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeEmbeddedDriverDiagnostics.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeEmbeddedDriverDiagnostics.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeEmbeddedDriverDiagnostics.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
class EmbeddedCuaDriverHostProtocol(typing.Protocol):
def connection(self, ) -> typing.Optional[EmbeddedDriverConnection]:
raise NotImplementedError
+ def last_diagnostics(self, ) -> typing.Optional[EmbeddedDriverDiagnostics]:
+ raise NotImplementedError
async def restart(self, ) -> EmbeddedDriverConnection:
raise NotImplementedError
async def start(self, ) -> EmbeddedDriverConnection:
@@ -10194,6 +10285,18 @@ class EmbeddedCuaDriverHost(EmbeddedCuaDriverHostProtocol):
*_uniffi_lowered_args,
)
return _uniffi_lift_return(_uniffi_ffi_result)
+ def last_diagnostics(self, ) -> typing.Optional[EmbeddedDriverDiagnostics]:
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterOptionalTypeEmbeddedDriverDiagnostics.lift
+ _uniffi_error_converter = None
+ _uniffi_ffi_result = _uniffi_rust_call_with_error(
+ _uniffi_error_converter,
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_last_diagnostics,
+ *_uniffi_lowered_args,
+ )
+ return _uniffi_lift_return(_uniffi_ffi_result)
async def restart(self, ) -> EmbeddedDriverConnection:
_uniffi_lowered_args = (
self._uniffi_clone_handle(),
@@ -10738,6 +10841,7 @@ __all__ = [
"EmbeddedEnvironmentVariable",
"EmbeddedMcpConfiguration",
"EmbeddedDriverConnection",
+ "EmbeddedDriverDiagnostics",
"EmbeddedDriverExit",
"EmbeddedDriverHostOptions",
"ForeignDriverChannelIdentity",
diff --git a/libs/cua-driver/python/tests/test_uniffi_loader.py b/libs/cua-driver/python/tests/test_uniffi_loader.py
index 11d14e5180..49b75ae09f 100644
--- a/libs/cua-driver/python/tests/test_uniffi_loader.py
+++ b/libs/cua-driver/python/tests/test_uniffi_loader.py
@@ -95,6 +95,17 @@ class GeneratedOptionsTests(unittest.TestCase):
EmbeddedDriverHostOptions(**required, no_overlay=True).no_overlay
)
+ def test_embedded_diagnostics_record_is_public(self) -> None:
+ from cua_driver import EmbeddedDriverDiagnostics
+
+ diagnostics = EmbeddedDriverDiagnostics(
+ lifecycle_phase="startup",
+ exit_code=7,
+ stderr_tail="failed",
+ stderr_truncated=False,
+ )
+ self.assertEqual(diagnostics.exit_code, 7)
+
@unittest.skipUnless(LIBRARY.exists(), "host-native UniFFI library is not staged")
@unittest.skipIf(os.name == "nt", "Unix socket fixture")
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/embedded.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/embedded.rs
index 99075b3b9b..b81d70062b 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/embedded.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/embedded.rs
@@ -11,19 +11,23 @@ use cua_driver_core::key_pacing::KEY_GAP_ENV;
use cua_driver_core::step_pacing::BATCH_PACING_ENV;
use cua_driver_core::window_observation::{WINDOW_CHANGE_POLL_ENV, WINDOW_CHANGE_TIMEOUT_ENV};
use std::collections::BTreeMap;
-use std::process::Stdio;
+use std::process::{ExitStatus, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use thiserror::Error;
-use tokio::io::AsyncWriteExt as _;
+use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
use tokio::process::{Child, ChildStdin, Command};
-use tokio::sync::Notify;
+use tokio::sync::{mpsc, Notify};
+use tokio::task::JoinHandle;
use uuid::Uuid;
const DEFAULT_STARTUP_TIMEOUT_MS: u64 = 10_000;
const DEFAULT_SHUTDOWN_TIMEOUT_MS: u64 = 2_000;
const HANDSHAKE_ATTEMPT_TIMEOUT_MS: u64 = 500;
+const STDERR_TAIL_LIMIT_BYTES: usize = 65_536;
+const STDERR_DRAIN_TIMEOUT_MS: u64 = 500;
+const STDERR_TEE_QUEUE_CHUNKS: usize = 16;
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum EmbeddedPermissionMode {
@@ -58,6 +62,8 @@ pub struct EmbeddedDriverHostOptions {
pub inherit_stderr: bool,
#[uniffi(default = false)]
pub no_overlay: bool,
+ #[uniffi(default = false)]
+ pub capture_stderr: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
@@ -93,6 +99,14 @@ pub struct EmbeddedDriverExit {
pub success: bool,
}
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct EmbeddedDriverDiagnostics {
+ pub lifecycle_phase: String,
+ pub exit_code: Option<i32>,
+ pub stderr_tail: String,
+ pub stderr_truncated: bool,
+}
+
#[derive(Debug, Error, uniffi::Error)]
pub enum EmbeddedDriverError {
#[error("invalid embedded host configuration: {reason}")]
@@ -127,6 +141,7 @@ struct ValidatedOptions {
environment: Vec<EmbeddedEnvironmentVariable>,
inherit_stderr: bool,
no_overlay: bool,
+ capture_stderr: bool,
}
#[cfg(unix)]
@@ -140,10 +155,16 @@ struct EndpointIdentity {
#[derive(Debug, Clone)]
struct EndpointIdentity;
-struct RunningProcess {
- connection: EmbeddedDriverConnection,
+struct ManagedChild {
child: Child,
liveness: Option<ChildStdin>,
+ stderr_pump: Option<StderrPump>,
+ shutdown_timeout: Duration,
+}
+
+struct RunningProcess {
+ connection: EmbeddedDriverConnection,
+ process: ManagedChild,
endpoint_identity: EndpointIdentity,
}
@@ -164,10 +185,144 @@ struct HostInner {
last_exit: Option<EmbeddedDriverExit>,
}
+type SharedDiagnostics = Arc<Mutex<DiagnosticCapture>>;
+
+struct DiagnosticCapture {
+ exit_code: Option<i32>,
+ stderr: Vec<u8>,
+ truncated: bool,
+}
+
+impl DiagnosticCapture {
+ fn new() -> Self {
+ Self {
+ exit_code: None,
+ stderr: Vec::new(),
+ truncated: false,
+ }
+ }
+
+ fn append(&mut self, bytes: &[u8]) {
+ if bytes.len() >= STDERR_TAIL_LIMIT_BYTES {
+ self.truncated |= bytes.len() > STDERR_TAIL_LIMIT_BYTES || !self.stderr.is_empty();
+ self.stderr.clear();
+ self.stderr
+ .extend_from_slice(&bytes[bytes.len() - STDERR_TAIL_LIMIT_BYTES..]);
+ return;
+ }
+ let overflow = self
+ .stderr
+ .len()
+ .saturating_add(bytes.len())
+ .saturating_sub(STDERR_TAIL_LIMIT_BYTES);
+ if overflow > 0 {
+ self.stderr.drain(..overflow);
+ self.truncated = true;
+ }
+ self.stderr.extend_from_slice(bytes);
+ }
+
+ fn snapshot(&self) -> EmbeddedDriverDiagnostics {
+ EmbeddedDriverDiagnostics {
+ lifecycle_phase: "startup".into(),
+ exit_code: self.exit_code,
+ stderr_tail: String::from_utf8_lossy(&self.stderr).into_owned(),
+ stderr_truncated: self.truncated,
+ }
+ }
+}
+
+struct StderrPump {
+ reader: Option<JoinHandle<()>>,
+ tee: Option<JoinHandle<()>>,
+ diagnostics: SharedDiagnostics,
+}
+
+impl StderrPump {
+ async fn finish(mut self, exit_code: Option<i32>) {
+ tokio::join!(
+ finish_stderr_task(self.reader.take()),
+ finish_stderr_task(self.tee.take())
+ );
+ self.diagnostics.lock().unwrap().exit_code = exit_code;
+ }
+}
+
+impl Drop for StderrPump {
+ fn drop(&mut self) {
+ if let Some(task) = self.reader.take() {
+ task.abort();
+ }
+ if let Some(task) = self.tee.take() {
+ task.abort();
+ }
+ }
+}
+
+impl ManagedChild {
+ fn close_liveness(&mut self) {
+ drop(self.liveness.take());
+ }
+
+ fn kill(&mut self) {
+ self.close_liveness();
+ let _ = self.child.start_kill();
+ }
+
+ async fn finish_stderr(&mut self, exit_code: Option<i32>) {
+ if let Some(stderr_pump) = self.stderr_pump.take() {
+ stderr_pump.finish(exit_code).await;
+ }
+ }
+
+ async fn terminate(&mut self) -> Option<ExitStatus> {
+ if let Some(mut liveness) = self.liveness.take() {
+ let _ = liveness.shutdown().await;
+ }
+ let status = match tokio::time::timeout(self.shutdown_timeout, self.child.wait()).await {
+ Ok(Ok(status)) => Some(status),
+ Ok(Err(_)) | Err(_) => {
+ let _ = self.child.start_kill();
+ self.child.wait().await.ok()
+ }
+ };
+ self.finish_stderr(status.as_ref().and_then(ExitStatus::code))
+ .await;
+ status
+ }
+
+ async fn stop(&mut self) -> Result<ExitStatus, EmbeddedDriverError> {
+ if let Some(mut liveness) = self.liveness.take() {
+ let _ = liveness.shutdown().await;
+ }
+ let status = match tokio::time::timeout(self.shutdown_timeout, self.child.wait()).await {
+ Ok(result) => result.map_err(|error| EmbeddedDriverError::Lifecycle {
+ reason: format!("wait for embedded daemon: {error}"),
+ }),
+ Err(_) => match self.child.start_kill() {
+ Ok(()) => self
+ .child
+ .wait()
+ .await
+ .map_err(|error| EmbeddedDriverError::Lifecycle {
+ reason: format!("reap force-killed embedded daemon: {error}"),
+ }),
+ Err(error) => Err(EmbeddedDriverError::Lifecycle {
+ reason: format!("force-kill embedded daemon: {error}"),
+ }),
+ },
+ };
+ self.finish_stderr(status.as_ref().ok().and_then(ExitStatus::code))
+ .await;
+ status
+ }
+}
+
#[derive(uniffi::Object)]
pub struct EmbeddedCuaDriverHost {
options: ValidatedOptions,
inner: Mutex<HostInner>,
+ diagnostics: Mutex<Option<SharedDiagnostics>>,
changed: Notify,
}
@@ -207,8 +362,7 @@ impl Drop for StopTransitionGuard {
return;
};
let generation = running.connection.generation.clone();
- drop(running.liveness.take());
- let _ = running.child.start_kill();
+ running.process.kill();
cleanup_owned_endpoint(&running.connection.socket_path, &running.endpoint_identity);
// Drop the kill-on-drop child before waking a concurrent starter.
drop(running);
@@ -270,6 +424,7 @@ impl EmbeddedCuaDriverHost {
environment: Vec::new(),
inherit_stderr: true,
no_overlay: false,
+ capture_stderr: false,
})
}
@@ -283,6 +438,7 @@ impl EmbeddedCuaDriverHost {
phase: HostPhase::Stopped,
last_exit: None,
}),
+ diagnostics: Mutex::new(None),
changed: Notify::new(),
}))
}
@@ -307,6 +463,12 @@ impl EmbeddedCuaDriverHost {
}
}
+ pub fn last_diagnostics(&self) -> Option<EmbeddedDriverDiagnostics> {
+ let diagnostics = self.diagnostics.lock().unwrap().clone()?;
+ let snapshot = diagnostics.lock().unwrap().snapshot();
+ Some(snapshot)
+ }
+
pub async fn start(self: Arc<Self>) -> Result<EmbeddedDriverConnection, EmbeddedDriverError> {
loop {
let notified = self.changed.notified();
@@ -317,18 +479,26 @@ impl EmbeddedCuaDriverHost {
HostPhase::Ready(running) => return Ok(running.connection.clone()),
HostPhase::Stopped => {
let generation = Uuid::new_v4().to_string();
+ let diagnostics = self
+ .options
+ .capture_stderr
+ .then(|| Arc::new(Mutex::new(DiagnosticCapture::new())));
+ *self.diagnostics.lock().unwrap() = diagnostics.clone();
let cancel = Arc::new(AtomicBool::new(false));
inner.phase = HostPhase::Starting {
generation: generation.clone(),
cancel: cancel.clone(),
};
- Some((generation, cancel))
+ Some((generation, cancel, diagnostics))
}
HostPhase::Starting { .. } | HostPhase::Stopping { .. } => None,
}
};
- if let Some((generation, cancel)) = transition {
- return self.clone().perform_start(generation, cancel).await;
+ if let Some((generation, cancel, diagnostics)) = transition {
+ return self
+ .clone()
+ .perform_start(generation, cancel, diagnostics)
+ .await;
}
notified.await;
}
@@ -417,6 +587,7 @@ impl EmbeddedCuaDriverHost {
self: Arc<Self>,
generation: String,
cancel: Arc<AtomicBool>,
+ diagnostics: Option<SharedDiagnostics>,
) -> Result<EmbeddedDriverConnection, EmbeddedDriverError> {
let mut transition_guard = StartupTransitionGuard {
host: self.clone(),
@@ -436,7 +607,9 @@ impl EmbeddedCuaDriverHost {
.env_clear()
.stdin(Stdio::piped())
.stdout(Stdio::null())
- .stderr(if self.options.inherit_stderr {
+ .stderr(if diagnostics.is_some() {
+ Stdio::piped()
+ } else if self.options.inherit_stderr {
Stdio::inherit()
} else {
Stdio::null()
@@ -462,33 +635,57 @@ impl EmbeddedCuaDriverHost {
binary_path: self.options.binary_path.clone(),
reason: "spawned process has no pid".into(),
})?;
- let mut liveness = child
+ let liveness = child
.stdin
.take()
.ok_or_else(|| EmbeddedDriverError::Spawn {
binary_path: self.options.binary_path.clone(),
reason: "failed to create parent-liveness stdin pipe".into(),
})?;
+ let stderr_pump = if let Some(diagnostics) = diagnostics.clone() {
+ let stderr = child
+ .stderr
+ .take()
+ .ok_or_else(|| EmbeddedDriverError::Spawn {
+ binary_path: self.options.binary_path.clone(),
+ reason: "failed to capture embedded daemon stderr".into(),
+ })?;
+ Some(spawn_stderr_pump(
+ stderr,
+ diagnostics,
+ self.options.inherit_stderr,
+ ))
+ } else {
+ None
+ };
+ let mut process = ManagedChild {
+ child,
+ liveness: Some(liveness),
+ stderr_pump,
+ shutdown_timeout: self.options.shutdown_timeout,
+ };
let deadline = tokio::time::Instant::now() + self.options.startup_timeout;
let metadata = loop {
if cancel.load(Ordering::Acquire) {
- terminate_startup_child(&mut child, &mut liveness).await;
+ process.terminate().await;
return Err(EmbeddedDriverError::StartupCancelled);
}
if let Some(status) =
- child
+ process
+ .child
.try_wait()
.map_err(|error| EmbeddedDriverError::Lifecycle {
reason: format!("inspect startup child: {error}"),
})?
{
+ process.finish_stderr(status.code()).await;
return Err(EmbeddedDriverError::ExitedBeforeReady {
code: status.code(),
});
}
if tokio::time::Instant::now() >= deadline {
- terminate_startup_child(&mut child, &mut liveness).await;
+ process.terminate().await;
return Err(EmbeddedDriverError::StartupTimeout {
timeout_ms: self.options.startup_timeout.as_millis() as u64,
});
@@ -506,13 +703,13 @@ impl EmbeddedCuaDriverHost {
Ok(Ok(Ok(metadata))) => break metadata,
Ok(Ok(Err(_))) => {}
Ok(Err(join_error)) => {
- terminate_startup_child(&mut child, &mut liveness).await;
+ process.terminate().await;
return Err(EmbeddedDriverError::Lifecycle {
reason: format!("daemon metadata task failed: {join_error}"),
});
}
Err(_) => {
- terminate_startup_child(&mut child, &mut liveness).await;
+ process.terminate().await;
return Err(EmbeddedDriverError::StartupTimeout {
timeout_ms: self.options.startup_timeout.as_millis() as u64,
});
@@ -525,12 +722,12 @@ impl EmbeddedCuaDriverHost {
let endpoint_identity = match capture_endpoint_identity(&socket_path) {
Ok(identity) => identity,
Err(error) => {
- terminate_startup_child(&mut child, &mut liveness).await;
+ process.terminate().await;
return Err(error);
}
};
if let Err(error) = validate_metadata(&metadata, pid, &self.options.host_bundle_id) {
- terminate_startup_child(&mut child, &mut liveness).await;
+ process.terminate().await;
cleanup_owned_endpoint(&socket_path, &endpoint_identity);
return Err(error);
}
@@ -545,14 +742,13 @@ impl EmbeddedCuaDriverHost {
};
if cancel.load(Ordering::Acquire) {
- terminate_startup_child(&mut child, &mut liveness).await;
+ process.terminate().await;
cleanup_owned_endpoint(&socket_path, &endpoint_identity);
return Err(EmbeddedDriverError::StartupCancelled);
}
let mut pending = Some(RunningProcess {
connection: connection.clone(),
- child,
- liveness: Some(liveness),
+ process,
endpoint_identity,
});
let still_starting = {
@@ -569,12 +765,20 @@ impl EmbeddedCuaDriverHost {
};
if !still_starting {
let mut running = pending.unwrap();
- let mut liveness = running.liveness.take().unwrap();
- terminate_startup_child(&mut running.child, &mut liveness).await;
+ running.process.terminate().await;
cleanup_owned_endpoint(&socket_path, &running.endpoint_identity);
return Err(EmbeddedDriverError::StartupCancelled);
}
transition_guard.disarm();
+ if let Some(diagnostics) = diagnostics {
+ let mut current = self.diagnostics.lock().unwrap();
+ if current
+ .as_ref()
+ .is_some_and(|capture| Arc::ptr_eq(capture, &diagnostics))
+ {
+ *current = None;
+ }
+ }
self.changed.notify_waiters();
Ok(connection)
}
@@ -588,31 +792,7 @@ impl EmbeddedCuaDriverHost {
running: Some(running),
armed: true,
};
- if let Some(mut liveness) = transition_guard.running_mut().liveness.take() {
- // Closing the write side is the primary graceful shutdown signal.
- let _ = liveness.shutdown().await;
- drop(liveness);
- }
- let status = {
- let running = transition_guard.running_mut();
- match tokio::time::timeout(self.options.shutdown_timeout, running.child.wait()).await {
- Ok(result) => result.map_err(|error| EmbeddedDriverError::Lifecycle {
- reason: format!("wait for embedded daemon: {error}"),
- }),
- Err(_) => {
- match running.child.start_kill() {
- Ok(()) => running.child.wait().await.map_err(|error| {
- EmbeddedDriverError::Lifecycle {
- reason: format!("reap force-killed embedded daemon: {error}"),
- }
- }),
- Err(error) => Err(EmbeddedDriverError::Lifecycle {
- reason: format!("force-kill embedded daemon: {error}"),
- }),
- }
- }
- }
- };
+ let status = transition_guard.running_mut().process.stop().await;
let running = transition_guard.disarm();
cleanup_owned_endpoint(&running.connection.socket_path, &running.endpoint_identity);
{
@@ -684,7 +864,7 @@ impl EmbeddedCuaDriverHost {
fn refresh_exit_locked(&self, inner: &mut HostInner) {
let phase = std::mem::replace(&mut inner.phase, HostPhase::Stopped);
match phase {
- HostPhase::Ready(mut running) => match running.child.try_wait() {
+ HostPhase::Ready(mut running) => match running.process.child.try_wait() {
Ok(Some(status)) => {
cleanup_owned_endpoint(
&running.connection.socket_path,
@@ -710,8 +890,7 @@ impl Drop for EmbeddedCuaDriverHost {
match phase {
HostPhase::Starting { cancel, .. } => cancel.store(true, Ordering::Release),
HostPhase::Ready(mut running) => {
- drop(running.liveness.take());
- let _ = running.child.start_kill();
+ running.process.kill();
cleanup_owned_endpoint(&running.connection.socket_path, &running.endpoint_identity);
}
HostPhase::Stopped | HostPhase::Stopping { .. } => {}
@@ -828,6 +1007,7 @@ fn validate_options(
environment: options.environment,
inherit_stderr: options.inherit_stderr,
no_overlay: options.no_overlay,
+ capture_stderr: options.capture_stderr,
})
}
@@ -1140,14 +1320,67 @@ fn cleanup_owned_endpoint(socket_path: &str, identity: &EndpointIdentity) {
}
}
-async fn terminate_startup_child(child: &mut Child, liveness: &mut ChildStdin) {
- let _ = liveness.shutdown().await;
- if tokio::time::timeout(Duration::from_millis(250), child.wait())
+fn spawn_stderr_pump(
+ mut stderr: tokio::process::ChildStderr,
+ diagnostics: SharedDiagnostics,
+ inherit_stderr: bool,
+) -> StderrPump {
+ let (tee_sender, tee) = if inherit_stderr {
+ let (sender, mut receiver) = mpsc::channel::<Vec<u8>>(STDERR_TEE_QUEUE_CHUNKS);
+ let task = tokio::spawn(async move {
+ let mut inherited = tokio::io::stderr();
+ while let Some(bytes) = receiver.recv().await {
+ if inherited.write_all(&bytes).await.is_err() {
+ break;
+ }
+ }
+ });
+ (Some(sender), Some(task))
+ } else {
+ (None, None)
+ };
+
+ let reader_diagnostics = diagnostics.clone();
+ let reader = tokio::spawn(async move {
+ let mut buffer = [0_u8; 8192];
+ while let Ok(count) = stderr.read(&mut buffer).await {
+ if count == 0 {
+ break;
+ }
+ capture_and_queue_stderr(&reader_diagnostics, &buffer[..count], tee_sender.as_ref());
+ }
+ });
+
+ StderrPump {
+ reader: Some(reader),
+ tee,
+ diagnostics,
+ }
+}
+
+fn capture_and_queue_stderr(
+ diagnostics: &SharedDiagnostics,
+ bytes: &[u8],
+ tee_sender: Option<&mpsc::Sender<Vec<u8>>>,
+) {
+ diagnostics.lock().unwrap().append(bytes);
+ if let Some(sender) = tee_sender {
+ // Diagnostics must keep draining even if inherited stderr is blocked.
+ // The bounded tee is intentionally best effort.
+ let _ = sender.try_send(bytes.to_vec());
+ }
+}
+
+async fn finish_stderr_task(task: Option<JoinHandle<()>>) {
+ let Some(mut task) = task else {
+ return;
+ };
+ if tokio::time::timeout(Duration::from_millis(STDERR_DRAIN_TIMEOUT_MS), &mut task)
.await
.is_err()
{
- let _ = child.start_kill();
- let _ = child.wait().await;
+ task.abort();
+ let _ = task.await;
}
}
@@ -1187,6 +1420,7 @@ mod tests {
environment: Vec::new(),
inherit_stderr: false,
no_overlay: false,
+ capture_stderr: false,
}
}
@@ -1280,6 +1514,39 @@ mod tests {
}
}
+ #[test]
+ fn diagnostic_capture_reports_only_discarded_bytes_as_truncated() {
+ let mut under = DiagnosticCapture::new();
+ under.append(&vec![b'a'; STDERR_TAIL_LIMIT_BYTES - 1]);
+ assert!(!under.snapshot().stderr_truncated);
+
+ let mut exact = DiagnosticCapture::new();
+ exact.append(&vec![b'a'; STDERR_TAIL_LIMIT_BYTES]);
+ assert!(!exact.snapshot().stderr_truncated);
+
+ let mut over = DiagnosticCapture::new();
+ over.append(&vec![b'a'; STDERR_TAIL_LIMIT_BYTES + 1]);
+ assert!(over.snapshot().stderr_truncated);
+ assert_eq!(over.snapshot().stderr_tail.len(), STDERR_TAIL_LIMIT_BYTES);
+
+ let mut replaced = DiagnosticCapture::new();
+ replaced.append(b"discarded");
+ replaced.append(&vec![b'a'; STDERR_TAIL_LIMIT_BYTES]);
+ assert!(replaced.snapshot().stderr_truncated);
+ }
+
+ #[tokio::test]
+ async fn blocked_stderr_tee_does_not_block_or_drop_diagnostics() {
+ let diagnostics = Arc::new(Mutex::new(DiagnosticCapture::new()));
+ let (sender, _receiver) = mpsc::channel(1);
+
+ capture_and_queue_stderr(&diagnostics, b"first-", Some(&sender));
+ capture_and_queue_stderr(&diagnostics, b"second", Some(&sender));
+
+ let snapshot = diagnostics.lock().unwrap().snapshot();
+ assert_eq!(snapshot.stderr_tail, "first-second");
+ }
+
#[test]
fn telemetry_preferences_are_inherited_and_overridable() {
assert!(allowed_environment_name("CUA_DRIVER_RS_TELEMETRY_ENABLED"));
@@ -1556,8 +1823,12 @@ mod tests {
environment: Vec::new(),
},
},
- child,
- liveness,
+ process: ManagedChild {
+ child,
+ liveness,
+ stderr_pump: None,
+ shutdown_timeout: Duration::from_millis(DEFAULT_SHUTDOWN_TIMEOUT_MS),
+ },
endpoint_identity,
};
host.inner.lock().unwrap().phase = HostPhase::Stopping { generation };
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs
index 2a43bcd903..204eb9adbc 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/embedded_host_sdk_mcp_test.rs
@@ -55,6 +55,7 @@ fn isolated_driver_host(
inherit_stderr: true,
// No overlay window on the developer's display.
no_overlay: true,
+ capture_stderr: false,
})
.expect("construct host");
(host, state)
@@ -116,6 +117,31 @@ fn write_test_shell_script(path: &std::path::Path, body: &str) {
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).unwrap();
}
+#[cfg(unix)]
+fn capturing_host(
+ binary: &std::path::Path,
+ host_bundle_id: &str,
+) -> std::sync::Arc<EmbeddedCuaDriverHost> {
+ EmbeddedCuaDriverHost::with_options(EmbeddedDriverHostOptions {
+ binary_path: binary.to_string_lossy().into_owned(),
+ host_bundle_id: host_bundle_id.into(),
+ socket_path: None,
+ startup_timeout_ms: None,
+ shutdown_timeout_ms: None,
+ permission_mode: None,
+ capability_manifest_path: None,
+ approve_capability_manifest: false,
+ session_policy_path: None,
+ approve_session_policy: false,
+ dangerously_bypass_approvals: false,
+ environment: Vec::new(),
+ inherit_stderr: false,
+ no_overlay: false,
+ capture_stderr: true,
+ })
+ .expect("construct capturing host")
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn embedded_host_serves_sdk_and_mcp_with_one_contract() {
let (host, _state) = isolated_driver_host("com.trycua.embedded-contract-test");
@@ -332,12 +358,15 @@ async fn concurrent_start_coalesces_and_restart_rotates_generation() {
async fn stop_cancels_startup_and_unblocks_every_waiter() {
let directory = tempfile::tempdir().unwrap();
let binary = directory.path().join("never-ready-driver");
- write_test_shell_script(&binary, "read _");
- let host = EmbeddedCuaDriverHost::new(
- binary.to_string_lossy().into_owned(),
- "com.trycua.embedded-cancel-test".into(),
- )
- .expect("construct host");
+ let started = directory.path().join("started");
+ write_test_shell_script(
+ &binary,
+ &format!(
+ "printf 'cancelled-startup\\n' >&2\n: > '{}'\nread _\nexit 9",
+ started.display()
+ ),
+ );
+ let host = capturing_host(&binary, "com.trycua.embedded-cancel-test");
let starting = tokio::spawn(host.clone().start());
let deadline = Instant::now() + Duration::from_secs(2);
@@ -345,6 +374,11 @@ async fn stop_cancels_startup_and_unblocks_every_waiter() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(host.state(), EmbeddedDriverHostState::Starting);
+ let fixture_deadline = Instant::now() + Duration::from_secs(10);
+ while !started.exists() && Instant::now() < fixture_deadline {
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ assert!(started.exists(), "startup fixture did not run");
host.clone().stop().await.expect("cancel startup");
let start_error = starting.await.unwrap().unwrap_err();
@@ -353,6 +387,9 @@ async fn stop_cancels_startup_and_unblocks_every_waiter() {
cua_driver_sdk::EmbeddedDriverError::StartupCancelled
));
assert_eq!(host.state(), EmbeddedDriverHostState::Stopped);
+ let diagnostics = host.last_diagnostics().unwrap();
+ assert_eq!(diagnostics.stderr_tail, "cancelled-startup\n");
+ assert_eq!(diagnostics.exit_code, Some(9));
}
#[cfg(unix)]
@@ -360,12 +397,8 @@ async fn stop_cancels_startup_and_unblocks_every_waiter() {
async fn early_child_exit_resets_the_host_to_stopped() {
let directory = tempfile::tempdir().unwrap();
let binary = directory.path().join("early-exit-driver");
- write_test_shell_script(&binary, "exit 7");
- let host = EmbeddedCuaDriverHost::new(
- binary.to_string_lossy().into_owned(),
- "com.trycua.embedded-early-exit-test".into(),
- )
- .expect("construct host");
+ write_test_shell_script(&binary, "printf 'complete-startup-error\\n' >&2\nexit 7");
+ let host = capturing_host(&binary, "com.trycua.embedded-early-exit-test");
for attempt in 1..=64 {
let error = host.clone().start().await.unwrap_err();
assert!(
@@ -380,5 +413,44 @@ async fn early_child_exit_resets_the_host_to_stopped() {
EmbeddedDriverHostState::Stopped,
"attempt {attempt}/64 did not reset the host after {error:?}"
);
+ let diagnostics = host
+ .last_diagnostics()
+ .expect("failed startup should retain diagnostics");
+ assert_eq!(diagnostics.exit_code, Some(7));
+ assert_eq!(diagnostics.stderr_tail, "complete-startup-error\n");
+ assert!(!diagnostics.stderr_truncated);
}
}
+
+#[cfg(unix)]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn late_stderr_from_an_old_start_cannot_contaminate_the_next_generation() {
+ let directory = tempfile::tempdir().unwrap();
+ let binary = directory.path().join("generation-driver");
+ let counter = directory.path().join("started-once");
+ write_test_shell_script(
+ &binary,
+ &format!(
+ "if [ ! -e '{}' ]; then\n : > '{}'\n (sleep 1; printf 'stale-generation\\n' >&2) &\n exit 7\nfi\nprintf 'current-generation\\n' >&2\nexit 8",
+ counter.display(),
+ counter.display()
+ ),
+ );
+ let host = capturing_host(&binary, "com.trycua.embedded-generation-test");
+
+ let first = host.clone().start().await.unwrap_err();
+ assert!(matches!(
+ first,
+ cua_driver_sdk::EmbeddedDriverError::ExitedBeforeReady { code: Some(7) }
+ ));
+ let second = host.clone().start().await.unwrap_err();
+ assert!(matches!(
+ second,
+ cua_driver_sdk::EmbeddedDriverError::ExitedBeforeReady { code: Some(8) }
+ ));
+ tokio::time::sleep(Duration::from_millis(700)).await;
+
+ let diagnostics = host.last_diagnostics().unwrap();
+ assert_eq!(diagnostics.exit_code, Some(8));
+ assert_eq!(diagnostics.stderr_tail, "current-generation\n");
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs
index 8b96d5853a..1e29b34667 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/private_worker_test.rs
@@ -286,6 +286,7 @@ async fn embedded_service_binds_authority_to_the_original_host_connection() {
inherit_stderr: true,
// No overlay window on the developer's display.
no_overlay: true,
+ capture_stderr: false,
})
.unwrap();
let connection = host.clone().start().await.unwrap();
diff --git a/libs/cua-driver/typescript/README.md b/libs/cua-driver/typescript/README.md
index bb34bcd3f2..2bb269325e 100644
--- a/libs/cua-driver/typescript/README.md
+++ b/libs/cua-driver/typescript/README.md
@@ -201,6 +201,15 @@ for its generation, observe unexpected termination with
Rust host also closes a parent-liveness pipe on normal destruction so the daemon
cannot remain orphaned after a host crash.
+For startup troubleshooting, create the host with
+`EmbeddedCuaDriverHost.withOptions()` and set `captureStderr: true`. After a
+failed start, `lastDiagnostics()` returns the generation-scoped final 65,536
+bytes, exit code, and truncation state; a successful start clears the previous
+diagnostics. Captured text is raw child stderr and can contain application data,
+so do not place secrets in daemon stderr or forward diagnostics to telemetry.
+When `inheritStderr` is also enabled, the host tees output on a bounded
+best-effort path so a blocked terminal cannot stop diagnostic collection.
+
The npm package installs one optional native package selected for the current
OS and CPU. It does not bundle the `cua-driver` executable: ship that executable
outside ASAR, preserve its executable bit, and sign it before signing and
diff --git a/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts b/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts
index b3e2ffcb6d..17f78c8e28 100644
--- a/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts
+++ b/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts
@@ -928,6 +928,11 @@ const DEFINITIONS = {
ret: FfiType.RustBuffer,
hasRustCallStatus: true,
},
+ "uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_last_diagnostics": {
+ args: [FfiType.Handle],
+ ret: FfiType.RustBuffer,
+ hasRustCallStatus: true,
+ },
"uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_restart": {
args: [FfiType.Handle],
ret: FfiType.Handle,
@@ -1563,6 +1568,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_last_diagnostics": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_restart": {
args: [],
ret: FfiType.UInt16,
@@ -1977,6 +1987,7 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_new(binaryPath: Uint8Array, hostBundleId: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_with_options(options: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_connection(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_last_diagnostics(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_restart(uniffiSelf: bigint): bigint;
uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_start(uniffiSelf: bigint): bigint;
uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_state(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
@@ -2104,6 +2115,7 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new(): number;
uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_with_options(): number;
uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_connection(): number;
+ uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_last_diagnostics(): number;
uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_restart(): number;
uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_start(): number;
uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_state(): number;
diff --git a/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts b/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
index 4c5487c8e8..792e98ba82 100644
--- a/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
+++ b/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
@@ -2793,6 +2793,57 @@ const FfiConverterTypeEmbeddedDriverConnection = (() => {
return new FFIConverter();
})();
+export type EmbeddedDriverDiagnostics = {
+ lifecyclePhase: string,
+ exitCode?: number,
+ stderrTail: string,
+ stderrTruncated: boolean
+}
+
+/**
+ * Generated factory for {@link EmbeddedDriverDiagnostics} record objects.
+ */
+export const EmbeddedDriverDiagnostics = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<EmbeddedDriverDiagnostics, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<EmbeddedDriverDiagnostics>,
+ });
+})();
+
+const FfiConverterTypeEmbeddedDriverDiagnostics = (() => {
+ type TypeName = EmbeddedDriverDiagnostics;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ lifecyclePhase: FfiConverterString.read(from),
+ exitCode: FfiConverterOptionalInt32.read(from),
+ stderrTail: FfiConverterString.read(from),
+ stderrTruncated: FfiConverterBool.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.lifecyclePhase, into);
+ FfiConverterOptionalInt32.write(value.exitCode, into);
+ FfiConverterString.write(value.stderrTail, into);
+ FfiConverterBool.write(value.stderrTruncated, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.lifecyclePhase) +
+ FfiConverterOptionalInt32.allocationSize(value.exitCode) +
+ FfiConverterString.allocationSize(value.stderrTail) +
+ FfiConverterBool.allocationSize(value.stderrTruncated);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export type EmbeddedDriverExit = {
generation: string,
code?: number,
@@ -2889,7 +2940,8 @@ export type EmbeddedDriverHostOptions = {
dangerouslyBypassApprovals: boolean,
environment: Array<EmbeddedEnvironmentVariable>,
inheritStderr: boolean,
- noOverlay: boolean
+ noOverlay: boolean,
+ captureStderr: boolean
}
/**
@@ -2899,7 +2951,8 @@ export const EmbeddedDriverHostOptions = (() => {
const defaults = () => ({
capabilityManifestPath: undefined,
approveCapabilityManifest: false,
- noOverlay: false
+ noOverlay: false,
+ captureStderr: false
});
const create = (() => {
return uniffiCreateRecord<EmbeddedDriverHostOptions, ReturnType<typeof defaults>>(defaults);
@@ -2929,7 +2982,8 @@ const FfiConverterTypeEmbeddedDriverHostOptions = (() => {
dangerouslyBypassApprovals: FfiConverterBool.read(from),
environment: FfiConverterSequenceTypeEmbeddedEnvironmentVariable.read(from),
inheritStderr: FfiConverterBool.read(from),
- noOverlay: FfiConverterBool.read(from)
+ noOverlay: FfiConverterBool.read(from),
+ captureStderr: FfiConverterBool.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
@@ -2947,6 +3001,7 @@ const FfiConverterTypeEmbeddedDriverHostOptions = (() => {
FfiConverterSequenceTypeEmbeddedEnvironmentVariable.write(value.environment, into);
FfiConverterBool.write(value.inheritStderr, into);
FfiConverterBool.write(value.noOverlay, into);
+ FfiConverterBool.write(value.captureStderr, into);
}
allocationSize(value: TypeName): number {
return FfiConverterString.allocationSize(value.binaryPath) +
@@ -2962,7 +3017,8 @@ const FfiConverterTypeEmbeddedDriverHostOptions = (() => {
FfiConverterBool.allocationSize(value.dangerouslyBypassApprovals) +
FfiConverterSequenceTypeEmbeddedEnvironmentVariable.allocationSize(value.environment) +
FfiConverterBool.allocationSize(value.inheritStderr) +
- FfiConverterBool.allocationSize(value.noOverlay);
+ FfiConverterBool.allocationSize(value.noOverlay) +
+ FfiConverterBool.allocationSize(value.captureStderr);
}
};
@@ -9137,6 +9193,7 @@ const uniffiCallbackInterfaceDriverServiceTransport: { vtable: any; register: ()
export interface EmbeddedCuaDriverHostLike {
connection(): EmbeddedDriverConnection | undefined;
+ lastDiagnostics(): EmbeddedDriverDiagnostics | undefined;
restart(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<EmbeddedDriverConnection>;
start(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<EmbeddedDriverConnection>;
state(): EmbeddedDriverHostState;
@@ -9203,6 +9260,23 @@ export class EmbeddedCuaDriverHost extends UniffiAbstractObject implements Embed
));
}
+ lastDiagnostics(): EmbeddedDriverDiagnostics | undefined {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterOptionalTypeEmbeddedDriverDiagnostics.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_embeddedcuadriverhost_last_diagnostics(
+ uniffiTypeEmbeddedCuaDriverHostObjectFactory.clonePointer(this),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
async restart(asyncOpts_?: { signal: AbortSignal }): Promise<EmbeddedDriverConnection> /*throws*/ {
const __stack = uniffiIsDebug ? new Error().stack : undefined;
try {
@@ -9672,6 +9746,9 @@ const FfiConverterSequenceTypeCursorMotionSample = new FfiConverterArray(FfiConv
// FfiConverter for EmbeddedDriverConnection | undefined
const FfiConverterOptionalTypeEmbeddedDriverConnection = new FfiConverterOptional(FfiConverterTypeEmbeddedDriverConnection);
+// FfiConverter for EmbeddedDriverDiagnostics | undefined
+const FfiConverterOptionalTypeEmbeddedDriverDiagnostics = new FfiConverterOptional(FfiConverterTypeEmbeddedDriverDiagnostics);
+
// FfiConverter for CursorMotionSpec | undefined
const FfiConverterOptionalTypeCursorMotionSpec = new FfiConverterOptional(FfiConverterTypeCursorMotionSpec);
@@ -10030,6 +10107,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_connection() !== 44467) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_connection");
}
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_last_diagnostics() !== 57979) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_last_diagnostics");
+ }
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_restart() !== 27248) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_embeddedcuadriverhost_restart");
}
@@ -10126,6 +10206,7 @@ export default Object.freeze({
FfiConverterTypeDriverServiceTransportError,
FfiConverterTypeEmbeddedCuaDriverHost,
FfiConverterTypeEmbeddedDriverConnection,
+ FfiConverterTypeEmbeddedDriverDiagnostics,
FfiConverterTypeEmbeddedDriverError,
FfiConverterTypeEmbeddedDriverExit,
FfiConverterTypeEmbeddedDriverHostOptions,