Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
feat: accept stdin for text commands (#373)
Lahfir97125f6ac74f
diff --git a/README.md b/README.mdindex 42ac024da..17bd6e781 100644--- a/README.md+++ b/README.md@@ -64,6 +64,7 @@ Each command prints one JSON envelope. A trimmed snapshot:- Refs carry their snapshot id. A bare `@e8` fails with `INVALID_ARGS`.- If the UI changed, an action returns `STALE_REF` or `AMBIGUOUS_TARGET`. Take a new snapshot and use its refs.- Actions are headless by default: no pointer movement, no focus change. Pass `--headed` for physical input.+- `type`, `set-value`, and `clipboard-set` accept `--stdin` for piped text, keeping it out of process arguments. Run secret steps as separate commands; batch JSON text appears in process arguments.- In PowerShell, quote every ref (`'@s8f3k2p9:e8'`), because a bare `@token` is the splatting operator.The full walkthrough is in the [quick start](https://agent-browser.dev/desktop/quick-start).diff --git a/apps/docs/content/docs/commands/clipboard.mdx b/apps/docs/content/docs/commands/clipboard.mdxindex eb8cd6497..b39a04054 100644--- a/apps/docs/content/docs/commands/clipboard.mdx+++ b/apps/docs/content/docs/commands/clipboard.mdx@@ -42,6 +42,7 @@ Writes text, a PNG image, or a list of file paths.```bashagent-desktop clipboard-set TEXT+printf '%s' 'Hello' | agent-desktop clipboard-set --stdinagent-desktop clipboard-set --image /tmp/a.pngagent-desktop clipboard-set --file-url /tmp/a.txt --file-url /tmp/b.txt```@@ -52,12 +53,17 @@ agent-desktop clipboard-set --file-url /tmp/a.txt --file-url /tmp/b.txt</thead><tbody><tr><td><code>TEXT</code></td><td>empty text</td><td>Text to write.</td></tr>+ <tr><td><code>--stdin</code></td><td>none</td><td>Read up to 128 KiB from a pipe or redirected file. Terminal input is rejected. Cannot be combined with <code>TEXT</code>, <code>--image</code>, or <code>--file-url</code>.</td></tr><tr><td><code>--image PATH</code></td><td>none</td><td>A regular PNG file of at most 64 MiB.</td></tr><tr><td><code>--file-url PATH</code></td><td>none</td><td>A file path to write as a file reference. Repeatable. Every path must exist.</td></tr></tbody></table>-One call writes one representation: `--file-url` wins over `--image`, which wins over `TEXT`. The result is an [OperationReport](/desktop/json-output#operationreport) plus the written `type`:+With `--stdin`, the command waits until the input ends. Empty input and all line breaks are kept, including a final newline. Use `printf '%s'` to avoid adding one. Input must be valid UTF-8 without NUL bytes (`\0`).++`--stdin` keeps text out of process arguments. Batch uses the JSON `text` field, which puts the text in process arguments. Run secret steps as separate `--stdin` commands. To copy the text `--stdin`, use `agent-desktop clipboard-set -- --stdin`.++Without `--stdin`, one call writes one representation: `--file-url` wins over `--image`, which wins over `TEXT`. The result is an [OperationReport](/desktop/json-output#operationreport) plus the written `type`:```json{diff --git a/apps/docs/content/docs/commands/interaction.mdx b/apps/docs/content/docs/commands/interaction.mdxindex c6402a4ac..0b2ee3d84 100644--- a/apps/docs/content/docs/commands/interaction.mdx+++ b/apps/docs/content/docs/commands/interaction.mdx@@ -156,6 +156,7 @@ Inserts text into a text target at its insertion point, then reads the field bac```bashagent-desktop type <REF> <TEXT> [--timeout-ms MS] [--interval-ms MS]+agent-desktop type <REF> --stdin [--timeout-ms MS] [--interval-ms MS]```<table>@@ -163,12 +164,24 @@ agent-desktop type <REF> <TEXT> [--timeout-ms MS] [--interval-ms MS]<tr><th>Flag or argument</th><th>Default</th><th>Meaning</th></tr></thead><tbody>- <tr><td><code>TEXT</code></td><td>required</td><td>The text, up to 10,000 bytes. A value that starts with a hyphen is accepted.</td></tr>+ <tr><td><code>TEXT</code></td><td>required unless <code>--stdin</code></td><td>The text, up to 10,000 bytes. A value that starts with a hyphen is accepted.</td></tr><tr><td><code>--timeout-ms MS</code></td><td><code>5000</code> plus <code>30</code> per character</td><td>Covers resolution, actionability, and delivery. An explicit value wins. With <code>--interval-ms</code>, it applies to each keystroke, and <code>0</code> makes each keystroke try once.</td></tr><tr><td><code>--interval-ms MS</code></td><td>off</td><td>Types one keystroke every <code>MS</code> milliseconds, 1 to 2000, instead of inserting the text at once.</td></tr></tbody></table>+Use `--stdin` with `type` or `set-value` to read text from a pipe or redirected file. Terminal input is rejected. Replace the example ref with one from your snapshot:++```bash+printf '%s' 'hello' | agent-desktop type @s8f3k2p9:e2 --stdin+```++The action timeout starts after the input ends; it doesn't limit this wait. Empty input and all line breaks are kept, including a final newline. Use `printf '%s'` to avoid adding one. Input must be valid UTF-8 without NUL bytes (`\0`). The limits are 10,000 bytes for `type` and 128 KiB for `set-value`.++Provide either `--stdin` or a command-line value. To enter the text `--stdin`, put it after `--`: `agent-desktop type @s8f3k2p9:e2 -- --stdin`. Batch uses the JSON `text` or `value` field, which puts the text in process arguments. Run secret steps as separate `--stdin` commands.++`--stdin` keeps text out of process arguments and omits observed `value` fields from JSON results, including `post_state.value`. Other app text and screenshot artifacts aren't redacted.+`type` inserts; it does not replace. After `set-value hello`, `type ' world'` into the same entry produced this, because the insertion point was at the start:```json@@ -197,8 +210,11 @@ Writes a value directly through the accessibility value path: text fields, text```bashagent-desktop set-value <REF> <VALUE> [--timeout-ms MS]+agent-desktop set-value <REF> --stdin [--timeout-ms MS]```+For piped text, use `--stdin` with the [input rules above](#type).+```json{"action": "set-value",diff --git a/crates/core/src/commands/find_live.rs b/crates/core/src/commands/find_live.rsindex aeb5d7abd..0cc9abea4 100644--- a/crates/core/src/commands/find_live.rs+++ b/crates/core/src/commands/find_live.rs@@ -48,7 +48,7 @@ pub(super) fn execute(args.surface,deadline,)?;- snapshot::first_surface_owner(windows, |window| {+ snapshot::window_capture::first_surface_owner(windows, |window| {resolve_query(adapter, query, ObservationRoot::Window(window), &request)})?.1diff --git a/crates/core/src/snapshot/mod.rs b/crates/core/src/snapshot/mod.rsindex 45859b9ce..dd5f744d9 100644--- a/crates/core/src/snapshot/mod.rs+++ b/crates/core/src/snapshot/mod.rs@@ -48,7 +48,7 @@ pub fn build(deadline: crate::Deadline,) -> Result<SnapshotResult, AppError> {let windows = surface_windows(adapter, app_name, window_id, opts.surface, deadline)?;- let (window, capture) = first_surface_owner(windows, |window| {+ let (window, capture) = window_capture::first_surface_owner(windows, |window| {window_capture::capture_window(adapter, opts, window, deadline)})?;let identity_unproven = capture.identity_unproven.clone();@@ -227,25 +227,6 @@ fn frontmost_process_windows(Ok(windows)}-pub(crate) fn first_surface_owner<T>(- windows: Vec<WindowInfo>,- mut observe: impl FnMut(&WindowInfo) -> Result<T, AppError>,-) -> Result<(WindowInfo, T), AppError> {- let mut windows = windows.into_iter().peekable();- while let Some(window) = windows.next() {- match observe(&window) {- Err(AppError::Adapter(error))- if error.code == crate::ErrorCode::ElementNotFound && windows.peek().is_some() => {}- result => return result.map(|observed| (window, observed)),- }- }- Err(- crate::AdapterError::new(crate::ErrorCode::WindowNotFound, "No window to observe")- .unsent()- .into(),- )-}-fn windows_for_app(adapter: &dyn PlatformAdapter,app_name: Option<&str>,diff --git a/crates/core/src/snapshot/window_capture.rs b/crates/core/src/snapshot/window_capture.rsindex d5687200c..a5a0fceca 100644--- a/crates/core/src/snapshot/window_capture.rs+++ b/crates/core/src/snapshot/window_capture.rs@@ -94,6 +94,25 @@ pub(crate) fn capture_window(})}+pub(crate) fn first_surface_owner<T>(+ windows: Vec<WindowInfo>,+ mut observe: impl FnMut(&WindowInfo) -> Result<T, AppError>,+) -> Result<(WindowInfo, T), AppError> {+ let mut windows = windows.into_iter().peekable();+ while let Some(window) = windows.next() {+ match observe(&window) {+ Err(AppError::Adapter(error))+ if error.code == crate::ErrorCode::ElementNotFound && windows.peek().is_some() => {}+ result => return result.map(|observed| (window, observed)),+ }+ }+ Err(+ crate::AdapterError::new(crate::ErrorCode::WindowNotFound, "No window to observe")+ .unsent()+ .into(),+ )+}+/// The whole-window read that proves tokenless refs, or why it cannot.fn whole_window(adapter: &dyn PlatformAdapter,diff --git a/skills/agent-desktop/references/commands-interaction.md b/skills/agent-desktop/references/commands-interaction.mdindex 49fb2a4a2..01e6b70c9 100644--- a/skills/agent-desktop/references/commands-interaction.md+++ b/skills/agent-desktop/references/commands-interaction.md@@ -97,6 +97,7 @@ agent-desktop right-click @s8f3k2p9:e5agent-desktop type @s8f3k2p9:e2 "[email protected]"agent-desktop type @s8f3k2p9:e2 "hello world" --interval-ms 60agent-desktop set-value @s8f3k2p9:e2 "new value"+printf '%s' 'hello' | agent-desktop set-value @s8f3k2p9:e2 --stdinagent-desktop clear @s8f3k2p9:e2agent-desktop focus @s8f3k2p9:e2```@@ -105,6 +106,11 @@ agent-desktop focus @s8f3k2p9:e2- The default `--timeout-ms` of `type` is 5000 plus 30 ms per character of the text. An explicit `--timeout-ms` wins.- `type --interval-ms N` (1 to 2000) types one keystroke every N ms inside one command; `--timeout-ms` then applies to each keystroke, and `0` makes each keystroke try once. A keystroke keeps combining marks, emoji sequences and CR LF together. The first keystroke is a full ref action (headed, it also focuses the window), and the rest go to the same element, taking the interaction lease one keystroke at a time. A headed keystroke is posted only while the target's process and focused element are unchanged; if focus moves, the burst stops with an error. The result adds `keystrokes` and `interval_ms`, and `post_state` is the field after the last keystroke. It stays `delivered_verified` only when that read shows the whole text; otherwise it is `delivered_unverified` with `verification_reason` `postcondition_mismatch`, `insufficient_evidence` (typed part way through the field) or `final_read_failed` (no `post_state`). `--wait-for` waits once, after the last keystroke. A failure part way through adds `details.typed_keystrokes` and `details.keystrokes` and is `delivered_unverified`: read the field before you type again.- `set-value` writes the value directly through the semantic value path. It is faster than `type`, but it may not fire every UI callback. Use it for text fields, text areas and sliders.+- Use `--stdin` with `type` or `set-value` to read text from a pipe or redirected file. Terminal input is rejected. Provide either `--stdin` or a command-line value.+- The action timeout starts after the input ends; it doesn't limit this wait. Empty input and all line breaks are kept, including a final newline. Use `printf '%s'` to avoid adding one. Input must be valid UTF-8 without NUL bytes (`\0`). The limits are 10,000 bytes for `type` and 128 KiB for `set-value`.+- Batch uses the JSON `text` or `value` field, which puts the text in process arguments. Run secret steps as separate `--stdin` commands.+- To enter the text `--stdin`, put it after `--`, as in `agent-desktop type @s8f3k2p9:e2 -- --stdin`.+- `--stdin` keeps text out of process arguments and omits observed `value` fields from JSON results, including `post_state.value`. Other app text and screenshot artifacts aren't redacted.- A cell that exposes no value write is not directly editable. Activate it, take a fresh snapshot, and target the editor that appears. Some apps expose no editor and accept only keyboard input.- `clear` empties the element. `focus` sets keyboard focus without clicking.diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.mdindex d654f8826..8df47af06 100644--- a/skills/agent-desktop/references/commands-system.md+++ b/skills/agent-desktop/references/commands-system.md@@ -101,6 +101,7 @@ Commands: `list-notifications`, `dismiss-notification`, `dismiss-all-notificatioagent-desktop clipboard-get --format autoagent-desktop clipboard-get --format image --out /tmp/clip.pngagent-desktop clipboard-set "Hello"+printf '%s' 'Hello' | agent-desktop clipboard-set --stdinagent-desktop clipboard-set --image /tmp/a.pngagent-desktop clipboard-set --file-url /tmp/a.txt --file-url /tmp/b.txtagent-desktop clipboard-clear@@ -109,6 +110,9 @@ agent-desktop clipboard-clear- Formats: `text` (default), `auto` (file references, then image, then text), `image`, `file-urls`. Output is `{ "type": "text", "text": ... }`, `{ "type": "file_urls", ... }`, or `{ "type": "image", "path", "width", "height" }`. When the clipboard has nothing in that form: `{ "type": "<format>", "found": false }`.- Image bytes go to `--out`, or to a private file under the active session directory (or `~/.agent-desktop/tmp`).- `clipboard-set` writes one representation per call. `--file-url` and `--image` win over the positional text. Every `--file-url` path must exist, or `INVALID_ARGS`.+- Use `clipboard-set --stdin` to read up to 128 KiB from a pipe or redirected file without putting it in process arguments. Terminal input is rejected. It cannot be combined with a command-line value, `--image`, or `--file-url`.+- The command waits until the input ends. Empty input and all line breaks are kept, including a final newline. Use `printf '%s'` to avoid adding one. Input must be valid UTF-8 without NUL bytes (`\0`).+- Batch uses the JSON `text` field, which puts the text in process arguments. Run secret steps as separate `--stdin` commands. To copy the text `--stdin`, use `agent-desktop clipboard-set -- --stdin`.- A write that loses clipboard ownership mid-way reports `delivered_unverified`, not a false success.## waitdiff --git a/src/Cargo.toml b/src/Cargo.tomlindex 94533fb05..bd8f34aee 100644--- a/src/Cargo.toml+++ b/src/Cargo.toml@@ -50,6 +50,10 @@ path = "tests/conformance.rs"name = "cli_process"path = "tests/cli_process.rs"+[[test]]+name = "cli_stdin"+path = "tests/cli_stdin.rs"+[[test]]name = "mcp_process"path = "tests/mcp_process.rs"diff --git a/src/batch/mod.rs b/src/batch/mod.rsindex cece17d32..2baf98430 100644--- a/src/batch/mod.rs+++ b/src/batch/mod.rs@@ -50,8 +50,8 @@ pub(crate) fn parse_command(item: BatchCommand) -> Result<Commands, AppError> {"double-click" => decode(command, item.args).map(Commands::DoubleClick),"triple-click" => decode(command, item.args).map(Commands::TripleClick),"right-click" => decode(command, item.args).map(Commands::RightClick),- "type" => decode(command, item.args).map(Commands::Type),- "set-value" => decode(command, item.args).map(Commands::SetValue),+ "type" => decode_batch_args(command, item.args, Some("text")).map(Commands::Type),+ "set-value" => decode_batch_args(command, item.args, Some("value")).map(Commands::SetValue),"clear" => decode(command, item.args).map(Commands::Clear),"focus" => decode(command, item.args).map(Commands::Focus),"select" => decode(command, item.args).map(Commands::Select),@@ -92,7 +92,7 @@ pub(crate) fn parse_command(item: BatchCommand) -> Result<Commands, AppError> {}"notification-action" => decode(command, item.args).map(Commands::NotificationAction),"clipboard-get" => decode(command, item.args).map(Commands::ClipboardGet),- "clipboard-set" => decode(command, item.args).map(Commands::ClipboardSet),+ "clipboard-set" => decode_batch_args(command, item.args, None).map(Commands::ClipboardSet),"clipboard-clear" => no_args(command, item.args).map(|()| Commands::ClipboardClear),"wait" => decode(command, item.args).map(Commands::Wait),"status" => no_args(command, item.args).map(|()| Commands::Status),@@ -129,6 +129,32 @@ where})}+fn decode_batch_args<T>(+ command: &str,+ args: Value,+ required_text: Option<&str>,+) -> Result<T, AppError>+where+ T: DeserializeOwned,+{+ if args.get("stdin").is_some() {+ return Err(AppError::invalid_input(+ "Batch text must be provided in JSON; --stdin is CLI-only",+ ));+ }+ if let Some(field) = required_text+ && !matches!(+ args.get(field).or_else(|| args.get(1)),+ Some(Value::String(_))+ )+ {+ return Err(AppError::invalid_input(format!(+ "Batch command '{command}' requires a string field '{field}'"+ )));+ }+ decode(command, args)+}+fn no_args(command: &str, args: Value) -> Result<(), AppError> {match args_or_empty(args) {Value::Object(map) if map.is_empty() => Ok(()),diff --git a/src/batch/tests.rs b/src/batch/tests.rsindex f766ad6a2..9344860d4 100644--- a/src/batch/tests.rs+++ b/src/batch/tests.rs@@ -319,6 +319,47 @@ fn session_batch_end_parses_id() {}}+#[test]+fn text_batch_requires_json_values_and_rejects_cli_stdin() {+ let reference = "@s8f3k2p9:e1";+ for (command, field) in [("type", "text"), ("set-value", "value")] {+ for text in ["", "legacy"] {+ for args in [+ serde_json::json!({ "ref_id": reference, (field): text }),+ serde_json::json!([reference, text]),+ ] {+ let value = match parse_command(item(command, args)).unwrap() {+ Commands::Type(args) => args.text,+ Commands::SetValue(args) => args.value,+ _ => panic!("unexpected text command"),+ };+ assert_eq!(value.as_deref(), Some(text));+ }+ }+ for args in [+ serde_json::json!({ "ref_id": reference }),+ serde_json::json!({ "ref_id": reference, (field): null }),+ serde_json::json!([reference]),+ serde_json::json!([reference, null]),+ serde_json::json!([reference, 42]),+ ] {+ assert!(parse_command(item(command, args)).is_err());+ }+ }+ for (command, field) in [+ ("type", "text"),+ ("set-value", "value"),+ ("clipboard-set", "text"),+ ] {+ let mut args = serde_json::json!({ (field): "text", "stdin": true });+ if command != "clipboard-set" {+ args["ref_id"] = serde_json::json!(reference);+ }+ let error = parse_command(item(command, args)).unwrap_err();+ assert!(error.to_string().contains("CLI-only"));+ }+}+#[test]fn every_cli_subcommand_is_known_to_batch_parser() {for subcommand in crate::cli::Cli::command().get_subcommands() {diff --git a/src/cli_args/actions.rs b/src/cli_args/actions.rsindex 0aeb00f61..a78c69da9 100644--- a/src/cli_args/actions.rs+++ b/src/cli_args/actions.rs@@ -29,14 +29,26 @@ pub(crate) struct TypeArgs {help = "Qualified ref from snapshot (@<snapshot_id>:eN)")]pub ref_id: String,- #[arg(value_name = "TEXT", allow_hyphen_values = true, help = "Text to type")]- pub text: String,+ #[arg(+ value_name = "TEXT",+ allow_hyphen_values = true,+ help = "Text to type",+ required_unless_present = "stdin",+ conflicts_with = "stdin"+ )]+ pub text: Option<String>,#[arg(long = "timeout-ms",help = "Maximum wait in milliseconds, covering ref resolution, actionability and delivery of the text; default 5000 plus 30 per character of TEXT; 0 disables the wait")]#[serde(default)]pub timeout_ms: Option<u64>,+ #[arg(+ long,+ help = "Read up to 10,000 bytes of UTF-8 text from a pipe or file"+ )]+ #[serde(skip)]+ pub stdin: bool,#[arg(long = "interval-ms",value_parser = clap::value_parser!(u64).range(1..=2000),@@ -50,13 +62,15 @@ impl TypeArgs {pub(crate) fn effective_timeout_ms(&self) -> u64 {if let Some(interval_ms) = self.interval_ms {return agent_desktop_core::commands::type_text::interval_budget_ms(- &self.text,+ self.text.as_deref().unwrap_or_default(),interval_ms,self.timeout_ms,);}self.timeout_ms.unwrap_or_else(|| {- agent_desktop_core::commands::type_text::default_timeout_ms(&self.text)+ agent_desktop_core::commands::type_text::default_timeout_ms(+ self.text.as_deref().unwrap_or_default(),+ )})}}@@ -72,9 +86,11 @@ pub(crate) struct SetValueArgs {#[arg(value_name = "VALUE",allow_hyphen_values = true,- help = "Value to set"+ help = "Value to set",+ required_unless_present = "stdin",+ conflicts_with = "stdin")]- pub value: String,+ pub value: Option<String>,#[arg(long = "timeout-ms",default_value_t = 5000,@@ -82,6 +98,9 @@ pub(crate) struct SetValueArgs {)]#[serde(default = "default_ref_timeout_ms")]pub timeout_ms: u64,+ #[arg(long, help = "Read up to 128 KiB of UTF-8 text from a pipe or file")]+ #[serde(skip)]+ pub stdin: bool,}#[derive(Parser, Debug, Deserialize)]diff --git a/src/cli_args/mod.rs b/src/cli_args/mod.rsindex 7df0b7292..4040af241 100644--- a/src/cli_args/mod.rs+++ b/src/cli_args/mod.rs@@ -18,6 +18,7 @@ pub(crate) mod session;pub(crate) mod skills;mod snapshot;pub(crate) mod snapshot_tree;+pub(crate) mod stdin;pub(crate) mod system;pub(crate) mod trace;diff --git a/src/cli_args/stdin.rs b/src/cli_args/stdin.rsnew file mode 100644index 000000000..673833601--- /dev/null+++ b/src/cli_args/stdin.rs@@ -0,0 +1,86 @@+use crate::Commands;+use agent_desktop_core::AppError;+use std::io::{IsTerminal, Read};++const MAX_STDIN_BYTES: usize = 128 * 1024;++pub(crate) fn resolve_stdin_text(+ command: &mut Commands,+ reader: impl Read + IsTerminal,+) -> Result<(), AppError> {+ if let Some(value) = input(command) {+ if reader.is_terminal() {+ return Err(AppError::invalid_input(+ "--stdin requires a pipe or redirected file",+ ));+ }+ *value = Some(read_text(reader)?);+ }+ Ok(())+}++pub(crate) fn input(command: &mut Commands) -> Option<&mut Option<String>> {+ match command {+ Commands::Type(args) if args.stdin => Some(&mut args.text),+ Commands::SetValue(args) if args.stdin => Some(&mut args.value),+ Commands::ClipboardSet(args) if args.stdin => Some(&mut args.text),+ _ => None,+ }+}++pub(crate) fn redact_result(+ mut result: Result<serde_json::Value, AppError>,+ stdin: bool,+) -> Result<serde_json::Value, AppError> {+ if stdin {+ let data = match &mut result {+ Ok(data) => Some(data),+ Err(AppError::Adapter(error)) => error.details.as_mut(),+ _ => None,+ };+ if let Some(data) = data {+ omit_values(data);+ }+ }+ result+}++fn omit_values(data: &mut serde_json::Value) {+ match data {+ serde_json::Value::Object(fields) => {+ fields.remove("value");+ fields.values_mut().for_each(omit_values);+ }+ serde_json::Value::Array(items) => items.iter_mut().for_each(omit_values),+ _ => {}+ }+}++pub(crate) fn read_text(reader: impl Read) -> Result<String, AppError> {+ let mut bytes = Vec::new();+ reader+ .take((MAX_STDIN_BYTES + 1) as u64)+ .read_to_end(&mut bytes)+ .map_err(|_| AppError::invalid_input("Could not read text from stdin"))?;+ validate_bytes(&bytes)?;+ String::from_utf8(bytes)+ .map_err(|_| AppError::invalid_input("stdin must contain valid UTF-8 text"))+}++pub(crate) fn validate_bytes(bytes: &[u8]) -> Result<(), AppError> {+ if bytes.len() > MAX_STDIN_BYTES {+ return Err(AppError::invalid_input(+ "stdin text exceeds the 128 KiB limit",+ ));+ }+ if bytes.contains(&0) {+ return Err(AppError::invalid_input(+ "stdin text cannot contain NUL bytes",+ ));+ }+ Ok(())+}++#[cfg(test)]+#[path = "stdin_tests.rs"]+mod tests;diff --git a/src/cli_args/stdin_tests.rs b/src/cli_args/stdin_tests.rsnew file mode 100644index 000000000..44e795850--- /dev/null+++ b/src/cli_args/stdin_tests.rs@@ -0,0 +1,65 @@+use super::read_text;+use std::io::Cursor;++#[test]+fn stdin_text_preserves_empty_input_unicode_crlf_and_trailing_newlines() {+ assert_eq!(read_text(Cursor::new(b"")).unwrap(), "");+ let text = "first\r\nsecond\n世界";+ assert_eq!(read_text(Cursor::new(text.as_bytes())).unwrap(), text);+}++#[test]+fn stdin_text_accepts_the_limit_and_rejects_one_extra_byte() {+ let input = vec![b'x'; 128 * 1024];+ assert_eq!(read_text(Cursor::new(input)).unwrap().len(), 128 * 1024);+ let error = read_text(Cursor::new(vec![b'x'; 128 * 1024 + 1])).unwrap_err();+ assert!(error.to_string().contains("128 KiB"));+}++#[test]+fn stdin_text_rejects_invalid_utf8_and_nul_without_echoing_input() {+ for input in [b"private-marker\xff".as_slice(), b"private-marker\0"] {+ let error = read_text(Cursor::new(input)).unwrap_err();+ assert_eq!(error.code(), "INVALID_ARGS");+ assert!(!error.to_string().contains("private-marker"));+ }+}++#[test]+fn stdin_read_failures_are_generic() {+ struct Failure;++ impl std::io::Read for Failure {+ fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {+ Err(std::io::Error::other("private marker"))+ }+ }++ let error = read_text(Failure).unwrap_err();+ assert_eq!(error.code(), "INVALID_ARGS");+ assert!(!error.to_string().contains("private marker"));+}++#[test]+fn stdin_flags_conflict_with_other_input_sources() {+ use clap::Parser;+ for args in [+ vec!["ad", "type", "@s8f3k2p9:e1"],+ vec!["ad", "set-value", "@s8f3k2p9:e1"],+ vec!["ad", "clipboard-set"],+ ] {+ let parse = |extra: &[&str]| crate::Cli::try_parse_from(args.iter().chain(extra).copied());+ let mut command = parse(&["--stdin"]).unwrap().command.unwrap();+ assert!(super::input(&mut command).is_some());+ assert!(parse(&["text", "--stdin"]).is_err());+ let mut literal = parse(&["--", "--stdin"]).unwrap().command.unwrap();+ assert!(super::input(&mut literal).is_none());+ if args[1] == "clipboard-set" {+ for flag in ["--image", "--file-url"] {+ assert!(parse(&["--stdin", flag, "file"]).is_err());+ }+ } else {+ assert!(parse(&[]).is_err());+ }+ }+}diff --git a/src/cli_args/system.rs b/src/cli_args/system.rsindex 996743d18..de906ac53 100644--- a/src/cli_args/system.rs+++ b/src/cli_args/system.rs@@ -189,6 +189,13 @@ pub(crate) struct ClipboardSetArgs {)]#[serde(default)]pub file_url: Vec<String>,+ #[arg(+ long,+ conflicts_with_all = ["text", "image", "file_url"],+ help = "Read up to 128 KiB of UTF-8 text from a pipe or file"+ )]+ #[serde(skip)]+ pub stdin: bool,}/// `event`/`window_id` flatten in as a sibling of `mode`/`predicate` herediff --git a/src/dispatch/cursor_overlay_lifecycle_tests.rs b/src/dispatch/cursor_overlay_lifecycle_tests.rsindex 323d87f83..1e47418a3 100644--- a/src/dispatch/cursor_overlay_lifecycle_tests.rs+++ b/src/dispatch/cursor_overlay_lifecycle_tests.rs@@ -186,6 +186,7 @@ fn mutating_keyboard_and_clipboard_commands_re_show_cursor_overlay() {dispatch(Commands::ClipboardSet(ClipboardSetArgs {text: Some("agent".into()),+ stdin: false,image: None,file_url: vec![],}),diff --git a/src/dispatch/disposition_tests.rs b/src/dispatch/disposition_tests.rsindex e980de5c3..11b48e821 100644--- a/src/dispatch/disposition_tests.rs+++ b/src/dispatch/disposition_tests.rs@@ -29,6 +29,14 @@ impl ObservationOps for FailingAdapter {impl ActionOps for FailingAdapter {}impl InputOps for FailingAdapter {+ fn set_clipboard_content(+ &self,+ _content: &agent_desktop_core::ClipboardContent,+ _lease: &InteractionLease,+ ) -> Result<OperationReport, AdapterError> {+ Err(self.0.clone())+ }+fn clear_clipboard(&self, _lease: &InteractionLease) -> Result<OperationReport, AdapterError> {Err(self.0.clone())}@@ -178,3 +186,26 @@ fn batch_entries_settle_their_failures_by_their_own_command() {assert_eq!(delivery(0), "not_delivered");assert_eq!(delivery(1), "unknown");}++#[test]+fn stdin_dispatch_omits_values_and_preserves_delivery() {+ let data = json!({"post_state": {"value": "private", "enabled": true},+ "after_action": {"steps": [{"label": "SetValue", "value": "private"}]}});+ let redacted = json!({"post_state": {"enabled": true},+ "after_action": {"steps": [{"label": "SetValue"}]}});+ for (argument, expected) in [("--stdin", redacted.clone()), ("private", data.clone())] {+ let error = failure_of(+ AdapterError::new(ErrorCode::ActionFailed, "verification failed")+ .with_details(data.clone())+ .with_disposition(DeliverySemantics::uncertain()),+ &["clipboard-set", argument],+ );+ assert_eq!(error.code, ErrorCode::ActionFailed);+ assert_eq!(error.details, Some(expected));+ assert_eq!(error.disposition, DeliverySemantics::uncertain());+ }+ assert_eq!(+ crate::cli_args::stdin::redact_result(Ok(data), true).unwrap(),+ redacted+ );+}diff --git a/src/dispatch/interaction.rs b/src/dispatch/interaction.rsindex 8dad6a3e6..63775f121 100644--- a/src/dispatch/interaction.rs+++ b/src/dispatch/interaction.rs@@ -60,10 +60,13 @@ pub(super) fn type_text(Some(_) => args.timeout_ms,None => helpers::normalize_action_timeout_ms(args.effective_timeout_ms()),};+ let text = args+ .text+ .ok_or_else(|| AppError::invalid_input("type text is missing"))?;type_text_command::execute(type_text_command::TypeArgs {ref_id: args.ref_id,- text: args.text,+ text,timeout_ms,interval_ms: args.interval_ms,},@@ -77,10 +80,13 @@ pub(super) fn set_value(adapter: &dyn PlatformAdapter,context: &CommandContext,) -> Result<Value, AppError> {+ let value = args+ .value+ .ok_or_else(|| AppError::invalid_input("set-value input is missing"))?;set_value_command::execute(set_value_command::SetValueArgs {ref_id: args.ref_id,- value: args.value,+ value,timeout_ms: helpers::normalize_action_timeout_ms(args.timeout_ms),},adapter,diff --git a/src/dispatch/mod.rs b/src/dispatch/mod.rsindex 373674f0a..a81a55443 100644--- a/src/dispatch/mod.rs+++ b/src/dispatch/mod.rs@@ -30,14 +30,16 @@ use serde_json::Value;use crate::cli::Commands;pub(crate) fn dispatch(- cmd: Commands,+ mut cmd: Commands,adapter: &dyn PlatformAdapter,permission_report: &PermissionReport,context: &CommandContext,) -> Result<Value, AppError> {let read_only = !cmd.is_mutating();- dispatch_command(cmd, adapter, permission_report, context)- .map_err(|error| disposition::settle_unknown_delivery(error, read_only))+ let stdin = crate::cli_args::stdin::input(&mut cmd).is_some();+ let result = dispatch_command(cmd, adapter, permission_report, context)+ .map_err(|error| disposition::settle_unknown_delivery(error, read_only));+ crate::cli_args::stdin::redact_result(result, stdin)}fn dispatch_command(diff --git a/src/main.rs b/src/main.rsindex 3e61f7f89..112b30462 100644--- a/src/main.rs+++ b/src/main.rs@@ -94,7 +94,7 @@ fn run() -> ExitCode {init_tracing(cli.visual_debug.verbose);- let cmd = match cli.command.take() {+ let mut cmd = match cli.command.take() {Some(c) => c,None => {return match root_command().print_help() {@@ -105,7 +105,14 @@ fn run() -> ExitCode {};let cmd_name = cmd.name();- finish(cmd_name, execute(cli, cmd))+ let stdin = cli_args::stdin::input(&mut cmd).is_some();+ if let Err(error) = cli_args::stdin::resolve_stdin_text(&mut cmd, std::io::stdin().lock()) {+ return finish(cmd_name, Err(error));+ }+ finish(+ cmd_name,+ cli_args::stdin::redact_result(execute(cli, cmd), stdin),+ )}/// The parsed command tree: every `Commands` variant plus `mcp`, which serves them.diff --git a/src/mcp/catalog.rs b/src/mcp/catalog.rsindex b4a2a69e6..718b1550e 100644--- a/src/mcp/catalog.rs+++ b/src/mcp/catalog.rs@@ -100,6 +100,7 @@ impl Tool {self.command.get_arguments().filter(|arg| {!arg.is_global_set()&& !arg.is_hide_set()+ && arg.get_id().as_str() != "stdin"&& !matches!(arg.get_action(),ArgAction::Helpdiff --git a/src/mcp/catalog_tests.rs b/src/mcp/catalog_tests.rsindex 5214a4861..ea00e0b0a 100644--- a/src/mcp/catalog_tests.rs+++ b/src/mcp/catalog_tests.rs@@ -147,7 +147,7 @@ fn flag_shaped_values_stay_values_and_never_become_flags() {let Some(crate::cli::Commands::Type(typed)) = cli.command else {panic!("type");};- assert_eq!(typed.text, hostile);+ assert_eq!(typed.text.as_deref(), Some(hostile));}#[test]@@ -168,3 +168,21 @@ fn global_flags_cannot_be_set_per_call() {assert!(error.contains("Unknown argument"), "{global}: {error}");}}++#[test]+fn stdin_input_is_not_exposed_to_mcp_calls() {+ for path in [["type"], ["set-value"], ["clipboard-set"]] {+ let tool = tool_at(&path);+ assert!(+ tool.definition()["inputSchema"]["properties"]+ .get("stdin")+ .is_none()+ );+ let arguments = Map::from_iter([("stdin".into(), Value::Bool(true))]);+ assert!(+ tool.argv(&arguments)+ .unwrap_err()+ .contains("Unknown argument 'stdin'")+ );+ }+}diff --git a/src/tests/cli_stdin.rs b/src/tests/cli_stdin.rsnew file mode 100644index 000000000..929d9e371--- /dev/null+++ b/src/tests/cli_stdin.rs@@ -0,0 +1,44 @@+use std::io::Write;+use std::process::{Command, Output, Stdio};++fn run_cli(args: &[&str], input: &[u8]) -> Output {+ let mut child = Command::new(env!("CARGO_BIN_EXE_agent-desktop"))+ .args(args)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .expect("CLI starts");+ child+ .stdin+ .take()+ .expect("stdin is piped")+ .write_all(input)+ .expect("stdin accepts input");+ child.wait_with_output().expect("CLI exits")+}++#[test]+fn each_stdin_command_rejects_invalid_utf8_before_dispatch() {+ let input = b"private-marker\xff";+ for args in [+ vec!["type", "@s8f3k2p9:e1", "--stdin"],+ vec!["set-value", "@s8f3k2p9:e1", "--stdin"],+ vec!["clipboard-set", "--stdin"],+ ] {+ let output = run_cli(&args, input);+ let response: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ assert!(!output.status.success());+ assert_eq!(response["command"], args[0]);+ assert_eq!(response["ok"], false);+ assert_eq!(response["error"]["code"], "INVALID_ARGS");+ assert!(+ response["error"]["message"]+ .as_str()+ .unwrap()+ .contains("valid UTF-8")+ );+ assert!(!String::from_utf8_lossy(&output.stdout).contains("private-marker"));+ assert!(!String::from_utf8_lossy(&output.stderr).contains("private-marker"));+ }+}