Skip to main content

ertangle_adapter/
pty.rs

1//! PTY passthrough adapter.
2//!
3//! Treats the agent CLI as an interactive process running inside a pseudo-terminal: output directly becomes [`AgentEvent::Output`],
4//! and user input is written back to the PTY. This approach **works for any CLI agent** and serves as a universal fallback.
5
6use crate::{AgentControl, AgentEvent, SessionSpec};
7use anyhow::{Context, Result};
8use ertangle_core::{Decision, SessionStatus};
9use portable_pty::{native_pty_system, CommandBuilder, PtySize};
10use std::io::{Read, Write};
11use std::sync::mpsc::Sender;
12use std::sync::{Arc, Mutex};
13use tr::tr;
14
15struct PtyControl {
16    writer: Mutex<Box<dyn Write + Send>>,
17    child: Arc<Mutex<Box<dyn portable_pty::Child + Send + Sync>>>,
18}
19
20impl AgentControl for PtyControl {
21    fn send_input(&self, text: &str) -> Result<()> {
22        let mut w = self.writer.lock().unwrap_or_else(|e| e.into_inner());
23        w.write_all(text.as_bytes())?;
24        w.write_all(b"\r")?;
25        w.flush()?;
26        Ok(())
27    }
28
29    fn cancel(&self) -> Result<()> {
30        let mut w = self.writer.lock().unwrap_or_else(|e| e.into_inner());
31        w.write_all(&[0x03])?; // Ctrl-C
32        w.flush()?;
33        Ok(())
34    }
35
36    fn pid(&self) -> Option<u32> {
37        self.child
38            .lock()
39            .unwrap_or_else(|e| e.into_inner())
40            .process_id()
41    }
42
43    fn kill(&self) -> Result<()> {
44        if let Some(pid) = self.pid() {
45            let _ = crate::signal_pgid(pid, "-KILL").or_else(|_| crate::signal_pid(pid, "-KILL"));
46        }
47        self.child
48            .lock()
49            .unwrap_or_else(|e| e.into_inner())
50            .kill()
51            .ok();
52        Ok(())
53    }
54
55    fn sleep(&self) -> Result<()> {
56        if let Some(pid) = self.pid() {
57            crate::signal_pgid(pid, "-STOP").or_else(|_| crate::signal_pid(pid, "-STOP"))?;
58        }
59        Ok(())
60    }
61
62    fn wake(&self) -> Result<()> {
63        if let Some(pid) = self.pid() {
64            crate::signal_pgid(pid, "-CONT").or_else(|_| crate::signal_pid(pid, "-CONT"))?;
65        }
66        Ok(())
67    }
68
69    /// PTY has no structured protocol and cannot handle per-item permission approval.
70    fn resolve_permission(&self, _req: &str, _decision: Decision) -> Result<()> {
71        Ok(())
72    }
73
74    /// PTY resolves user questions by writing the answer string directly to stdin.
75    fn resolve_question(&self, _id: &str, answers: &[String]) -> Result<()> {
76        if let Some(ans) = answers.first() {
77            self.send_input(&format!("{ans}\n"))?;
78        }
79        Ok(())
80    }
81
82    fn transport(&self) -> &'static str {
83        "pty"
84    }
85}
86
87pub fn start(spec: SessionSpec, tx: Sender<AgentEvent>) -> Result<Box<dyn AgentControl>> {
88    let pty_system = native_pty_system();
89    let pair = pty_system
90        .openpty(PtySize {
91            rows: spec.rows.max(24),
92            cols: spec.cols.max(80),
93            pixel_width: 0,
94            pixel_height: 0,
95        })
96        .with_context(|| tr!("openpty 失敗"))?;
97
98    let (default_prog, base) = spec.kind.pty_command();
99    let prog = match spec.bin.as_deref() {
100        Some(b) => crate::which(b).with_context(|| tr!("找不到指定的執行檔 `{b}`", b = b))?,
101        None => crate::which(default_prog)
102            .with_context(|| tr!("找不到 `{prog}`", prog = default_prog))?,
103    };
104    let mut cmd = CommandBuilder::new(prog);
105    for a in base {
106        cmd.arg(a);
107    }
108    for a in &spec.args {
109        cmd.arg(a);
110    }
111    cmd.cwd(&spec.cwd);
112    cmd.env("TERM", "xterm-256color");
113    for (k, v) in &spec.env {
114        cmd.env(k, v);
115    }
116
117    let child = pair
118        .slave
119        .spawn_command(cmd)
120        .with_context(|| tr!("spawn agent 失敗"))?;
121    drop(pair.slave);
122
123    let mut reader = pair
124        .master
125        .try_clone_reader()
126        .with_context(|| tr!("clone reader 失敗"))?;
127    let writer = pair
128        .master
129        .take_writer()
130        .with_context(|| tr!("take writer 失敗"))?;
131    drop(pair.master);
132
133    let _ = tx.send(AgentEvent::Status(SessionStatus::Idle));
134
135    // Read output: strip terminal escape codes and send in real time, but skip redraw chunks that are entirely whitespace.
136    //
137    // Note: Fullscreen TUIs (opencode/claude/agy interactive mode) use screen-oriented output positioned
138    // solely with escape sequences, so plain text extraction is inherently imperfect. For readable structured output,
139    // use ACP / headless; this is a universal fallback. Full vt100 terminal emulation is deferred for later.
140    {
141        let tx = tx.clone();
142        std::thread::spawn(move || {
143            let mut stripper = crate::ansi::AnsiStripper::new();
144            let mut buf = [0u8; 8192];
145            loop {
146                match reader.read(&mut buf) {
147                    Ok(0) => break,
148                    Ok(n) => {
149                        let text = stripper.feed(&buf[..n]);
150                        if text.trim().is_empty() {
151                            continue;
152                        }
153                        let trimmed = text.trim_end_matches(['\r', ' ', '\t']);
154                        if tx.send(AgentEvent::Output(trimmed.to_string())).is_err() {
155                            break;
156                        }
157                    }
158                    Err(_) => break, // Linux returns EIO when the child process exits
159                }
160            }
161        });
162    }
163
164    // Wait for termination (poll with try_wait to avoid holding the lock during a blocking wait, which would deadlock kill).
165    let child = Arc::new(Mutex::new(child));
166    {
167        let child = child.clone();
168        let tx = tx.clone();
169        std::thread::spawn(move || {
170            let code = loop {
171                let status = {
172                    let mut c = child.lock().unwrap_or_else(|e| e.into_inner());
173                    c.try_wait()
174                };
175                match status {
176                    Ok(Some(s)) => break Some(s.exit_code() as i32),
177                    Ok(None) => std::thread::sleep(std::time::Duration::from_millis(100)),
178                    Err(_) => break None,
179                }
180            };
181            let _ = tx.send(AgentEvent::Exited(code));
182        });
183    }
184
185    let control = PtyControl {
186        writer: Mutex::new(writer),
187        child,
188    };
189
190    if let Some(p) = &spec.initial_prompt {
191        let _ = control.send_input_with(p, &spec.initial_attachments);
192    }
193
194    Ok(Box::new(control))
195}