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            // 強制終止處理程序群組或處理程序,若行程已結束則忽略
46            let _ = crate::signal_pgid(pid, "-KILL").or_else(|_| crate::signal_pid(pid, "-KILL"));
47        }
48        self.child
49            .lock()
50            .unwrap_or_else(|e| e.into_inner())
51            .kill()
52            .ok();
53        Ok(())
54    }
55
56    fn sleep(&self) -> Result<()> {
57        if let Some(pid) = self.pid() {
58            crate::signal_pgid(pid, "-STOP").or_else(|_| crate::signal_pid(pid, "-STOP"))?;
59        }
60        Ok(())
61    }
62
63    fn wake(&self) -> Result<()> {
64        if let Some(pid) = self.pid() {
65            crate::signal_pgid(pid, "-CONT").or_else(|_| crate::signal_pid(pid, "-CONT"))?;
66        }
67        Ok(())
68    }
69
70    /// PTY has no structured protocol and cannot handle per-item permission approval.
71    fn resolve_permission(&self, _req: &str, _decision: Decision) -> Result<()> {
72        Ok(())
73    }
74
75    /// PTY resolves user questions by writing the answer string directly to stdin.
76    fn resolve_question(&self, _id: &str, answers: &[String]) -> Result<()> {
77        if let Some(ans) = answers.first() {
78            self.send_input(&format!("{ans}\n"))?;
79        }
80        Ok(())
81    }
82
83    fn transport(&self) -> &'static str {
84        "pty"
85    }
86}
87
88pub fn start(spec: SessionSpec, tx: Sender<AgentEvent>) -> Result<Box<dyn AgentControl>> {
89    let pty_system = native_pty_system();
90    let pair = pty_system
91        .openpty(PtySize {
92            rows: spec.rows.max(24),
93            cols: spec.cols.max(80),
94            pixel_width: 0,
95            pixel_height: 0,
96        })
97        .with_context(|| tr!("openpty 失敗"))?;
98
99    let (default_prog, base) = spec.kind.pty_command();
100    let prog = match spec.bin.as_deref() {
101        Some(b) => crate::which(b).with_context(|| tr!("找不到指定的執行檔 `{b}`", b = b))?,
102        None => crate::which(default_prog)
103            .with_context(|| tr!("找不到 `{prog}`", prog = default_prog))?,
104    };
105    let mut cmd = CommandBuilder::new(prog);
106    for a in base {
107        cmd.arg(a);
108    }
109    for a in &spec.args {
110        cmd.arg(a);
111    }
112    cmd.cwd(&spec.cwd);
113    cmd.env("TERM", "xterm-256color");
114    for k in crate::env_removals(&spec.kind) {
115        cmd.env_remove(k);
116    }
117    for (k, v) in &spec.env {
118        cmd.env(k, v);
119    }
120
121    let child = pair
122        .slave
123        .spawn_command(cmd)
124        .with_context(|| tr!("spawn agent 失敗"))?;
125    drop(pair.slave);
126
127    let mut reader = pair
128        .master
129        .try_clone_reader()
130        .with_context(|| tr!("clone reader 失敗"))?;
131    let writer = pair
132        .master
133        .take_writer()
134        .with_context(|| tr!("take writer 失敗"))?;
135    drop(pair.master);
136
137    // 接收端若已關閉則忽略狀態更新
138    let _ = tx.send(AgentEvent::Status(SessionStatus::Idle));
139
140    // Read output: strip terminal escape codes and send in real time, but skip redraw chunks that are entirely whitespace.
141    //
142    // Note: Fullscreen TUIs (opencode/claude/agy interactive mode) use screen-oriented output positioned
143    // solely with escape sequences, so plain text extraction is inherently imperfect. For readable structured output,
144    // use ACP / headless; this is a universal fallback. Full vt100 terminal emulation is deferred for later.
145    {
146        let tx = tx.clone();
147        std::thread::spawn(move || {
148            let mut stripper = crate::ansi::AnsiStripper::new();
149            let mut buf = [0u8; 8192];
150            loop {
151                match reader.read(&mut buf) {
152                    Ok(0) => break,
153                    Ok(n) => {
154                        let text = stripper.feed(buf.get(..n).unwrap_or_default());
155                        if text.trim().is_empty() {
156                            continue;
157                        }
158                        let trimmed = text.trim_end_matches(['\r', ' ', '\t']);
159                        if tx.send(AgentEvent::Output(trimmed.to_string())).is_err() {
160                            break;
161                        }
162                    }
163                    Err(_) => break, // Linux returns EIO when the child process exits
164                }
165            }
166        });
167    }
168
169    // Wait for termination (poll with try_wait to avoid holding the lock during a blocking wait, which would deadlock kill).
170    let child = Arc::new(Mutex::new(child));
171    {
172        let child = child.clone();
173        let tx = tx.clone();
174        std::thread::spawn(move || {
175            let code = loop {
176                let status = {
177                    let mut c = child.lock().unwrap_or_else(|e| e.into_inner());
178                    c.try_wait()
179                };
180                match status {
181                    Ok(Some(s)) => break Some(s.exit_code() as i32),
182                    Ok(None) => std::thread::sleep(std::time::Duration::from_millis(100)),
183                    Err(_) => break None,
184                }
185            };
186            // 接收端若已關閉則忽略退出事件
187            let _ = tx.send(AgentEvent::Exited(code));
188        });
189    }
190
191    let control = PtyControl {
192        writer: Mutex::new(writer),
193        child,
194    };
195
196    if let Some(p) = &spec.initial_prompt {
197        // 寫入初始 prompt 失敗由後續事件與流程處理
198        let _ = control.send_input_with(p, &spec.initial_attachments);
199    }
200
201    Ok(Box::new(control))
202}