| /* | |
| * Licensed to the Apache Software Foundation (ASF) under one | |
| * or more contributor license agreements. See the NOTICE file | |
| * distributed with this work for additional information | |
| * regarding copyright ownership. The ASF licenses this file | |
| * to you under the Apache License, Version 2.0 (the | |
| * "License"); you may not use this file except in compliance | |
| * with the License. You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, | |
| * software distributed under the License is distributed on an | |
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
| * KIND, either express or implied. See the License for the | |
| * specific language governing permissions and limitations | |
| * under the License. | |
| */ | |
| //! Native screen-reader input. Terminal observations acknowledge input, never model completion. | |
| use super::*; | |
| use std::time::Duration; | |
| use tokio::{ | |
| io::{AsyncWrite, AsyncWriteExt}, | |
| sync::watch, | |
| }; | |
| #[derive(Clone, Default)] | |
| pub(super) struct Screen { | |
| end: u64, | |
| bytes: Vec<u8>, | |
| } | |
| impl Screen { | |
| fn push_byte(&mut self, byte: u8) { | |
| self.bytes.push(byte); | |
| self.end += 1; | |
| } | |
| fn end_line(&mut self) { | |
| if !self.bytes.is_empty() && !self.bytes.ends_with(b"\n") { | |
| self.push_byte(b'\n'); | |
| } | |
| } | |
| fn after(&self, mark: u64) -> String { | |
| let start = self.end - self.bytes.len() as u64; | |
| let at = mark.saturating_sub(start).min(self.bytes.len() as u64) as usize; | |
| String::from_utf8_lossy(&self.bytes[at..]).into_owned() | |
| } | |
| } | |
| #[derive(Default)] | |
| enum Escape { | |
| #[default] | |
| Text, | |
| Start, | |
| Csi(Option<u16>), | |
| Osc, | |
| OscEnd, | |
| } | |
| #[derive(Default)] | |
| pub(super) struct Decoder { | |
| escape: Escape, | |
| /// Rows between the cursor and the row the observation ends on. Claude moves | |
| /// up either to erase and redraw its last rows, or to add to a row it drew | |
| /// earlier and come back; the observation is linear and keeps only the redraw. | |
| above: u16, | |
| } | |
| impl Decoder { | |
| pub fn push(&mut self, screen: &mut Screen, bytes: &[u8]) { | |
| for &byte in bytes { | |
| match self.escape { | |
| Escape::Text => match byte { | |
| 27 => self.escape = Escape::Start, | |
| b'\r' => {} | |
| b'\n' if self.above > 0 => self.above -= 1, | |
| b'\n' | b'\t' | 32..=255 if self.above == 0 => screen.push_byte(byte), | |
| _ => {} | |
| }, | |
| Escape::Start => { | |
| self.escape = match byte { | |
| b'[' => Escape::Csi(None), | |
| b']' => Escape::Osc, | |
| _ => Escape::Text, | |
| } | |
| } | |
| Escape::Csi(count) => { | |
| if byte.is_ascii_digit() { | |
| let digit = u16::from(byte - b'0'); | |
| self.escape = Escape::Csi(Some( | |
| count.unwrap_or(0).saturating_mul(10).saturating_add(digit), | |
| )); | |
| } else if (0x40..=0x7e).contains(&byte) { | |
| match (byte, count) { | |
| (b'A', _) => { | |
| self.above = self.above.saturating_add(count.unwrap_or(1).max(1)); | |
| } | |
| (b'B', _) => { | |
| self.above = self.above.saturating_sub(count.unwrap_or(1).max(1)); | |
| } | |
| // Full-line (2K) and forward/full-screen (J/0J/2J/3J) erases start a | |
| // redraw; partial in-place erases (K/0K/1K/1J) leave rows below intact. | |
| (b'K', Some(2)) | (b'J', None | Some(0 | 2 | 3)) => { | |
| self.above = 0; | |
| screen.end_line(); | |
| } | |
| _ => {} | |
| } | |
| self.escape = Escape::Text; | |
| } else { | |
| self.escape = Escape::Csi(None); | |
| } | |
| } | |
| Escape::Osc => match byte { | |
| 7 => self.escape = Escape::Text, | |
| 27 => self.escape = Escape::OscEnd, | |
| _ => {} | |
| }, | |
| Escape::OscEnd => { | |
| self.escape = if byte == b'\\' { | |
| Escape::Text | |
| } else { | |
| Escape::Osc | |
| } | |
| } | |
| } | |
| } | |
| // Only a rolling terminal observation, not a prompt, attachment, or transcript limit. | |
| // One MiB is hundreds of screens at this PTY's 120×40 viewport. | |
| if screen.bytes.len() > 1024 * 1024 { | |
| screen.bytes.drain(..screen.bytes.len() - 1024 * 1024); | |
| } | |
| } | |
| } | |
| pub(super) fn text(prompt: &str) -> String { | |
| let mut out = String::with_capacity(prompt.len()); | |
| let mut chars = prompt.chars().peekable(); | |
| while let Some(c) = chars.next() { | |
| match c { | |
| '\r' => { | |
| if chars.peek() == Some(&'\n') { | |
| chars.next(); | |
| } | |
| out.push('\n'); | |
| } | |
| '\n' | '\t' => out.push(c), | |
| c if c.is_control() => { | |
| use std::fmt::Write; | |
| write!(out, "\\u{{{:x}}}", c as u32).expect("write to String"); | |
| } | |
| c => out.push(c), | |
| } | |
| } | |
| out | |
| } | |
| pub(super) async fn write(io: &mut (impl AsyncWrite + Unpin), bytes: &[u8]) -> Result<(), Error> { | |
| io.write_all(bytes) | |
| .await | |
| .map_err(|error| Error::Provider(format!("Claude PTY input failed: {error}")))?; | |
| io.flush() | |
| .await | |
| .map_err(|error| Error::Provider(format!("Claude PTY input flush failed: {error}"))) | |
| } | |
| async fn paste(io: &mut (impl AsyncWrite + Unpin), text: &str) -> Result<(), Error> { | |
| write(io, b"\x1b[200~").await?; | |
| write(io, text.as_bytes()).await?; | |
| write(io, b"\x1b[201~").await | |
| } | |
| async fn changed(screen: &mut watch::Receiver<Screen>) -> Result<(), Error> { | |
| screen | |
| .changed() | |
| .await | |
| .map_err(|_| Error::Provider("Claude closed before interactive input was accepted".into())) | |
| } | |
| enum Startup<'a> { | |
| Wait, | |
| Ready, | |
| Answer(&'a [u8]), | |
| } | |
| fn startup<'a>(text: &str, cwd: &str) -> Result<Startup<'a>, Error> { | |
| let lower = text.to_lowercase(); | |
| if lower.contains("select login method") || lower.contains("log in with your claude account") { | |
| return Err(Error::Invalid("Claude native login is required".into())); | |
| } | |
| if lower.contains("yes, i trust this folder") && lower.contains("enter y/n:") { | |
| let path = text | |
| .split("Permission Required: Accessing workspace:") | |
| .nth(1) | |
| .and_then(|s| s.lines().find(|line| !line.trim().is_empty())) | |
| .map(str::trim); | |
| if path != Some(cwd) { | |
| return Err(Error::Invalid( | |
| "Claude requested trust outside this invocation's workspace".into(), | |
| )); | |
| } | |
| return Ok(Startup::Answer(b"y\r")); | |
| } | |
| if lower.contains("choose the text style") && lower.contains("enter") { | |
| return Ok(Startup::Answer(b"\r")); | |
| } | |
| if lower.contains("security notes:") && lower.contains("press enter") { | |
| return Ok(Startup::Answer(b"\r")); | |
| } | |
| if lower.contains("terminal setup?") && lower.contains("esc to skip") { | |
| return Ok(Startup::Answer(b"\x1b")); | |
| } | |
| if lower.contains("bypass permissions mode") && lower.contains("yes, i accept") { | |
| // Native highest-permission mode was explicitly selected in the captured runtime configuration. | |
| if lower.contains("y. yes, i accept") && lower.contains("enter y/n:") { | |
| return Ok(Startup::Answer(b"y\r")); | |
| } | |
| if lower.contains("2. yes, i accept") && lower.contains("enter") { | |
| return Ok(Startup::Answer(b"2\r")); | |
| } | |
| } | |
| if text.lines().last().is_some_and(|line| line.trim() == "$") { | |
| return Ok(Startup::Ready); | |
| } | |
| Ok(Startup::Wait) | |
| } | |
| pub(super) async fn submit( | |
| io: &mut (impl AsyncWrite + Unpin), | |
| screen: &mut watch::Receiver<Screen>, | |
| cwd: &str, | |
| prompt: &str, | |
| images: &[Value], | |
| bridge: &mcp::Bridge, | |
| start: &mut Start, | |
| ) -> Result<Submitted, Error> { | |
| let mut mark = 0; | |
| let ready = async { | |
| loop { | |
| let (text, end) = { | |
| let s = screen.borrow(); | |
| (s.after(mark), s.end) | |
| }; | |
| match startup(&text, cwd)? { | |
| Startup::Ready => return Ok::<_, Error>(()), | |
| Startup::Answer(key) => { | |
| mark = end; | |
| write(io, key).await?; | |
| } | |
| Startup::Wait => changed(screen).await?, | |
| } | |
| } | |
| }; | |
| tokio::time::timeout(runtime::SETUP_TIMEOUT, ready) | |
| .await | |
| .map_err(|_| { | |
| let screen = screen.borrow(); | |
| let tail = screen.after(screen.end.saturating_sub(4096)); | |
| Error::Provider(format!( | |
| "Claude interactive startup timed out. Recent terminal output:\n{}", | |
| tail.trim() | |
| )) | |
| })??; | |
| // The prompt can draw before MCP discovery ends. | |
| tokio::time::timeout(runtime::SETUP_TIMEOUT, bridge.listed.cancelled()) | |
| .await | |
| .map_err(|_| Error::Provider("Claude Host MCP discovery timed out".into()))?; | |
| bridge.admit()?; | |
| send(io, screen, prompt, images, start).await | |
| } | |
| /// What `send` put into the composer: the image markers, then the prompt. | |
| pub(super) struct Submitted { | |
| pub markers: String, | |
| pub prompt: String, | |
| pub images: usize, | |
| } | |
| // Enter keeps Claude's native busy-input semantics; it is not the send-now shortcut. | |
| pub(super) async fn send( | |
| io: &mut (impl AsyncWrite + Unpin), | |
| screen: &mut watch::Receiver<Screen>, | |
| prompt: &str, | |
| images: &[Value], | |
| start: &mut Start, | |
| ) -> Result<Submitted, Error> { | |
| let mut markers = Vec::with_capacity(images.len()); | |
| for (index, image) in images.iter().enumerate() { | |
| let path = runtime::string(image, "/path")?; | |
| let mark = screen.borrow().end; | |
| paste(io, path).await?; | |
| let accepted = async { | |
| loop { | |
| // AX redraws may repeat older labels. Use the latest label, never the | |
| // first match in scrollback, and require a new attachment in this composer. | |
| if let Some(marker) = image_marker(&screen.borrow().after(mark)) | |
| && !markers.iter().any(|seen| seen == &marker) | |
| { | |
| return Ok::<_, Error>(marker); | |
| } | |
| changed(screen).await?; | |
| } | |
| }; | |
| let marker = tokio::time::timeout(runtime::SETUP_TIMEOUT, accepted) | |
| .await | |
| .map_err(|_| Error::Provider(format!("Claude did not accept image {}", index + 1)))??; | |
| markers.push(marker); | |
| } | |
| let mark = screen.borrow().end; | |
| paste(io, prompt).await?; | |
| let echoed = async { | |
| loop { | |
| let observation = screen.borrow().after(mark); | |
| if shows(composer(&observation), prompt) { | |
| return Ok::<_, Error>(()); | |
| } | |
| changed(screen).await?; | |
| } | |
| }; | |
| let budget = runtime::SETUP_TIMEOUT + Duration::from_secs(prompt.len() as u64 / (32 * 1024)); | |
| tokio::time::timeout(budget, echoed) | |
| .await | |
| .map_err(|_| Error::Provider("Claude did not acknowledge the pasted prompt".into()))??; | |
| *start = Start::Submitted; | |
| // Enter is sent only after every attachment and the text have been acknowledged. | |
| write(io, b"\r").await?; | |
| Ok(Submitted { | |
| markers: markers.join(" "), | |
| prompt: prompt.into(), | |
| images: images.len(), | |
| }) | |
| } | |
| /// Whether the composer shows the pasted prompt. The terminal wraps a long line | |
| /// wherever it reaches the last column, which in text without spaces is inside a | |
| /// word, so only the characters that are not whitespace are compared. | |
| fn shows(composer: &str, prompt: &str) -> bool { | |
| let visible = |text: &str| -> String { text.chars().filter(|c| !c.is_whitespace()).collect() }; | |
| // Claude replaces large pastes by a numbered placeholder, preserving the actual text. | |
| composer.contains("[Pasted text") || visible(composer).contains(&visible(prompt)) | |
| } | |
| fn image_marker(text: &str) -> Option<String> { | |
| // A complete AX prompt redraw supersedes any historical labels before it. | |
| let (_, after) = composer(text).rsplit_once("[Image #")?; | |
| let end = after.find(']')?; | |
| let number = &after[..end]; | |
| if number.is_empty() || !number.bytes().all(|b| b.is_ascii_digit()) { | |
| return None; | |
| } | |
| Some(format!("[Image #{number}]")) | |
| } | |
| fn composer(text: &str) -> &str { | |
| text.rsplit_once("\n$").map_or(text, |(_, latest)| latest) | |
| } | |
| #[cfg(test)] | |
| mod tests { | |
| use super::*; | |
| fn observed(bytes: &[u8]) -> String { | |
| let mut screen = Screen::default(); | |
| Decoder::default().push(&mut screen, bytes); | |
| screen.after(0) | |
| } | |
| // Byte sequences written by Claude Code 2.1.327 and 2.1.328 with --ax-screen-reader. | |
| #[test] | |
| fn text_added_to_an_earlier_row_does_not_join_the_prompt_row() { | |
| let hint = b"bypass permissions on\r\neffort: medium \xc2\xb7 /effort\r\n$\x1b[2G\x1b[2A\x1b[22G (shift+tab to cycle)\x1b[2G\x1b[2B"; | |
| let text = observed(hint); | |
| assert!( | |
| matches!(startup(&text, "/workspace"), Ok(Startup::Ready)), | |
| "{text:?}" | |
| ); | |
| // Partial erase-to-EOL on an earlier row (CSI K) and ECMA-48 zero counts (0A/0B -> 1) | |
| // must not leak earlier-row updates onto the prompt row. | |
| let edited = b"bypass permissions on\r\neffort: medium\r\n$\x1b[2G\x1b[2A\x1b[22G\x1b[K (updated)\x1b[2B\x1b[0Aabove\x1b[0B"; | |
| assert!( | |
| matches!(startup(&observed(edited), "/workspace"), Ok(Startup::Ready)), | |
| "{:?}", | |
| observed(edited) | |
| ); | |
| // After the cursor is back on the prompt row, typed text is observed again. | |
| assert!(observed(&[hint.as_slice(), b"hello"].concat()).ends_with("$hello")); | |
| assert!(observed(&[edited.as_slice(), b"hello"].concat()).ends_with("$hello")); | |
| } | |
| #[test] | |
| fn rows_that_claude_erases_and_redraws_are_observed() { | |
| let text = observed( | |
| b"$\xc2\xa0 one\r\ntwo\x1b[1A\x1b[2K\x1b[1A\x1b[2K\x1b[G$\xc2\xa0 one\r\ntwo three", | |
| ); | |
| assert_eq!(composer(&text), "\u{a0} one\ntwo three"); | |
| } | |
| #[test] | |
| fn a_prompt_wrapped_inside_text_without_spaces_is_acknowledged() { | |
| let prompt = "第一行没有空格的长文本。\n\n第二行 with spaces"; | |
| // The composer as a 120 column terminal draws it: wrapped after a character. | |
| assert!(shows( | |
| "\u{a0} 第一行没有空格\n的长文本。\n\n第二行 with\nspaces", | |
| prompt | |
| )); | |
| assert!(shows("\u{a0} [Pasted text #1 +4 lines]", prompt)); | |
| assert!(!shows("\u{a0} 第一行没有空格", prompt)); | |
| } | |
| #[test] | |
| fn latest_composer_image_labels_do_not_assume_a_counter_reset() { | |
| assert_eq!( | |
| image_marker("[Image #7] [Image #8]"), | |
| Some("[Image #8]".into()) | |
| ); | |
| assert_eq!(image_marker("old [Image #7]\n$"), None); | |
| assert_eq!( | |
| image_marker("old [Image #7]\n$[Image #1]"), | |
| Some("[Image #1]".into()) | |
| ); | |
| assert_eq!(image_marker("[Image #1] [Image #"), None); | |
| assert_eq!(image_marker("[Image #not-a-number]"), None); | |
| } | |
| #[test] | |
| fn trust_is_only_for_the_captured_workspace_and_control_bytes_are_not_keys() { | |
| let prompt = "Permission Required: Accessing workspace:\n/work\nQuick safety check\ny. Yes, I trust this folder\nn. No, exit\nEnter y/n:\nEnter to confirm"; | |
| assert!(matches!( | |
| startup(prompt, "/work").unwrap(), | |
| Startup::Answer(b"y\r") | |
| )); | |
| assert!(startup(prompt, "/work-other").is_err()); | |
| assert!(startup(&prompt.replace("/work", "/work/subdir"), "/work").is_err()); | |
| assert_eq!(text("literal\x1b[201~\rnext"), "literal\\u{1b}[201~\nnext"); | |
| assert_eq!(text("a\r\nb"), "a\nb"); | |
| let mut decoder = Decoder::default(); | |
| let mut screen = Screen::default(); | |
| decoder.push(&mut screen, b"\x1b[31m[Image #"); | |
| decoder.push(&mut screen, b"2]\x1b[0m"); | |
| assert_eq!(screen.after(0), "[Image #2]"); | |
| } | |
| } |