AnyBot/src/pty.rs

196 lines
8.0 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 互動終端機: a program that needs a real terminal — a coding agent's own screen (pi-bolt,
// Claude Code), an editor, a y/n prompt — runs in a pseudo-terminal (a pty on Mac and Linux,
// ConPTY on Windows), and the bot reads its screen as a person sees it (the escape codes drawn
// by a terminal emulator, not dumped as text) and types into it, keys included.
//
// Plain commands don't come here: they run with their input closed (tools::run_command), so a
// program that reads its input to the end — `pi-bolt -p` did, `cat` does — finishes instead of
// waiting forever for words that never come.
use std::io::{Read, Write};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
/// The terminal's size: wide and tall enough for the coding agents' screens.
pub const ROWS: u16 = 40;
pub const COLS: u16 = 120;
/// Lines kept above the screen (what scrolled off).
const SCROLLBACK: usize = 2_000;
/// A running program's terminal: what it shows, and its keyboard.
pub struct Screen {
parser: Mutex<vt100::Parser>,
writer: Mutex<Box<dyn Write + Send>>,
/// Kept open: closing the controlling side would hang up on the program.
_master: Mutex<Box<dyn portable_pty::MasterPty + Send>>,
/// Bytes the program has written, and when it last wrote (ms since `born`).
bytes: AtomicU64,
last_ms: AtomicU64,
born: Instant,
}
impl Screen {
/// The screen as text: without the empty lines under the last one written, and a run of
/// empty lines as one (a full-screen program fills all 40 rows; the blanks were most of what
/// a bot read).
pub fn text(&self) -> String {
let p = self.parser.lock().unwrap();
let t = p.screen().contents();
let mut out: Vec<&str> = vec![];
for l in t.trim_end().lines().map(str::trim_end) {
if l.is_empty() && out.last().is_some_and(|x| x.is_empty()) {
continue;
}
out.push(l);
}
out.join("\n")
}
/// How much it has written so far.
pub fn bytes(&self) -> u64 {
self.bytes.load(Ordering::Relaxed)
}
/// How long since it last wrote anything.
pub fn quiet_for(&self) -> Duration {
let now = self.born.elapsed().as_millis() as u64;
Duration::from_millis(now.saturating_sub(self.last_ms.load(Ordering::Relaxed)))
}
/// Type into it.
pub fn send(&self, bytes: &[u8]) -> Result<(), String> {
let mut w = self.writer.lock().unwrap();
w.write_all(bytes).and_then(|_| w.flush()).map_err(|e| format!("送不進去:{e}"))
}
}
/// Start `command` (built like any other: its sandbox, environment and folder) in a terminal.
pub fn spawn(command: &std::process::Command) -> Result<(Arc<Screen>, Box<dyn portable_pty::Child + Send + Sync>), String> {
let pair = portable_pty::native_pty_system()
.openpty(portable_pty::PtySize { rows: ROWS, cols: COLS, pixel_width: 0, pixel_height: 0 })
.map_err(|e| format!("開不了終端機:{e}"))?;
let mut b = portable_pty::CommandBuilder::new(command.get_program());
b.args(command.get_args());
for (k, v) in command.get_envs() {
match v {
Some(v) => b.env(k, v),
None => b.env_remove(k),
}
}
if let Some(d) = command.get_current_dir() {
b.cwd(d);
}
// A terminal that draws colours and moves the cursor, like the person's own.
b.env("TERM", "xterm-256color");
b.env_remove("NO_COLOR");
let child = pair.slave.spawn_command(b).map_err(|e| format!("無法執行:{e}"))?;
// (Only the program holds its side now: when it ends, reading sees the end.)
drop(pair.slave);
let mut reader = pair.master.try_clone_reader().map_err(|e| format!("讀不到終端機:{e}"))?;
let writer = pair.master.take_writer().map_err(|e| format!("寫不進終端機:{e}"))?;
let screen = Arc::new(Screen {
parser: Mutex::new(vt100::Parser::new(ROWS, COLS, SCROLLBACK)),
writer: Mutex::new(writer),
_master: Mutex::new(pair.master),
bytes: AtomicU64::new(0),
last_ms: AtomicU64::new(0),
born: Instant::now(),
});
let s = screen.clone();
std::thread::spawn(move || {
let mut chunk = [0u8; 8192];
while let Ok(n) = reader.read(&mut chunk) {
if n == 0 {
break;
}
s.parser.lock().unwrap().process(&chunk[..n]);
s.bytes.fetch_add(n as u64, Ordering::Relaxed);
s.last_ms.store(s.born.elapsed().as_millis() as u64, Ordering::Relaxed);
}
});
Ok((screen, child))
}
/// What a named key sends ("enter", "up", "ctrl-c"…), or why it is unknown.
pub fn key(name: &str) -> Result<Vec<u8>, String> {
let n = name.trim().to_lowercase().replace(['_', ' '], "-");
Ok(match n.as_str() {
"enter" | "return" => b"\r".to_vec(),
"tab" => b"\t".to_vec(),
"shift-tab" | "backtab" => b"\x1b[Z".to_vec(),
"esc" | "escape" => b"\x1b".to_vec(),
"backspace" => b"\x7f".to_vec(),
"delete" | "del" => b"\x1b[3~".to_vec(),
"space" => b" ".to_vec(),
"up" => b"\x1b[A".to_vec(),
"down" => b"\x1b[B".to_vec(),
"right" => b"\x1b[C".to_vec(),
"left" => b"\x1b[D".to_vec(),
"home" => b"\x1b[H".to_vec(),
"end" => b"\x1b[F".to_vec(),
"pageup" | "page-up" => b"\x1b[5~".to_vec(),
"pagedown" | "page-down" => b"\x1b[6~".to_vec(),
k => match k.strip_prefix("ctrl-").map(|c| c.as_bytes()) {
// Ctrl + a letter: 1–26 (ctrl-c is 3, ctrl-d 4).
Some([c]) if c.is_ascii_lowercase() => vec![c - b'a' + 1],
_ => return Err(format!("不認得的按鍵「{name}」:可用 enter、tab、shift-tab、esc、backspace、delete、space、up、down、left、right、home、end、pageup、pagedown、ctrl-字母")),
},
})
}
/// Wait for the screen to settle: until the program has written something new and then been
/// quiet for `quiet` (a prompt waiting, an answer finished), `until` shows on the screen, it
/// ends (`ended`), or `max` passes. `since` is how much it had written before.
pub fn settle(screen: &Screen, since: u64, max: Duration, quiet: Duration, until: &str, ended: impl Fn() -> bool, stop: impl Fn() -> bool) {
let start = Instant::now();
loop {
if ended() || stop() {
// (What it wrote last reaches the screen.)
std::thread::sleep(Duration::from_millis(120));
return;
}
if !until.is_empty() {
if screen.text().contains(until) {
return;
}
} else if screen.bytes() > since && screen.quiet_for() >= quiet {
return;
}
if start.elapsed() >= max {
return;
}
std::thread::sleep(Duration::from_millis(50));
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
#[test]
fn keys_are_what_a_terminal_sends() {
assert_eq!(key("Enter").unwrap(), b"\r");
assert_eq!(key("ctrl-c").unwrap(), vec![3]);
assert_eq!(key("Ctrl_D").unwrap(), vec![4]);
assert_eq!(key("up").unwrap(), b"\x1b[A");
assert!(key("hyper").unwrap_err().contains("不認得"));
}
/// A program that asks: its question is on the screen, the answer typed reaches it.
#[test]
fn a_prompt_is_seen_and_answered() {
let mut c = std::process::Command::new("/bin/sh");
c.arg("-c").arg("printf '你的名字?'; read n; echo \"你好 $n\"; sleep 5");
let (screen, mut child) = spawn(&c).unwrap();
settle(&screen, 0, Duration::from_secs(5), Duration::from_millis(300), "名字", || false, || false);
assert!(screen.text().contains("你的名字?"), "{}", screen.text());
let before = screen.bytes();
screen.send(b"Ada\r").unwrap();
settle(&screen, before, Duration::from_secs(5), Duration::from_millis(300), "你好 Ada", || false, || false);
assert!(screen.text().contains("你好 Ada"), "{}", screen.text());
let _ = child.kill();
let _ = child.wait();
}
}