Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(sdk): cua sb exec -i streams a command's stdio into a Space (CUA-1949) (#5629)
ddupontcd509859675e
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.tsindex 9f81e0a46c..dcbce8c7fc 100644--- a/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts+++ b/apps/cua-spaces-desktop/src/native/generated/cua_sdk-ffi.ts@@ -2660,7 +2660,7 @@ const DEFINITIONS = {hasRustCallStatus: false,},"uniffi_cua_sdk_fn_method_spacesdprocess_signal": {- args: [FfiType.Handle, FfiType.RustBuffer],+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Int8],ret: FfiType.Handle,hasRustCallStatus: false,},@@ -5439,7 +5439,7 @@ interface NativeModuleInterface {uniffi_cua_sdk_fn_method_spacesdprocess_next_event(uniffiSelf: bigint): bigint;uniffi_cua_sdk_fn_method_spacesdprocess_pid(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): number;uniffi_cua_sdk_fn_method_spacesdprocess_resize(uniffiSelf: bigint, cols: number, rows: number): bigint;- uniffi_cua_sdk_fn_method_spacesdprocess_signal(uniffiSelf: bigint, signal: Uint8Array): bigint;+ uniffi_cua_sdk_fn_method_spacesdprocess_signal(uniffiSelf: bigint, signal: Uint8Array, processGroup: number): bigint;uniffi_cua_sdk_fn_method_spacesdprocess_tag(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_sdk_fn_method_spacesdprocess_wait(uniffiSelf: bigint): bigint;uniffi_cua_sdk_fn_method_spacesdprocess_write_pty(uniffiSelf: bigint, data: Uint8Array): bigint;diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.tsindex fd931ab981..743afe72be 100644--- a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts+++ b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts@@ -15818,7 +15818,14 @@ export type SpacesdCommand = {/*** Run in a PTY of this size.*/- pty?: PtySize+ pty?: PtySize,+ /**+ * Kill the process (`term`, then `kill`) when this client's connection+ * to cua-spacesd ends before the process does, including when the+ * client process dies. Off by default: processes are detached and can be+ * reattached by tag.+ */+ killOnDisconnect: boolean}/**@@ -15833,7 +15840,8 @@ export const SpacesdCommand = (() => {timeoutMs: undefined,tag: undefined,stdin: false,- pty: undefined+ pty: undefined,+ killOnDisconnect: false});const create = (() => {return uniffiCreateRecord<SpacesdCommand, ReturnType<typeof defaults>>(defaults);@@ -15858,7 +15866,8 @@ const FfiConverterTypeSpacesdCommand = (() => {timeoutMs: FfiConverterOptionalUInt32.read(from),tag: FfiConverterOptionalString.read(from),stdin: FfiConverterBool.read(from),- pty: FfiConverterOptionalTypePtySize.read(from)+ pty: FfiConverterOptionalTypePtySize.read(from),+ killOnDisconnect: FfiConverterBool.read(from)};}write(value: TypeName, into: RustBuffer): void {@@ -15871,6 +15880,7 @@ const FfiConverterTypeSpacesdCommand = (() => {FfiConverterOptionalString.write(value.tag, into);FfiConverterBool.write(value.stdin, into);FfiConverterOptionalTypePtySize.write(value.pty, into);+ FfiConverterBool.write(value.killOnDisconnect, into);}allocationSize(value: TypeName): number {return FfiConverterString.allocationSize(value.program) +@@ -15881,7 +15891,8 @@ const FfiConverterTypeSpacesdCommand = (() => {FfiConverterOptionalUInt32.allocationSize(value.timeoutMs) +FfiConverterOptionalString.allocationSize(value.tag) +FfiConverterBool.allocationSize(value.stdin) +- FfiConverterOptionalTypePtySize.allocationSize(value.pty);+ FfiConverterOptionalTypePtySize.allocationSize(value.pty) ++ FfiConverterBool.allocationSize(value.killOnDisconnect);}};@@ -22964,9 +22975,11 @@ export interface SpacesdProcessLike {*/resize(cols: number, rows: number, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;/**- * Sends a signal by name (`term`, `kill`, `SIGINT`, ...).+ * Sends a signal by name (`term`, `kill`, `SIGINT`, ...). With+ * `process_group`, to the process's whole group (everything it started),+ * as a terminal's Ctrl-C does; by default to the process alone.*/- signal(signal: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;+ signal(signal: string, processGroup: boolean, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;/*** Tag, when set.*/@@ -23180,16 +23193,18 @@ private constructor(pointer: UniffiHandle) {}/**- * Sends a signal by name (`term`, `kill`, `SIGINT`, ...).+ * Sends a signal by name (`term`, `kill`, `SIGINT`, ...). With+ * `process_group`, to the process's whole group (everything it started),+ * as a terminal's Ctrl-C does; by default to the process alone.*/- async signal(signal: string, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {+ async signal(signal: string, processGroup: boolean = false, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {const __stack = uniffiIsDebug ? new Error().stack : undefined;try {return await uniffiRustCallAsync(/*rustCaller:*/ uniffiCaller,/*rustFutureFunc:*/ () => {return nativeModule().uniffi_cua_sdk_fn_method_spacesdprocess_signal(- uniffiTypeSpacesdProcessObjectFactory.clonePointer(this),FfiConverterString.lower(signal, nativeModule().rustbuffer_alloc)+ uniffiTypeSpacesdProcessObjectFactory.clonePointer(this),FfiConverterString.lower(signal, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(processGroup, nativeModule().rustbuffer_alloc));},/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_void,@@ -36580,7 +36595,7 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_sdk_checksum_method_spacesdprocess_resize() !== 46607) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spacesdprocess_resize");}- if (nativeModule().uniffi_cua_sdk_checksum_method_spacesdprocess_signal() !== 61925) {+ if (nativeModule().uniffi_cua_sdk_checksum_method_spacesdprocess_signal() !== 44588) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spacesdprocess_signal");}if (nativeModule().uniffi_cua_sdk_checksum_method_spacesdprocess_tag() !== 24315) {diff --git a/docs/content/docs/cua-cli/index.mdx b/docs/content/docs/cua-cli/index.mdxindex d832f7f03e..036a32c454 100644--- a/docs/content/docs/cua-cli/index.mdx+++ b/docs/content/docs/cua-cli/index.mdx@@ -63,4 +63,39 @@ and the [CLI reference](/cua-cli/reference/cli) list every option.`cua sb exec` and `cua spacesd exec` exit with the command's own status. Statelives in `~/.cua` (`CUA_HOME` moves it).+### Run a command as a stdio stream++A plain `exec` collects the output and returns when the command ends, and+`cua sb exec` stops a command after 120 seconds. Add `-i` (`--stdin`) to use+`exec` as a long-lived pipe into the sandbox, the way `docker exec -i` is used:++```bash test="cli-shape" id="exec-stream"+cua sb exec -i dev -- bash -c 'wc -c'+```++With `-i`:++- The command is an argv, not a shell line: nothing is joined or re-quoted,+ so `-- bash -c '<script>'` reaches the sandbox as three words.+- Standard input is forwarded until it ends, then the command sees end of+ file. Standard output and standard error arrive as they are produced and+ stay separate.+- There is no time limit. `--timeout SECONDS` sets one (`0` removes the+ 120 second limit of a plain `cua sb exec`).+- The exit status is the command's, or 128 plus the signal number when a+ signal ended it. Exit 127 means the command could not start.+- `SIGINT`, `SIGTERM` and `SIGHUP` sent to `cua` are passed on to the command.+- The command is killed when `cua` goes away, even if `cua` is killed with+ `SIGKILL`, so a host that dies leaves nothing running in the sandbox.+- `--user NAME` and `--cwd DIR` choose the guest account and start directory.+ They also work without `-i`.++Options go before the sandbox name. `cua spacesd exec -i URL ...` takes the+same options for a cua-spacesd address. A local macOS 15 sandbox without+cua-spacesd cannot stream (it only has `lume ssh`); the command fails with+`Unsupported`.++From code, `SpacesdClient.spawn` with `stdin=True` and `kill_on_disconnect=True`+is the same stream in the Python, TypeScript, Swift, Kotlin and Rust SDKs.+Start with the [Quickstart](/cua-cli/quickstart), which also creates a local macOS sandbox.diff --git a/docs/content/docs/cua-cli/reference/cli/sandboxes.mdx b/docs/content/docs/cua-cli/reference/cli/sandboxes.mdxindex 012732f882..bb5e27c295 100644--- a/docs/content/docs/cua-cli/reference/cli/sandboxes.mdx+++ b/docs/content/docs/cua-cli/reference/cli/sandboxes.mdx@@ -329,15 +329,22 @@ cua sandbox exec [OPTIONS] <NAME> <COMMAND>...| `<NAME>` | string | required | Sandbox name or ref (`local:NAME`). || `<COMMAND>...` | string | required | Command and arguments. Repeatable. |-| Flag | Type | Default | Description |-| --- | --- | --- | --- |-| <span id="cua-sandbox-exec--local"></span>`--local` | boolean | `false` | Look NAME up among local sandboxes only (same as `local:NAME`). |+| Flag | Short | Type | Default | Description |+| --- | --- | --- | --- | --- |+| <span id="cua-sandbox-exec--user"></span>`--user` | | string | | Run as this guest user. |+| <span id="cua-sandbox-exec--cwd"></span>`--cwd` | | string | | Start in this guest directory. |+| <span id="cua-sandbox-exec--timeout"></span>`--timeout` | | integer | | Stop the command after this many seconds (0: no limit). |+| <span id="cua-sandbox-exec--stdin"></span>`--stdin` | `-i` | boolean | `false` | Stream: run the command as argv (no shell), forward this command's stdin, write stdout and stderr as they arrive, set no time limit, pass SIGINT/SIGTERM/SIGHUP on, and kill the command when this process ends. Exits with the command's status (128 + n for signal n). |+| <span id="cua-sandbox-exec--local"></span>`--local` | | boolean | `false` | Look NAME up among local sandboxes only (same as `local:NAME`). |**Examples**```bash test="cli-shape" id="ref-cua-sandbox-exec"cua sb exec dev uname -acua sb exec dev 'ls /tmp | wc -l'++# A long-lived stdio stream, like `docker exec -i`: argv, not a shell line+cua sb exec -i dev -- bash -c 'wc -c'```### `cua sandbox shell`diff --git a/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx b/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdxindex fc5f2248d8..3550f682ac 100644--- a/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx+++ b/docs/content/docs/cua-cli/reference/cli/spaces-and-computers.mdx@@ -1153,14 +1153,21 @@ cua spacesd exec [OPTIONS] <URL> <COMMAND>...| `<URL>` | string | required | spacesd URL (`http://host:port`). || `<COMMAND>...` | string | required | Program and arguments. Repeatable. |-| Flag | Type | Default | Env var | Description |-| --- | --- | --- | --- | --- |-| <span id="cua-spacesd-exec--token"></span>`--token` | string | | `CUA_ENV_TOKEN` | spacesd token. |+| Flag | Short | Type | Default | Env var | Description |+| --- | --- | --- | --- | --- | --- |+| <span id="cua-spacesd-exec--user"></span>`--user` | | string | | | Run as this guest user. |+| <span id="cua-spacesd-exec--cwd"></span>`--cwd` | | string | | | Start in this guest directory. |+| <span id="cua-spacesd-exec--timeout"></span>`--timeout` | | integer | | | Stop the command after this many seconds (0: no limit). |+| <span id="cua-spacesd-exec--token"></span>`--token` | | string | | `CUA_ENV_TOKEN` | spacesd token. |+| <span id="cua-spacesd-exec--stdin"></span>`--stdin` | `-i` | boolean | `false` | | Stream: run the command as argv (no shell), forward this command's stdin, write stdout and stderr as they arrive, set no time limit, pass SIGINT/SIGTERM/SIGHUP on, and kill the command when this process ends. Exits with the command's status (128 + n for signal n). |**Examples**```bash test="cli-shape" id="ref-cua-spacesd-exec"cua spacesd exec http://127.0.0.1:3211 uname -a++# A long-lived stdio stream (stdin forwarded, no time limit, killed with this command)+cua spacesd exec -i http://127.0.0.1:3211 cat```### `cua spacesd cp`diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdxindex 69785c5876..1db606ba80 100644--- a/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx+++ b/docs/content/docs/cua-sdk/reference/rust/cua-sdk.mdx@@ -242,6 +242,7 @@ pub struct SpacesdCommand {pub tag: Option<String>,pub stdin: bool,pub pty: Option<PtySize>,+ pub kill_on_disconnect: bool,}```diff --git a/docs/content/docs/cua-sdk/reference/spacesd/index.mdx b/docs/content/docs/cua-sdk/reference/spacesd/index.mdxindex 0986355dc0..b5472018ba 100644--- a/docs/content/docs/cua-sdk/reference/spacesd/index.mdx+++ b/docs/content/docs/cua-sdk/reference/spacesd/index.mdx@@ -1385,27 +1385,29 @@ pub async fn resize(&self, cols: u32, rows: u32) -> Result<(), CuaError>### `SpacesdProcess.signal`-Sends a signal by name (`term`, `kill`, `SIGINT`, ...).+Sends a signal by name (`term`, `kill`, `SIGINT`, ...). With+`process_group`, to the process's whole group (everything it started),+as a terminal's Ctrl-C does; by default to the process alone.<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist><Tab value="Python">```python-async def signal(self, signal: str) -> None+async def signal(self, signal: str, process_group: bool = False) -> None```</Tab><Tab value="TypeScript">```ts-signal(signal: string, asyncOpts_?: { signal: AbortSignal }): Promise<void>+signal(signal: string, processGroup: boolean = false, asyncOpts_?: { signal: AbortSignal }): Promise<void>```</Tab><Tab value="Swift">```swift-func signal(signal: String) async throws+func signal(signal: String, processGroup: Bool = false) async throws```</Tab>@@ -1413,14 +1415,14 @@ func signal(signal: String) async throws```kotlin@Throws(CuaException::class)-suspend fun signal(signal: String)+suspend fun signal(signal: String, processGroup: Boolean = false)```</Tab><Tab value="Rust">```rust-pub async fn signal(&self, signal: String) -> Result<(), CuaError>+pub async fn signal(&self, signal: String, process_group: bool) -> Result<(), CuaError>```</Tab>@@ -1429,6 +1431,7 @@ pub async fn signal(&self, signal: String) -> Result<(), CuaError>| Parameter | Type | Default || --- | --- | --- || `signal` | `String` | required |+| `process_group` | `bool` | `false` |**Async** · **Raises** [`CuaError`](/cua-sdk/reference/errors)@@ -1591,6 +1594,7 @@ A command to run in the guest.| `tag` | `Option<String>` | `None` | Tag for reattaching (`attach(tag=…)`). || `stdin` | `bool` | `false` | Keep stdin open for `write_stdin`. || `pty` | [`Option<PtySize>`](#ptysize-record) | `None` | Run in a PTY of this size. |+| `kill_on_disconnect` / `killOnDisconnect` | `bool` | `false` | Kill the process (`term`, then `kill`) when this client's connection to cua-spacesd ends before the process does, including when the client process dies. Off by default: processes are detached and can be reattached by tag. |## `ProcessOutput` recorddiff --git a/libs/cua/crates/cua-cli/src/lib.rs b/libs/cua/crates/cua-cli/src/lib.rsindex 02e042a2cb..048d511447 100644--- a/libs/cua/crates/cua-cli/src/lib.rs+++ b/libs/cua/crates/cua-cli/src/lib.rs@@ -575,8 +575,12 @@ enum SpacesdCmd {},/// Run a command (argv, no shell).#[command(after_help = "Examples:- cua spacesd exec http://127.0.0.1:3211 uname -a")]+ cua spacesd exec http://127.0.0.1:3211 uname -a+ # A long-lived stdio stream (stdin forwarded, no time limit, killed with this command)+ cua spacesd exec -i http://127.0.0.1:3211 cat")]Exec {+ #[command(flatten)]+ flags: shell::ExecFlags,/// spacesd URL (`http://host:port`).url: String,/// spacesd token.@@ -1795,12 +1799,25 @@ async fn run_sdk(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {}}SpacesdCmd::Exec {+ flags,url,token,command,} => {let env = env_at(&cua, &url, token).await?;- return shell::exec(&env, &command, out).await;+ if flags.stdin {+ return shell::stream(+ &env,+ &command,+ flags.opts(None),+ tokio::io::stdin(),+ shell::os_signals(),+ out,+ &mut std::io::stderr(),+ )+ .await;+ }+ return shell::exec_with(&env, &command, flags.opts(None), out).await;}SpacesdCmd::Cp {url,@@ -2909,6 +2926,26 @@ mod tests {.await;assert_eq!(r.unwrap(), 0);assert_eq!(out, "hi\n");+ // The streaming form parses with the flags that go with it (it runs+ // against the real binary in tests/sandbox_do.rs: it reads stdin).+ for args in [+ &[+ "cua", "spacesd", "exec", "-i", "--user", "u", "--cwd", "/w", "URL", "cat",+ ][..],+ &[+ "cua",+ "sandbox",+ "exec",+ "-i",+ "--timeout",+ "0",+ "dev",+ "--",+ "cat",+ ],+ ] {+ assert!(Cli::try_parse_from(args).is_ok(), "{args:?}");+ }let (r, _) = cli(&["--embedded","spacesd",diff --git a/libs/cua/crates/cua-cli/src/sandbox.rs b/libs/cua/crates/cua-cli/src/sandbox.rsindex 5fb9b243ff..dce2aadb47 100644--- a/libs/cua/crates/cua-cli/src/sandbox.rs+++ b/libs/cua/crates/cua-cli/src/sandbox.rs@@ -428,8 +428,12 @@ pub enum SandboxCmd {/// runs it via SSH (`lume ssh`).#[command(after_help = "Examples:cua sb exec dev uname -a- cua sb exec dev 'ls /tmp | wc -l'")]+ cua sb exec dev 'ls /tmp | wc -l'+ # A long-lived stdio stream, like `docker exec -i`: argv, not a shell line+ cua sb exec -i dev -- bash -c 'wc -c'")]Exec {+ #[command(flatten)]+ flags: shell::ExecFlags,#[command(flatten)]at: Narrow,/// Sandbox name or ref (`local:NAME`).@@ -1863,10 +1867,20 @@ pub async fn run(}return Ok(0);}- SandboxCmd::Exec { name, command, at } => {+ SandboxCmd::Exec {+ flags,+ name,+ command,+ at,+ } => {let name = at.apply(&name)?;let env = match env_of(cua, &name).await {Err(CuaError::SpacesdNotAvailable(m)) => match agentless(cua, &name).await? {+ Some(_) if flags.any() => {+ return Err(CuaError::Unsupported(format!(+ "-i, --user, --cwd and --timeout need cua-spacesd in {name}"+ )));+ }Some(sb) => {return exec_agentless(&sb, &name, &command.join(" "), json_global, out).await;@@ -1875,7 +1889,24 @@ pub async fn run(},other => other?,};- let o = env.sh(command.join(" "), Some(120_000)).await?;+ if flags.stdin {+ return shell::stream(+ &env,+ &command,+ flags.opts(None),+ tokio::io::stdin(),+ shell::os_signals(),+ out,+ &mut std::io::stderr(),+ )+ .await;+ }+ let o = env+ .run(shell::with_opts(+ shell::command_of(&sh_argv(&command.join(" "))),+ flags.opts(Some(120_000)),+ ))+ .await?;let code = exit_code(&o);if json_global {line(diff --git a/libs/cua/crates/cua-cli/src/shell.rs b/libs/cua/crates/cua-cli/src/shell.rsindex 9bd4134b69..f2fa922ff3 100644--- a/libs/cua/crates/cua-cli/src/shell.rs+++ b/libs/cua/crates/cua-cli/src/shell.rs@@ -16,6 +16,7 @@ pub fn command_of(argv: &[String]) -> SpacesdCommand {tag: None,stdin: false,pty: None,+ kill_on_disconnect: false,}}@@ -26,12 +27,218 @@ pub async fn exec(argv: &[String],out: &mut dyn Write,) -> Result<i32, CuaError> {- let o = env.run(command_of(argv)).await?;+ exec_with(env, argv, StreamOpts::default(), out).await+}++/// `cmd` run as a user, in a directory, with a time limit.+pub fn with_opts(mut cmd: SpacesdCommand, opts: StreamOpts) -> SpacesdCommand {+ cmd.user = opts.user;+ cmd.cwd = opts.cwd;+ cmd.timeout_ms = opts.timeout_ms;+ cmd+}++/// [`exec`] as a user, in a directory, with a time limit.+pub async fn exec_with(+ env: &SpacesdClient,+ argv: &[String],+ opts: StreamOpts,+ out: &mut dyn Write,+) -> Result<i32, CuaError> {+ let o = env.run(with_opts(command_of(argv), opts)).await?;out.write_all(&o.stdout).ok();std::io::stderr().write_all(&o.stderr).ok();Ok(exit_code(&o))}+/// Options for [`stream`].+#[derive(Debug, Clone, Default)]+pub struct StreamOpts {+ /// Run as this guest user.+ pub user: Option<String>,+ /// Start in this guest directory.+ pub cwd: Option<String>,+ /// Stop the process after this many milliseconds (default: never).+ pub timeout_ms: Option<u32>,+}++/// Flags `exec` takes on both `cua spacesd` and `cua sandbox`.+#[derive(clap::Args, Debug, Clone, Default)]+pub struct ExecFlags {+ /// Stream: run the command as argv (no shell), forward this command's+ /// stdin, write stdout and stderr as they arrive, set no time limit,+ /// pass SIGINT/SIGTERM/SIGHUP on, and kill the command when this process+ /// ends. Exits with the command's status (128 + n for signal n).+ #[arg(short = 'i', long)]+ pub stdin: bool,+ /// Run as this guest user.+ #[arg(long)]+ pub user: Option<String>,+ /// Start in this guest directory.+ #[arg(long)]+ pub cwd: Option<String>,+ /// Stop the command after this many seconds (0: no limit).+ #[arg(long, value_name = "SECONDS")]+ pub timeout: Option<u32>,+}++impl ExecFlags {+ /// The options, with `default_ms` when `--timeout` is not given.+ pub fn opts(&self, default_ms: Option<u32>) -> StreamOpts {+ StreamOpts {+ user: self.user.clone(),+ cwd: self.cwd.clone(),+ timeout_ms: match self.timeout {+ Some(0) => None,+ Some(s) => Some(s.saturating_mul(1000)),+ None => default_ms,+ },+ }+ }++ /// Whether anything beyond a plain command is asked for.+ pub fn any(&self) -> bool {+ self.stdin || self.user.is_some() || self.cwd.is_some() || self.timeout.is_some()+ }+}++/// Names of the signals [`stream`] forwards, as `SpacesdProcess::signal`+/// takes them.+pub type SignalRx = tokio::sync::mpsc::UnboundedReceiver<&'static str>;++/// Forwards this process's SIGINT, SIGTERM and SIGHUP into the returned+/// channel until the receiver is dropped (Unix; elsewhere never fires).+pub fn os_signals() -> SignalRx {+ let (tx, rx) = tokio::sync::mpsc::unbounded_channel();+ #[cfg(unix)]+ {+ use tokio::signal::unix::{SignalKind, signal};+ for (kind, name) in [+ (SignalKind::interrupt(), "int"),+ (SignalKind::terminate(), "term"),+ (SignalKind::hangup(), "hup"),+ ] {+ let Ok(mut s) = signal(kind) else { continue };+ let tx = tx.clone();+ tokio::spawn(async move {+ while s.recv().await.is_some() {+ if tx.send(name).is_err() {+ break;+ }+ }+ });+ }+ }+ rx+}++/// Shell exit status for a process ended by a signal: 128 + its number.+fn signal_exit_code(name: &str) -> i32 {+ let n = match name {+ "hup" => 1,+ "int" => 2,+ "quit" => 3,+ "kill" => 9,+ "usr1" => 10,+ "usr2" => 12,+ "term" => 15,+ _ => 0,+ };+ 128 + n+}++/// Aborts its task when dropped, so a cancelled [`stream`] leaves no+/// helper holding the guest connection open.+struct AbortOnDrop(tokio::task::JoinHandle<()>);++impl Drop for AbortOnDrop {+ fn drop(&mut self) {+ self.0.abort();+ }+}++/// Runs argv in the guest as a long-lived stdio stream: `stdin` is forwarded+/// (EOF closes the guest's stdin), stdout and stderr are written as they+/// arrive, and the call returns the process's exit status (128 + n when a+/// signal ended it). There is no time limit unless `opts.timeout_ms` is set.+/// Signals received on `signals` are forwarded to the guest process group, and the+/// guest process is killed when this client's connection ends (so a host+/// that dies, even by SIGKILL, leaves nothing running).+pub async fn stream<R>(+ env: &SpacesdClient,+ argv: &[String],+ opts: StreamOpts,+ mut stdin: R,+ mut signals: SignalRx,+ out: &mut dyn Write,+ err: &mut dyn Write,+) -> Result<i32, CuaError>+where+ R: tokio::io::AsyncRead + Unpin + Send + 'static,+{+ let mut cmd = with_opts(command_of(argv), opts);+ cmd.stdin = true;+ cmd.kill_on_disconnect = true;+ let p = env.spawn(cmd).await?;+ let writer = p.clone();+ let _input = AbortOnDrop(tokio::spawn(async move {+ use tokio::io::AsyncReadExt;+ let mut buf = vec![0u8; 16 * 1024];+ loop {+ match stdin.read(&mut buf).await {+ Ok(0) | Err(_) => {+ let _ = writer.close_stdin().await;+ break;+ }+ Ok(n) => {+ if writer.write_stdin(buf[..n].to_vec()).await.is_err() {+ break;+ }+ }+ }+ }+ }));+ let forward = p.clone();+ let _sigs = AbortOnDrop(tokio::spawn(async move {+ while let Some(name) = signals.recv().await {+ let _ = forward.signal(name.into(), true).await;+ }+ }));+ async {+ loop {+ let Some(ev) = p.next_event().await? else {+ return Ok(1);+ };+ if let Some(exit) = ev.exit {+ if let Some(e) = &exit.error {+ let _ = writeln!(err, "cua: {e}");+ return Ok(127);+ }+ if exit.timed_out {+ let _ = writeln!(err, "cua: timed out");+ return Ok(124);+ }+ return Ok(match (exit.code, &exit.signal) {+ (Some(c), _) => c,+ (None, Some(sig)) => signal_exit_code(sig),+ (None, None) => 1,+ });+ }+ match ev.kind {+ cua_sdk::ProcessEventKind::Stderr => {+ let _ = err.write_all(&ev.data);+ let _ = err.flush();+ }+ _ => {+ let _ = out.write_all(&ev.data);+ let _ = out.flush();+ }+ }+ }+ }+ .await+}+/// Exit code of a finished process.pub fn exit_code(o: &cua_sdk::ProcessOutput) -> i32 {o.exit.code.unwrap_or(if o.exit.success { 0 } else { 1 })@@ -180,3 +387,123 @@ pub async fn interactive(result?;Ok(code)}++#[cfg(test)]+mod tests {+ use super::*;+ use cua_daemon::fixtures;+ use cua_sdk::{Cua, CuaConfig};+ use std::{sync::Arc, time::Duration};+ use tokio::sync::mpsc::unbounded_channel;++ async fn client(url: &str) -> Arc<SpacesdClient> {+ let home = tempfile::tempdir().unwrap();+ let cua = Cua::embedded(CuaConfig {+ state_dir: Some(home.path().display().to_string()),+ ..Default::default()+ })+ .unwrap();+ cua.spacesd(url.to_string(), Some("t".into()))+ .await+ .unwrap()+ }++ fn argv(words: &[&str]) -> Vec<String> {+ words.iter().map(|w| w.to_string()).collect()+ }++ fn no_signals() -> SignalRx {+ unbounded_channel().1+ }++ /// Runs `stream` to the end with `input` as stdin.+ async fn run(+ env: &SpacesdClient,+ words: &[&str],+ opts: StreamOpts,+ input: &'static [u8],+ ) -> (i32, String, String) {+ let (mut out, mut err) = (Vec::new(), Vec::new());+ let code = stream(+ env,+ &argv(words),+ opts,+ input,+ no_signals(),+ &mut out,+ &mut err,+ )+ .await+ .unwrap();+ (+ code,+ String::from_utf8(out).unwrap(),+ String::from_utf8(err).unwrap(),+ )+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn stdin_round_trips_and_the_start_request_is_a_stream() {+ let fx = fixtures::start_env(Some("t"), None).await;+ let env = client(&fx.url).await;+ let opts = StreamOpts {+ user: Some("agent".into()),+ cwd: Some("/work".into()),+ timeout_ms: None,+ };+ let (code, out, _) = run(&env, &["cat"], opts, b"hello\nworld").await;+ assert_eq!((code, out.as_str()), (0, "hello\nworld"));+ let started = fx.mock.state.started_processes();+ let req = started.last().unwrap();+ let cfg = req.config.as_ref().unwrap();+ assert!(req.stdin && req.kill_on_disconnect && req.pty.is_none());+ assert!(cfg.timeout.is_none(), "a stream has no time limit");+ assert_eq!((cfg.user.as_str(), cfg.cwd.as_str()), ("agent", "/work"));+ assert_eq!(cfg.command, "cat", "argv is passed through, not joined");+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn exit_codes_and_stderr_propagate() {+ let fx = fixtures::start_env(Some("t"), None).await;+ let env = client(&fx.url).await;+ let (code, out, err) = run(&env, &["fail", "7"], StreamOpts::default(), b"").await;+ assert_eq!((code, out.as_str(), err.as_str()), (7, "", "failed\n"));+ let (code, _, err) = run(&env, &["nope"], StreamOpts::default(), b"").await;+ assert_eq!(code, 127, "{err}");+ assert!(err.contains("executable not found"), "{err}");+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn signals_are_forwarded_and_become_128_plus_n() {+ let fx = fixtures::start_env(Some("t"), None).await;+ let env = client(&fx.url).await;+ let (tx, rx) = unbounded_channel();+ let (mut out, mut err) = (Vec::new(), Vec::new());+ // Stdin that never ends, so only the signal can finish `cat`.+ let (_keep, held) = tokio::io::duplex(8);+ let sender = tokio::spawn(async move {+ tokio::time::sleep(Duration::from_millis(300)).await;+ tx.send("term").unwrap();+ });+ let code = stream(+ &env,+ &argv(&["cat"]),+ StreamOpts::default(),+ held,+ rx,+ &mut out,+ &mut err,+ )+ .await+ .unwrap();+ sender.await.unwrap();+ assert_eq!(code, 128 + 15);+ let signals = fx.mock.state.signals();+ assert_eq!(signals.len(), 1);+ assert_eq!(signals[0].1, cua_spacesd_client::pb::Signal::Term as i32);+ assert!(+ signals[0].2,+ "a client signal reaches the whole process group"+ );+ }+}diff --git a/libs/cua/crates/cua-cli/tests/sandbox_do.rs b/libs/cua/crates/cua-cli/tests/sandbox_do.rsindex e11ec327fe..be14df3182 100644--- a/libs/cua/crates/cua-cli/tests/sandbox_do.rs+++ b/libs/cua/crates/cua-cli/tests/sandbox_do.rs@@ -6,6 +6,7 @@ use common::*;use cua_daemon::fixtures;use cua_host::testing::FakeRelay;use serde_json::json;+use std::time::Duration;async fn direct(h: &Home, url: &str, name: &str) {direct_with(h, url, name, "t").await;@@ -89,6 +90,38 @@ async fn sandbox_lifecycle_exec_and_compat_aliases() {.run(&["--embedded", "sb", "exec", "dev", "--", "fail", "4"]).await;assert_eq!(o.code, 4);+ // -i streams the argv (no shell join), with no 120 s cap, and keeps the+ // command's own exit code.+ let o = h+ .run(&[+ "--embedded",+ "sb",+ "exec",+ "-i",+ "dev",+ "--",+ "echo",+ "streamed",+ ])+ .await;+ o.ok();+ assert_eq!(o.stdout, "streamed\n");+ let o = h+ .run(&[+ "--embedded",+ "sb",+ "exec",+ "-i",+ "--timeout",+ "30",+ "dev",+ "--",+ "fail",+ "4",+ ])+ .await;+ assert_eq!(o.code, 4, "{o:?}");+ exec_stream_round_trip(&h, &env).await;let o = h.run(&["--embedded", "--json", "sb", "exec", "dev", "echo hi"]).await;@@ -1003,3 +1036,62 @@ async fn sandbox_info_connection_prints_the_spacesd_url_and_token() {assert!(!o.stdout.contains("s3cret-token"), "{o:?}");}}++/// `sb exec -i` against the real binary: stdin round trip, signal+/// forwarding, and the guest process dying with a killed client.+async fn exec_stream_round_trip(h: &Home, env: &fixtures::SpacesdFixture) {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let mut child = h.spawn(&["--embedded", "sb", "exec", "-i", "dev", "--", "cat"]);+ let mut stdin = child.stdin.take().unwrap();+ let mut stdout = child.stdout.take().unwrap();+ stdin.write_all(b"ping\n").await.unwrap();+ let mut buf = [0u8; 5];+ tokio::time::timeout(Duration::from_secs(30), stdout.read_exact(&mut buf))+ .await+ .expect("echo in time")+ .unwrap();+ assert_eq!(&buf, b"ping\n");+ // EOF on stdin ends cat, and the exit code comes back.+ drop(stdin);+ let status = tokio::time::timeout(Duration::from_secs(30), child.wait())+ .await+ .expect("exit in time")+ .unwrap();+ assert_eq!(status.code(), Some(0));++ // SIGTERM to the client is forwarded: 128 + 15.+ let mut child = h.spawn(&["--embedded", "sb", "exec", "-i", "dev", "--", "cat"]);+ let mut stdin = child.stdin.take().unwrap();+ let mut stdout = child.stdout.take().unwrap();+ stdin.write_all(b"x").await.unwrap();+ stdout.read_exact(&mut [0u8; 1]).await.unwrap();+ let n_before = env.mock.state.signals().len();+ // SAFETY: signalling our own child.+ unsafe { libc::kill(child.id().unwrap() as i32, libc::SIGTERM) };+ let status = tokio::time::timeout(Duration::from_secs(30), child.wait())+ .await+ .expect("exit in time")+ .unwrap();+ assert_eq!(status.code(), Some(128 + 15));+ assert_eq!(env.mock.state.signals().len(), n_before + 1);++ // A SIGKILLed client cannot forward anything: the guest process still+ // dies, because the stream carried kill_on_disconnect.+ let mut child = h.spawn(&["--embedded", "sb", "exec", "-i", "dev", "--", "cat"]);+ let mut stdin = child.stdin.take().unwrap();+ let mut stdout = child.stdout.take().unwrap();+ stdin.write_all(b"y").await.unwrap();+ stdout.read_exact(&mut [0u8; 1]).await.unwrap();+ let pid = env.mock.state.last_pid().unwrap();+ assert!(env.mock.state.process_end(pid).is_none());+ child.kill().await.unwrap();+ let mut ended = None;+ for _ in 0..100 {+ ended = env.mock.state.process_end(pid);+ if ended.is_some() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ assert!(ended.is_some(), "guest process survived its client");+}diff --git a/libs/cua/crates/cua-sdk/src/native/spacesd.rs b/libs/cua/crates/cua-sdk/src/native/spacesd.rsindex 0a69d1ef04..3e5fdd8582 100644--- a/libs/cua/crates/cua-sdk/src/native/spacesd.rs+++ b/libs/cua/crates/cua-sdk/src/native/spacesd.rs@@ -35,6 +35,7 @@ impl SpacesdCommand {if let Some(p) = self.pty {c = c.pty(p.cols, p.rows);}+ c.kill_on_disconnect = self.kill_on_disconnect;c}}@@ -219,8 +220,11 @@ impl SpacesdProcess {.await}- /// Sends a signal by name (`term`, `kill`, `SIGINT`, ...).- pub async fn signal(&self, signal: String) -> Result<()> {+ /// Sends a signal by name (`term`, `kill`, `SIGINT`, ...). With+ /// `process_group`, to the process's whole group (everything it started),+ /// as a terminal's Ctrl-C does; by default to the process alone.+ #[uniffi::method(default(process_group = false))]+ pub async fn signal(&self, signal: String, process_group: bool) -> Result<()> {let sig = parse_signal(&signal)?;let (client, process) = (self.client.clone(), Some(self.selector()));run(async move {@@ -229,7 +233,7 @@ impl SpacesdProcess {.signal_process(pb::SignalProcessRequest {process,signal: sig as i32,- process_group: false,+ process_group,}).await?;Ok(())@@ -239,7 +243,7 @@ impl SpacesdProcess {/// SIGKILL.pub async fn kill(&self) -> Result<()> {- self.signal("kill".into()).await+ self.signal("kill".into(), false).await}/// Resizes the PTY.diff --git a/libs/cua/crates/cua-sdk/src/types.rs b/libs/cua/crates/cua-sdk/src/types.rsindex a186cea2c9..4bb036bcb4 100644--- a/libs/cua/crates/cua-sdk/src/types.rs+++ b/libs/cua/crates/cua-sdk/src/types.rs@@ -120,6 +120,12 @@ pub struct SpacesdCommand {/// Run in a PTY of this size.#[uniffi(default = None)]pub pty: Option<PtySize>,+ /// Kill the process (`term`, then `kill`) when this client's connection+ /// to cua-spacesd ends before the process does, including when the+ /// client process dies. Off by default: processes are detached and can be+ /// reattached by tag.+ #[uniffi(default = false)]+ pub kill_on_disconnect: bool,}/// How a process ended.diff --git a/libs/cua/crates/cua-sdk/src/web/mod.rs b/libs/cua/crates/cua-sdk/src/web/mod.rsindex 4d79dd584e..96b3fe7c39 100644--- a/libs/cua/crates/cua-sdk/src/web/mod.rs+++ b/libs/cua/crates/cua-sdk/src/web/mod.rs@@ -307,6 +307,7 @@ impl SpacesdClient {tag: None,stdin: false,pty: None,+ kill_on_disconnect: false,}).await})diff --git a/libs/cua/crates/cua-sdk/tests/ffi_threads.rs b/libs/cua/crates/cua-sdk/tests/ffi_threads.rsindex 0db2b94112..f3616c1089 100644--- a/libs/cua/crates/cua-sdk/tests/ffi_threads.rs+++ b/libs/cua/crates/cua-sdk/tests/ffi_threads.rs@@ -89,6 +89,7 @@ fn cmd(program: &str, args: &[&str]) -> SpacesdCommand {tag: None,stdin: false,pty: None,+ kill_on_disconnect: false,}}diff --git a/libs/cua/crates/cua-sdk/tests/topologies.rs b/libs/cua/crates/cua-sdk/tests/topologies.rsindex 97cd0d802d..5a9172aa72 100644--- a/libs/cua/crates/cua-sdk/tests/topologies.rs+++ b/libs/cua/crates/cua-sdk/tests/topologies.rs@@ -136,6 +136,7 @@ fn cmd(program: &str, args: &[&str]) -> SpacesdCommand {tag: None,stdin: false,pty: None,+ kill_on_disconnect: false,}}diff --git a/libs/cua/crates/cua-spacesd-client/src/testing.rs b/libs/cua/crates/cua-spacesd-client/src/testing.rsindex 7272f84713..9c0b3bb333 100644--- a/libs/cua/crates/cua-spacesd-client/src/testing.rs+++ b/libs/cua/crates/cua-spacesd-client/src/testing.rs@@ -129,6 +129,10 @@ pub struct MockState {files: Mutex<HashMap<String, Vec<u8>>>,uploads: Mutex<HashMap<String, Upload>>,procs: Mutex<HashMap<u32, Proc>>,+ /// `StartProcess` requests received, in order.+ started: Mutex<Vec<pb::StartProcessRequest>>,+ /// Signals delivered through `SignalProcess` as `(pid, signal)`.+ signalled: Mutex<Vec<(u32, i32, bool)>>,next_pid: AtomicU32,clipboard: Mutex<(Option<String>, u64)>,cursor: Mutex<(f64, f64)>,@@ -223,6 +227,31 @@ pub struct TeleportImport {}impl MockState {+ /// `StartProcess` requests received, in order.+ pub fn started_processes(&self) -> Vec<pb::StartProcessRequest> {+ self.started.lock().unwrap().clone()+ }++ /// The pid of the newest process started.+ pub fn last_pid(&self) -> Option<u32> {+ self.procs.lock().unwrap().keys().max().copied()+ }++ /// How the process `pid` ended, or `None` while it runs.+ pub fn process_end(&self, pid: u32) -> Option<pb::ProcessEnd> {+ self.procs+ .lock()+ .unwrap()+ .get(&pid)+ .and_then(|p| p.end.clone())+ }++ /// Signals delivered by `SignalProcess` as `(pid, signal number,+ /// whole process group)`.+ pub fn signals(&self) -> Vec<(u32, i32, bool)> {+ self.signalled.lock().unwrap().clone()+ }+/// Session bundles committed through `TeleportService.ImportSession`/// and not wiped since.pub fn teleport_imports(&self) -> Vec<TeleportImport> {@@ -911,6 +940,10 @@ impl Svc {}fn finish(&self, pid: u32, code: Option<i32>, timed_out: bool, error: String) {+ self.finish_with(pid, code, timed_out, error, pb::Signal::Kill as i32);+ }++ fn finish_with(&self, pid: u32, code: Option<i32>, timed_out: bool, error: String, sig: i32) {let mut procs = self.0.procs.lock().unwrap();if let Some(p) = procs.get_mut(&pid)&& p.end.is_none()@@ -918,7 +951,7 @@ impl Svc {p.end = Some(pb::ProcessEnd {exit_code: code,signal: if code.is_none() && error.is_empty() {- pb::Signal::Kill as i32+ sig} else {0},@@ -958,11 +991,28 @@ impl Svc {pid: u32,from: u64,keepalive: Duration,+ kill_on_disconnect: bool,wrap: fn(pb::ProcessEvent) -> T,) -> Stream<T> {let (tx, rx) = mpsc::channel::<Result<T, Status>>(64);let svc = self.clone();tokio::spawn(async move {+ // Dropped without `finished` when the client goes away first.+ struct KillGuard(Svc, u32, bool);+ impl Drop for KillGuard {+ fn drop(&mut self) {+ if self.2 {+ self.0.finish_with(+ self.1,+ None,+ false,+ String::new(),+ pb::Signal::Term as i32,+ );+ }+ }+ }+ let mut guard = KillGuard(svc.clone(), pid, kill_on_disconnect);let (start, changed) = {let procs = svc.0.procs.lock().unwrap();let p = &procs[&pid];@@ -1020,10 +1070,12 @@ impl Svc {}}if let Some(end) = end {+ guard.2 = false;let _ = tx.send(Ok(send(pb::process_event::Event::End(end)))).await;return;}tokio::select! {+ _ = tx.closed() => return,_ = notified => {}_ = tokio::time::sleep(keepalive) => {let ev = pb::process_event::Event::Keepalive(pb::KeepAlive {});@@ -1048,6 +1100,7 @@ impl ProcessService for Svc {req: tonic::Request<pb::StartProcessRequest>,) -> Result<tonic::Response<Self::StartProcessStream>, Status> {let req = req.into_inner();+ self.0.started.lock().unwrap().push(req.clone());let cfg = req.config.clone().unwrap_or_default();let script = parse_script(&cfg);let pid = self.0.next_pid.fetch_add(1, Ordering::Relaxed);@@ -1161,6 +1214,7 @@ impl ProcessService for Svc {pid,0,keepalive,+ req.kill_on_disconnect,|e| pb::StartProcessResponse { event: Some(e) },)))}@@ -1187,6 +1241,7 @@ impl ProcessService for Svc {pid,from,keepalive,+ false,|e| pb::ConnectProcessResponse { event: Some(e) },)))}@@ -1303,8 +1358,14 @@ impl ProcessService for Svc {&self,req: tonic::Request<pb::SignalProcessRequest>,) -> Result<tonic::Response<pb::SignalProcessResponse>, Status> {- let pid = self.find(&req.into_inner().process)?;- self.finish(pid, None, false, String::new());+ let req = req.into_inner();+ let pid = self.find(&req.process)?;+ self.0+ .signalled+ .lock()+ .unwrap()+ .push((pid, req.signal, req.process_group));+ self.finish_with(pid, None, false, String::new(), req.signal);Ok(tonic::Response::new(pb::SignalProcessResponse {}))}diff --git a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.ktindex a26509d7f4..5a450351a2 100644--- a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt+++ b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt@@ -2468,7 +2468,7 @@ external fun uniffi_cua_sdk_fn_method_spacesdprocess_pid(`ptr`: Long,uniffi_out_): Intexternal fun uniffi_cua_sdk_fn_method_spacesdprocess_resize(`ptr`: Long,`cols`: Int,`rows`: Int,): Long-external fun uniffi_cua_sdk_fn_method_spacesdprocess_signal(`ptr`: Long,`signal`: RustBuffer.ByValue,+external fun uniffi_cua_sdk_fn_method_spacesdprocess_signal(`ptr`: Long,`signal`: RustBuffer.ByValue,`processGroup`: Byte,): Longexternal fun uniffi_cua_sdk_fn_method_spacesdprocess_tag(`ptr`: Long,uniffi_out_err: UniffiRustCallStatus,): RustBuffer.ByValue@@ -3918,7 +3918,7 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {if (lib.uniffi_cua_sdk_checksum_method_spacesdprocess_resize() != 46607.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}- if (lib.uniffi_cua_sdk_checksum_method_spacesdprocess_signal() != 61925.toShort()) {+ if (lib.uniffi_cua_sdk_checksum_method_spacesdprocess_signal() != 44588.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}if (lib.uniffi_cua_sdk_checksum_method_spacesdprocess_tag() != 24315.toShort()) {@@ -21863,9 +21863,11 @@ public interface SpacesdProcessInterface {suspend fun `resize`(`cols`: kotlin.UInt, `rows`: kotlin.UInt)/**- * Sends a signal by name (`term`, `kill`, `SIGINT`, ...).+ * Sends a signal by name (`term`, `kill`, `SIGINT`, ...). With+ * `process_group`, to the process's whole group (everything it started),+ * as a terminal's Ctrl-C does; by default to the process alone.*/- suspend fun `signal`(`signal`: kotlin.String)+ suspend fun `signal`(`signal`: kotlin.String, `processGroup`: kotlin.Boolean = false)/*** Tag, when set.@@ -22132,16 +22134,18 @@ open class SpacesdProcess: Disposable, AutoCloseable, SpacesdProcessInterface/**- * Sends a signal by name (`term`, `kill`, `SIGINT`, ...).+ * Sends a signal by name (`term`, `kill`, `SIGINT`, ...). With+ * `process_group`, to the process's whole group (everything it started),+ * as a terminal's Ctrl-C does; by default to the process alone.*/@Throws(CuaException::class)@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")- override suspend fun `signal`(`signal`: kotlin.String) {+ override suspend fun `signal`(`signal`: kotlin.String, `processGroup`: kotlin.Boolean) {return uniffiRustCallAsync(callWithHandle { uniffiHandle ->UniffiLib.uniffi_cua_sdk_fn_method_spacesdprocess_signal(uniffiHandle,- FfiConverterString.lower(`signal`),+ FfiConverterString.lower(`signal`),FfiConverterBoolean.lower(`processGroup`),)},{ future, callback, continuation -> UniffiLib.ffi_cua_sdk_rust_future_poll_void(future, callback, continuation) },@@ -35927,6 +35931,14 @@ data class SpacesdCommand (* Run in a PTY of this size.*/var `pty`: PtySize? = null+ ,+ /**+ * Kill the process (`term`, then `kill`) when this client's connection+ * to cua-spacesd ends before the process does, including when the+ * client process dies. Off by default: processes are detached and can be+ * reattached by tag.+ */+ var `killOnDisconnect`: kotlin.Boolean = false){@@ -35952,6 +35964,7 @@ public object FfiConverterTypeSpacesdCommand: FfiConverterRustBuffer<SpacesdCommFfiConverterOptionalString.read(buf),FfiConverterBoolean.read(buf),FfiConverterOptionalTypePtySize.read(buf),+ FfiConverterBoolean.read(buf),)}@@ -35964,7 +35977,8 @@ public object FfiConverterTypeSpacesdCommand: FfiConverterRustBuffer<SpacesdCommFfiConverterOptionalUInt.allocationSize(value.`timeoutMs`) +FfiConverterOptionalString.allocationSize(value.`tag`) +FfiConverterBoolean.allocationSize(value.`stdin`) +- FfiConverterOptionalTypePtySize.allocationSize(value.`pty`)+ FfiConverterOptionalTypePtySize.allocationSize(value.`pty`) ++ FfiConverterBoolean.allocationSize(value.`killOnDisconnect`))override fun write(value: SpacesdCommand, buf: ByteBuffer) {@@ -35977,6 +35991,7 @@ public object FfiConverterTypeSpacesdCommand: FfiConverterRustBuffer<SpacesdCommFfiConverterOptionalString.write(value.`tag`, buf)FfiConverterBoolean.write(value.`stdin`, buf)FfiConverterOptionalTypePtySize.write(value.`pty`, buf)+ FfiConverterBoolean.write(value.`killOnDisconnect`, buf)}}diff --git a/libs/cua/python/src/cua/_native.py b/libs/cua/python/src/cua/_native.pyindex 8c32765ecc..2c962bceff 100644--- a/libs/cua/python/src/cua/_native.py+++ b/libs/cua/python/src/cua/_native.py@@ -1301,7 +1301,7 @@ def _uniffi_check_api_checksums(lib):raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_spacesdprocess_resize() != 46607:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")- if lib.uniffi_cua_sdk_checksum_method_spacesdprocess_signal() != 61925:+ if lib.uniffi_cua_sdk_checksum_method_spacesdprocess_signal() != 44588:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_spacesdprocess_tag() != 24315:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")@@ -4129,6 +4129,7 @@ _UniffiLib.uniffi_cua_sdk_fn_method_spacesdprocess_resize.restype = ctypes.c_uin_UniffiLib.uniffi_cua_sdk_fn_method_spacesdprocess_signal.argtypes = (ctypes.c_uint64,_UniffiRustBuffer,+ ctypes.c_int8,)_UniffiLib.uniffi_cua_sdk_fn_method_spacesdprocess_signal.restype = ctypes.c_uint64_UniffiLib.uniffi_cua_sdk_fn_method_spacesdprocess_tag.argtypes = (@@ -19971,7 +19972,7 @@ class SpacesdCommand:"""A command to run in the guest."""- def __init__(self, *, program:str, args:typing.List[str] = _DEFAULT, env:dict[str, str] = _DEFAULT, cwd:typing.Optional[str] = _DEFAULT, user:typing.Optional[str] = _DEFAULT, timeout_ms:typing.Optional[int] = _DEFAULT, tag:typing.Optional[str] = _DEFAULT, stdin:bool = False, pty:typing.Optional[PtySize] = _DEFAULT):+ def __init__(self, *, program:str, args:typing.List[str] = _DEFAULT, env:dict[str, str] = _DEFAULT, cwd:typing.Optional[str] = _DEFAULT, user:typing.Optional[str] = _DEFAULT, timeout_ms:typing.Optional[int] = _DEFAULT, tag:typing.Optional[str] = _DEFAULT, stdin:bool = False, pty:typing.Optional[PtySize] = _DEFAULT, kill_on_disconnect:bool = False):self.program = programif args is _DEFAULT:self.args = []@@ -20002,12 +20003,13 @@ class SpacesdCommand:self.pty = Noneelse:self.pty = pty+ self.kill_on_disconnect = kill_on_disconnectdef __str__(self):- return "SpacesdCommand(program={}, args={}, env={}, cwd={}, user={}, timeout_ms={}, tag={}, stdin={}, pty={})".format(self.program, self.args, self.env, self.cwd, self.user, self.timeout_ms, self.tag, self.stdin, self.pty)+ return "SpacesdCommand(program={}, args={}, env={}, cwd={}, user={}, timeout_ms={}, tag={}, stdin={}, pty={}, kill_on_disconnect={})".format(self.program, self.args, self.env, self.cwd, self.user, self.timeout_ms, self.tag, self.stdin, self.pty, self.kill_on_disconnect)def __eq__(self, other):if self.program != other.program:return False@@ -20027,6 +20029,8 @@ class SpacesdCommand:return Falseif self.pty != other.pty:return False+ if self.kill_on_disconnect != other.kill_on_disconnect:+ return Falsereturn Trueclass _UniffiFfiConverterTypeSpacesdCommand(_UniffiConverterRustBuffer):@@ -20042,6 +20046,7 @@ class _UniffiFfiConverterTypeSpacesdCommand(_UniffiConverterRustBuffer):tag=_UniffiFfiConverterOptionalString.read(buf),stdin=_UniffiFfiConverterBoolean.read(buf),pty=_UniffiFfiConverterOptionalTypePtySize.read(buf),+ kill_on_disconnect=_UniffiFfiConverterBoolean.read(buf),)@staticmethod@@ -20055,6 +20060,7 @@ class _UniffiFfiConverterTypeSpacesdCommand(_UniffiConverterRustBuffer):_UniffiFfiConverterOptionalString.check_lower(value.tag)_UniffiFfiConverterBoolean.check_lower(value.stdin)_UniffiFfiConverterOptionalTypePtySize.check_lower(value.pty)+ _UniffiFfiConverterBoolean.check_lower(value.kill_on_disconnect)@staticmethoddef write(value, buf):@@ -20067,6 +20073,7 @@ class _UniffiFfiConverterTypeSpacesdCommand(_UniffiConverterRustBuffer):_UniffiFfiConverterOptionalString.write(value.tag, buf)_UniffiFfiConverterBoolean.write(value.stdin, buf)_UniffiFfiConverterOptionalTypePtySize.write(value.pty, buf)+ _UniffiFfiConverterBoolean.write(value.kill_on_disconnect, buf)@dataclassclass SpacesdHttpHeader:@@ -25567,9 +25574,11 @@ class SpacesdProcessProtocol(typing.Protocol):Resizes the PTY."""raise NotImplementedError- async def signal(self, signal: str) -> None:+ async def signal(self, signal: str,process_group: bool = False) -> None:"""- Sends a signal by name (`term`, `kill`, `SIGINT`, ...).+ Sends a signal by name (`term`, `kill`, `SIGINT`, ...). With+ `process_group`, to the process's whole group (everything it started),+ as a terminal's Ctrl-C does; by default to the process alone."""raise NotImplementedErrordef tag(self, ) -> typing.Optional[str]:@@ -25735,15 +25744,20 @@ class SpacesdProcess(SpacesdProcessProtocol):_uniffi_lift_return,_uniffi_error_converter,)- async def signal(self, signal: str) -> None:+ async def signal(self, signal: str,process_group: bool = False) -> None:"""- Sends a signal by name (`term`, `kill`, `SIGINT`, ...).+ Sends a signal by name (`term`, `kill`, `SIGINT`, ...). With+ `process_group`, to the process's whole group (everything it started),+ as a terminal's Ctrl-C does; by default to the process alone."""_UniffiFfiConverterString.check_lower(signal)++ _UniffiFfiConverterBoolean.check_lower(process_group)_uniffi_lowered_args = (self._uniffi_clone_handle(),_UniffiFfiConverterString.lower(signal),+ _UniffiFfiConverterBoolean.lower(process_group),)_uniffi_lift_return = lambda val: None_uniffi_error_converter = _UniffiFfiConverterTypeCuaErrordiff --git a/libs/cua/swift/Sources/Cua/Cua.swift b/libs/cua/swift/Sources/Cua/Cua.swiftindex 420c58185d..7ef5ad05fb 100644--- a/libs/cua/swift/Sources/Cua/Cua.swift+++ b/libs/cua/swift/Sources/Cua/Cua.swift@@ -28,7 +28,7 @@ public extension SpacesdCommand {init(_ program: String, _ args: [String] = [], stdin: Bool = false) {self.init(program: program, args: args, env: [:], cwd: nil, user: nil,- timeoutMs: nil, tag: nil, stdin: stdin, pty: nil+ timeoutMs: nil, tag: nil, stdin: stdin, pty: nil, killOnDisconnect: false)}}diff --git a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swiftindex beac67998e..a99843b170 100644--- a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift+++ b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift@@ -12776,9 +12776,11 @@ public protocol SpacesdProcessProtocol: AnyObject, Sendable {func resize(cols: UInt32, rows: UInt32) async throws/**- * Sends a signal by name (`term`, `kill`, `SIGINT`, ...).+ * Sends a signal by name (`term`, `kill`, `SIGINT`, ...). With+ * `process_group`, to the process's whole group (everything it started),+ * as a terminal's Ctrl-C does; by default to the process alone.*/- func signal(signal: String) async throws+ func signal(signal: String, processGroup: Bool) async throws/*** Tag, when set.@@ -12972,15 +12974,17 @@ open func resize(cols: UInt32, rows: UInt32)async throws {}/**- * Sends a signal by name (`term`, `kill`, `SIGINT`, ...).+ * Sends a signal by name (`term`, `kill`, `SIGINT`, ...). With+ * `process_group`, to the process's whole group (everything it started),+ * as a terminal's Ctrl-C does; by default to the process alone.*/-open func signal(signal: String)async throws {+open func signal(signal: String, processGroup: Bool = false)async throws {returntry await uniffiRustCallAsync(rustFutureFunc: {uniffi_cua_sdk_fn_method_spacesdprocess_signal(self.uniffiCloneHandle(),- FfiConverterString.lower(signal)+ FfiConverterString.lower(signal),FfiConverterBool.lower(processGroup))},pollFunc: ffi_cua_sdk_rust_future_poll_void,@@ -31293,6 +31297,13 @@ public struct SpacesdCommand: Equatable, Hashable {* Run in a PTY of this size.*/public var pty: PtySize?+ /**+ * Kill the process (`term`, then `kill`) when this client's connection+ * to cua-spacesd ends before the process does, including when the+ * client process dies. Off by default: processes are detached and can be+ * reattached by tag.+ */+ public var killOnDisconnect: Bool// Default memberwise initializers are never public by default, so we// declare one manually.@@ -31323,7 +31334,13 @@ public struct SpacesdCommand: Equatable, Hashable {*/stdin: Bool = false,/*** Run in a PTY of this size.- */pty: PtySize? = nil) {+ */pty: PtySize? = nil,+ /**+ * Kill the process (`term`, then `kill`) when this client's connection+ * to cua-spacesd ends before the process does, including when the+ * client process dies. Off by default: processes are detached and can be+ * reattached by tag.+ */killOnDisconnect: Bool = false) {self.program = programself.args = argsself.env = env@@ -31333,6 +31350,7 @@ public struct SpacesdCommand: Equatable, Hashable {self.tag = tagself.stdin = stdinself.pty = pty+ self.killOnDisconnect = killOnDisconnect}@@ -31359,7 +31377,8 @@ public struct FfiConverterTypeSpacesdCommand: FfiConverterRustBuffer {timeoutMs: FfiConverterOptionUInt32.read(from: &buf),tag: FfiConverterOptionString.read(from: &buf),stdin: FfiConverterBool.read(from: &buf),- pty: FfiConverterOptionTypePtySize.read(from: &buf)+ pty: FfiConverterOptionTypePtySize.read(from: &buf),+ killOnDisconnect: FfiConverterBool.read(from: &buf))}@@ -31373,6 +31392,7 @@ public struct FfiConverterTypeSpacesdCommand: FfiConverterRustBuffer {FfiConverterOptionString.write(value.tag, into: &buf)FfiConverterBool.write(value.stdin, into: &buf)FfiConverterOptionTypePtySize.write(value.pty, into: &buf)+ FfiConverterBool.write(value.killOnDisconnect, into: &buf)}}@@ -39914,7 +39934,7 @@ private let initializationResult: InitializationResult = {if (uniffi_cua_sdk_checksum_method_spacesdprocess_resize() != 46607) {return InitializationResult.apiChecksumMismatch}- if (uniffi_cua_sdk_checksum_method_spacesdprocess_signal() != 61925) {+ if (uniffi_cua_sdk_checksum_method_spacesdprocess_signal() != 44588) {return InitializationResult.apiChecksumMismatch}if (uniffi_cua_sdk_checksum_method_spacesdprocess_tag() != 24315) {diff --git a/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h b/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.hindex e1bbf8b903..09ddf4ad52 100644--- a/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h+++ b/libs/cua/swift/Sources/cua_sdkFFI/include/cua_sdkFFI.h@@ -2464,7 +2464,7 @@ uint64_t uniffi_cua_sdk_fn_method_spacesdprocess_resize(uint64_t ptr, uint32_t c#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACESDPROCESS_SIGNAL#define UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACESDPROCESS_SIGNAL-uint64_t uniffi_cua_sdk_fn_method_spacesdprocess_signal(uint64_t ptr, RustBuffer signal+uint64_t uniffi_cua_sdk_fn_method_spacesdprocess_signal(uint64_t ptr, RustBuffer signal, int8_t process_group);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SDK_FN_METHOD_SPACESDPROCESS_TAGdiff --git a/libs/cua/typescript/src/native/cua_sdk-ffi.ts b/libs/cua/typescript/src/native/cua_sdk-ffi.tsindex 21bada6569..233acfb436 100644--- a/libs/cua/typescript/src/native/cua_sdk-ffi.ts+++ b/libs/cua/typescript/src/native/cua_sdk-ffi.ts@@ -2654,7 +2654,7 @@ const DEFINITIONS = {hasRustCallStatus: false,},"uniffi_cua_sdk_fn_method_spacesdprocess_signal": {- args: [FfiType.Handle, FfiType.RustBuffer],+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.Int8],ret: FfiType.Handle,hasRustCallStatus: false,},@@ -5433,7 +5433,7 @@ interface NativeModuleInterface {uniffi_cua_sdk_fn_method_spacesdprocess_next_event(uniffiSelf: bigint): bigint;uniffi_cua_sdk_fn_method_spacesdprocess_pid(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): number;uniffi_cua_sdk_fn_method_spacesdprocess_resize(uniffiSelf: bigint, cols: number, rows: number): bigint;- uniffi_cua_sdk_fn_method_spacesdprocess_signal(uniffiSelf: bigint, signal: Uint8Array): bigint;+ uniffi_cua_sdk_fn_method_spacesdprocess_signal(uniffiSelf: bigint, signal: Uint8Array, processGroup: number): bigint;uniffi_cua_sdk_fn_method_spacesdprocess_tag(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_sdk_fn_method_spacesdprocess_wait(uniffiSelf: bigint): bigint;uniffi_cua_sdk_fn_method_spacesdprocess_write_pty(uniffiSelf: bigint, data: Uint8Array): bigint;diff --git a/libs/cua/typescript/src/native/cua_sdk.ts b/libs/cua/typescript/src/native/cua_sdk.tsindex b7c5df1c34..d65e250155 100644--- a/libs/cua/typescript/src/native/cua_sdk.ts+++ b/libs/cua/typescript/src/native/cua_sdk.ts@@ -15812,7 +15812,14 @@ export type SpacesdCommand = {/*** Run in a PTY of this size.*/- pty?: PtySize+ pty?: PtySize,+ /**+ * Kill the process (`term`, then `kill`) when this client's connection+ * to cua-spacesd ends before the process does, including when the+ * client process dies. Off by default: processes are detached and can be+ * reattached by tag.+ */+ killOnDisconnect: boolean}/**@@ -15827,7 +15834,8 @@ export const SpacesdCommand = (() => {timeoutMs: undefined,tag: undefined,stdin: false,- pty: undefined+ pty: undefined,+ killOnDisconnect: false});const create = (() => {return uniffiCreateRecord<SpacesdCommand, ReturnType<typeof defaults>>(defaults);@@ -15852,7 +15860,8 @@ const FfiConverterTypeSpacesdCommand = (() => {timeoutMs: FfiConverterOptionalUInt32.read(from),tag: FfiConverterOptionalString.read(from),stdin: FfiConverterBool.read(from),- pty: FfiConverterOptionalTypePtySize.read(from)+ pty: FfiConverterOptionalTypePtySize.read(from),+ killOnDisconnect: FfiConverterBool.read(from)};}write(value: TypeName, into: RustBuffer): void {@@ -15865,6 +15874,7 @@ const FfiConverterTypeSpacesdCommand = (() => {FfiConverterOptionalString.write(value.tag, into);FfiConverterBool.write(value.stdin, into);FfiConverterOptionalTypePtySize.write(value.pty, into);+ FfiConverterBool.write(value.killOnDisconnect, into);}allocationSize(value: TypeName): number {return FfiConverterString.allocationSize(value.program) +@@ -15875,7 +15885,8 @@ const FfiConverterTypeSpacesdCommand = (() => {FfiConverterOptionalUInt32.allocationSize(value.timeoutMs) +FfiConverterOptionalString.allocationSize(value.tag) +FfiConverterBool.allocationSize(value.stdin) +- FfiConverterOptionalTypePtySize.allocationSize(value.pty);+ FfiConverterOptionalTypePtySize.allocationSize(value.pty) ++ FfiConverterBool.allocationSize(value.killOnDisconnect);}};@@ -22958,9 +22969,11 @@ export interface SpacesdProcessLike {*/resize(cols: number, rows: number, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;/**- * Sends a signal by name (`term`, `kill`, `SIGINT`, ...).+ * Sends a signal by name (`term`, `kill`, `SIGINT`, ...). With+ * `process_group`, to the process's whole group (everything it started),+ * as a terminal's Ctrl-C does; by default to the process alone.*/- signal(signal: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;+ signal(signal: string, processGroup: boolean, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<void>;/*** Tag, when set.*/@@ -23174,16 +23187,18 @@ private constructor(pointer: UniffiHandle) {}/**- * Sends a signal by name (`term`, `kill`, `SIGINT`, ...).+ * Sends a signal by name (`term`, `kill`, `SIGINT`, ...). With+ * `process_group`, to the process's whole group (everything it started),+ * as a terminal's Ctrl-C does; by default to the process alone.*/- async signal(signal: string, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {+ async signal(signal: string, processGroup: boolean = false, asyncOpts_?: { signal: AbortSignal }): Promise<void> /*throws*/ {const __stack = uniffiIsDebug ? new Error().stack : undefined;try {return await uniffiRustCallAsync(/*rustCaller:*/ uniffiCaller,/*rustFutureFunc:*/ () => {return nativeModule().uniffi_cua_sdk_fn_method_spacesdprocess_signal(- uniffiTypeSpacesdProcessObjectFactory.clonePointer(this),FfiConverterString.lower(signal, nativeModule().rustbuffer_alloc)+ uniffiTypeSpacesdProcessObjectFactory.clonePointer(this),FfiConverterString.lower(signal, nativeModule().rustbuffer_alloc),FfiConverterBool.lower(processGroup, nativeModule().rustbuffer_alloc));},/*pollFunc:*/ nativeModule().ffi_cua_sdk_rust_future_poll_void,@@ -36574,7 +36589,7 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_sdk_checksum_method_spacesdprocess_resize() !== 46607) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spacesdprocess_resize");}- if (nativeModule().uniffi_cua_sdk_checksum_method_spacesdprocess_signal() !== 61925) {+ if (nativeModule().uniffi_cua_sdk_checksum_method_spacesdprocess_signal() !== 44588) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_spacesdprocess_signal");}if (nativeModule().uniffi_cua_sdk_checksum_method_spacesdprocess_tag() !== 24315) {diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.jsonindex 18852f5ea9..69d82227f4 100644--- a/scripts/docs-generators/cli-specs/cua.json+++ b/scripts/docs-generators/cli-specs/cua.json@@ -3376,7 +3376,7 @@},{"abstract": "Run a command (joined into one shell line, as `sh -c`). Exits with the command's own status. A local Lume sandbox without cua-spacesd runs it via SSH (`lume ssh`)",- "after_help": "Examples:\n cua sb exec dev uname -a\n cua sb exec dev 'ls /tmp | wc -l'",+ "after_help": "Examples:\n cua sb exec dev uname -a\n cua sb exec dev 'ls /tmp | wc -l'\n # A long-lived stdio stream, like `docker exec -i`: argv, not a shell line\n cua sb exec -i dev -- bash -c 'wc -c'","aliases": [],"arguments": [{@@ -3401,6 +3401,17 @@}],"flags": [+ {+ "aliases": [],+ "default_value": false,+ "env": null,+ "help": "Stream: run the command as argv (no shell), forward this command's stdin, write stdout and stderr as they arrive, set no time limit, pass SIGINT/SIGTERM/SIGHUP on, and kill the command when this process ends. Exits with the command's status (128 + n for signal n)",+ "hidden": false,+ "name": "stdin",+ "repeatable": false,+ "short_name": "i",+ "takes_value": false+ },{"aliases": [],"default_value": false,@@ -3427,7 +3438,56 @@"hidden": false,"hidden_aliases": [],"name": "exec",- "options": [],+ "options": [+ {+ "aliases": [],+ "default_value": null,+ "env": null,+ "help": "Run as this guest user",+ "hidden": false,+ "is_optional": true,+ "multiple_values": false,+ "name": "user",+ "possible_values": [],+ "repeatable": false,+ "short_name": null,+ "takes_value": true,+ "type": "string",+ "value_name": "USER"+ },+ {+ "aliases": [],+ "default_value": null,+ "env": null,+ "help": "Start in this guest directory",+ "hidden": false,+ "is_optional": true,+ "multiple_values": false,+ "name": "cwd",+ "possible_values": [],+ "repeatable": false,+ "short_name": null,+ "takes_value": true,+ "type": "string",+ "value_name": "CWD"+ },+ {+ "aliases": [],+ "default_value": null,+ "env": null,+ "help": "Stop the command after this many seconds (0: no limit)",+ "hidden": false,+ "is_optional": true,+ "multiple_values": false,+ "name": "timeout",+ "possible_values": [],+ "repeatable": false,+ "short_name": null,+ "takes_value": true,+ "type": "integer",+ "value_name": "SECONDS"+ }+ ],"subcommand_optional": false,"subcommands": [],"usage": "cua sandbox exec [OPTIONS] <NAME> <COMMAND>..."@@ -7879,7 +7939,7 @@},{"abstract": "Run a command (argv, no shell)",- "after_help": "Examples:\n cua spacesd exec http://127.0.0.1:3211 uname -a",+ "after_help": "Examples:\n cua spacesd exec http://127.0.0.1:3211 uname -a\n # A long-lived stdio stream (stdin forwarded, no time limit, killed with this command)\n cua spacesd exec -i http://127.0.0.1:3211 cat","aliases": [],"arguments": [{@@ -7903,11 +7963,71 @@"type": "string"}],- "flags": [],+ "flags": [+ {+ "aliases": [],+ "default_value": false,+ "env": null,+ "help": "Stream: run the command as argv (no shell), forward this command's stdin, write stdout and stderr as they arrive, set no time limit, pass SIGINT/SIGTERM/SIGHUP on, and kill the command when this process ends. Exits with the command's status (128 + n for signal n)",+ "hidden": false,+ "name": "stdin",+ "repeatable": false,+ "short_name": "i",+ "takes_value": false+ }+ ],"hidden": false,"hidden_aliases": [],"name": "exec","options": [+ {+ "aliases": [],+ "default_value": null,+ "env": null,+ "help": "Run as this guest user",+ "hidden": false,+ "is_optional": true,+ "multiple_values": false,+ "name": "user",+ "possible_values": [],+ "repeatable": false,+ "short_name": null,+ "takes_value": true,+ "type": "string",+ "value_name": "USER"+ },+ {+ "aliases": [],+ "default_value": null,+ "env": null,+ "help": "Start in this guest directory",+ "hidden": false,+ "is_optional": true,+ "multiple_values": false,+ "name": "cwd",+ "possible_values": [],+ "repeatable": false,+ "short_name": null,+ "takes_value": true,+ "type": "string",+ "value_name": "CWD"+ },+ {+ "aliases": [],+ "default_value": null,+ "env": null,+ "help": "Stop the command after this many seconds (0: no limit)",+ "hidden": false,+ "is_optional": true,+ "multiple_values": false,+ "name": "timeout",+ "possible_values": [],+ "repeatable": false,+ "short_name": null,+ "takes_value": true,+ "type": "integer",+ "value_name": "SECONDS"+ },{"aliases": [],"default_value": null,diff --git a/tests/e2e/cua-sdk/python/e2e.py b/tests/e2e/cua-sdk/python/e2e.pyindex 2dacff7495..e8a20fdd2b 100644--- a/tests/e2e/cua-sdk/python/e2e.py+++ b/tests/e2e/cua-sdk/python/e2e.py@@ -323,6 +323,17 @@ async def env_smoke(env: "cua.SpacesdClient", *, desktop: bool, mock: bool = Falawait proc.close_stdin()assert (await proc.wait()).stdout == b"xyz"+ # kill_on_disconnect: letting go of the starting stream ends the process.+ tag = f"kod-py-{RUN}"+ proc = await env.spawn(+ cua.SpacesdCommand(+ program="cat", args=[], stdin=True, tag=tag, kill_on_disconnect=True+ )+ )+ await proc.detach()+ ended = await (await env.attach(None, tag, cua.ReplayMode.NONE())).wait()+ assert not ended.exit.success, ended.exit+blob = bytes(i % 251 for i in range(1 << 20))path = f"/tmp/cua-e2e-{RUN}/blob.bin"up = await env.upload(path, blob, None)diff --git a/tests/e2e/cua-sdk/rust/src/lib.rs b/tests/e2e/cua-sdk/rust/src/lib.rsindex 726472c5a7..4beb5c8b67 100644--- a/tests/e2e/cua-sdk/rust/src/lib.rs+++ b/tests/e2e/cua-sdk/rust/src/lib.rs@@ -15,7 +15,7 @@ use std::sync::{Arc, OnceLock};use std::time::{Duration, Instant};pub use cua_sdk::{self as cua, CuaError};-use cua_sdk::{Cua, CuaConfig, ReadinessProbe, SandboxCreateOptions, SpacesdClient, SpacesdCommand};+use cua_sdk::{Cua, CuaConfig, ReadinessProbe, ReplayMode, SandboxCreateOptions, SpacesdClient, SpacesdCommand};pub type Res<T = ()> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;@@ -288,6 +288,7 @@ pub fn cmd(program: &str, args: &[&str]) -> SpacesdCommand {tag: None,stdin: false,pty: None,+ kill_on_disconnect: false,}}@@ -565,6 +566,15 @@ pub async fn env_smoke(env: &SpacesdClient, desktop: bool, mock: bool) -> Res<sep.write_stdin(b"xyz".to_vec()).await?;p.close_stdin().await?;assert_eq!(p.wait().await?.stdout, b"xyz");+ // kill_on_disconnect: letting go of the starting stream ends the process.+ let mut c = cmd("cat", &[]);+ c.stdin = true;+ c.kill_on_disconnect = true;+ c.tag = Some(format!("kod-rs-{}", run_id()));+ let p = env.spawn(c.clone()).await?;+ p.detach().await;+ let ended = env.attach(None, c.tag.clone(), ReplayMode::None).await?.wait().await?;+ assert!(!ended.exit.success, "kill_on_disconnect left it running: {ended:?}");let blob: Vec<u8> = (0..(1usize << 20)).map(|i| (i % 251) as u8).collect();let path = format!("/tmp/cua-e2e-{}/blob-rs.bin", run_id());let up = env.upload(path.clone(), blob.clone(), None).await?;diff --git a/tests/e2e/cua-sdk/typescript/lib.mjs b/tests/e2e/cua-sdk/typescript/lib.mjsindex 442b68f4df..2a03232d72 100644--- a/tests/e2e/cua-sdk/typescript/lib.mjs+++ b/tests/e2e/cua-sdk/typescript/lib.mjs@@ -287,6 +287,12 @@ export async function envSmoke(env, { desktop, mock = false }) {await p.writeStdin(u8("xyz").buffer)await p.closeStdin()if (str((await p.wait()).stdout) !== "xyz") throw new Error("stdin roundtrip")+ // kill_on_disconnect: letting go of the starting stream ends the process.+ const kodTag = `kod-ts-${RUN}`+ const kod = await env.spawn(cmd("cat", [], { stdin: true, tag: kodTag, killOnDisconnect: true }))+ await kod.detach()+ const ended = await (await env.attach(undefined, kodTag, cua.ReplayMode.None.new())).wait()+ if (ended.exit.success) throw new Error("kill_on_disconnect left the process running")const blob = new Uint8Array(1 << 20).map((_, i) => i % 251)const path = `/tmp/cua-e2e-${RUN}/blob-ts.bin`const up = await env.upload(path, blob.buffer, undefined)