Skip to main content

ertangle_adapter/
lib.rs

1//! `ertangle-adapter` — Normalization layer for diverse agents.
2//!
3//! Protocols for each agent (ACP, stream-json, app-server, PTY) are translated here into
4//! a uniform set of [`AgentEvent`]s, so layers above the daemon do not need to know which agent is underneath.
5//!
6//! Structured adapters (native, zero extra dependencies):
7//! * [`acp`]: Agent Client Protocol — OpenCode (`opencode acp`), Antigravity (`agy acp`).
8//! * [`claude`]: Claude Code's `--input-format/--output-format stream-json`.
9//! * [`codex`]: Codex's `codex app-server` (stdio JSON-RPC).
10//!
11//! Universal fallback:
12//! * [`pty`]: PTY passthrough, **works for any CLI agent**.
13
14pub mod acp;
15pub mod ansi;
16pub mod claude;
17pub mod codex;
18pub mod models;
19pub mod pty;
20pub mod question;
21pub mod stderr;
22pub mod stream;
23
24use anyhow::{bail, Context, Result};
25use ertangle_core::{
26    AgentKind, Cost, Decision, PermissionPolicy, PermissionRequest, SessionId, SessionStatus,
27};
28use ertangle_protocol::Transport;
29use std::path::PathBuf;
30use std::sync::mpsc::Sender;
31use tr::tr;
32
33/// Events sent upward after normalization by the adapter.
34#[derive(Debug, Clone)]
35pub enum AgentEvent {
36    Status(SessionStatus),
37    /// Text output from the agent (may contain newlines).
38    Output(String),
39    /// Continues the last unterminated output line (the first segment of the text is
40    /// appended to it), so a mid-line stream pause does not split Markdown constructs.
41    OutputAppend(String),
42    ToolCall {
43        name: String,
44        input: String,
45        /// `None` = in progress.
46        ok: Option<bool>,
47        output: Option<String>,
48    },
49    Permission(PermissionRequest),
50    Question(ertangle_core::UserQuestion),
51    Cost(Cost),
52    Model(String),
53    /// Native slash command names of the agent (without `/`).
54    Commands(Vec<String>),
55    /// Native session ID of the agent (for resumption). Sent only when resumption is possible with this ID.
56    NativeId(String),
57    /// Quota exhausted / rate limited.
58    Limited(String),
59    /// Sets a status note for the session (e.g. failure reason).
60    Note(String),
61    /// Session context usage.
62    Context {
63        used: u64,
64        window: Option<u64>,
65    },
66    /// Account quota status update.
67    Quota(ertangle_core::Quota),
68    /// Process exited.
69    Exited(Option<i32>),
70}
71
72/// All information required to launch a session.
73#[derive(Debug, Clone)]
74pub struct SessionSpec {
75    pub id: SessionId,
76    pub kind: AgentKind,
77    pub cwd: PathBuf,
78    pub transport: Transport,
79    /// Custom executable path or name (overrides default PATH lookup).
80    pub bin: Option<String>,
81    /// Extra command-line arguments.
82    pub args: Vec<String>,
83    /// Model to use (currently only supported by Claude structured mode).
84    pub model: Option<String>,
85    /// Reasoning effort (Claude `--effort`, Codex `model_reasoning_effort`, ACP configOption).
86    pub effort: Option<String>,
87    /// Claude-specific: extra allowed / disallowed tools.
88    pub allowed_tools: Vec<String>,
89    pub disallowed_tools: Vec<String>,
90    /// Read-only mode (achieved via plan mode in Claude).
91    pub read_only: bool,
92    /// Codex-specific sandbox mode.
93    pub sandbox: Option<String>,
94    /// Extra environment variables.
95    pub env: Vec<(String, String)>,
96    /// Unified permission policy.
97    pub permission: PermissionPolicy,
98    /// If the `ertangle` executable path is provided, the adapter injects `ertangle mcp` into the agent at startup.
99    pub mcp_exe: Option<PathBuf>,
100    /// Collaboration instructions appended to the system prompt (Claude `--append-system-prompt`, Codex `developerInstructions`)
101    /// or prepended to the first prompt in ACP; not injected for PTY.
102    pub system_append: Option<String>,
103    /// First prompt sent immediately after startup.
104    pub initial_prompt: Option<String>,
105    /// Attachments for the initial prompt.
106    pub initial_attachments: Vec<ertangle_core::Attachment>,
107    /// Resume an existing conversation: agent's native conversation ID. `None` starts a new conversation.
108    pub resume: Option<String>,
109    pub cols: u16,
110    pub rows: u16,
111}
112
113/// Control handle for a running session.
114pub trait AgentControl: Send + Sync {
115    /// Sends user input / prompt text.
116    fn send_input(&self, text: &str) -> Result<()>;
117    /// Sends a prompt with files/images attached. By default inlines attachments into text; adapters supporting image blocks override this.
118    fn send_input_with(&self, text: &str, attachments: &[ertangle_core::Attachment]) -> Result<()> {
119        self.send_input(&ertangle_core::compose_text(text, attachments, true))
120    }
121    /// Interrupts the current turn (without killing the process).
122    fn cancel(&self) -> Result<()>;
123    /// Terminates and kills the process.
124    fn kill(&self) -> Result<()>;
125    /// Pauses child processes (SIGSTOP, used for idle sleep).
126    fn sleep(&self) -> Result<()> {
127        Ok(())
128    }
129    /// Wakes child processes (SIGCONT).
130    fn wake(&self) -> Result<()> {
131        Ok(())
132    }
133    /// Resolves a permission request.
134    fn resolve_permission(&self, req: &str, decision: Decision) -> Result<()>;
135    /// Resolves an interactive user question.
136    fn resolve_question(&self, id: &str, answers: &[String]) -> Result<()> {
137        let _ = (id, answers);
138        bail!(
139            "{}",
140            tr!("{transport} 不支援回答問題", transport = self.transport())
141        )
142    }
143    /// Actual transport used by this session (for display).
144    fn transport(&self) -> &'static str;
145    /// Gets the agent main process PID.
146    fn pid(&self) -> Option<u32> {
147        None
148    }
149    /// Switches model and/or effort at runtime (takes effect from the next turn).
150    /// On success returns the model actually in effect (if reported by the agent); unsupported adapters return a clear error.
151    fn set_config(&self, model: Option<&str>, effort: Option<&str>) -> Result<Option<String>> {
152        let _ = (model, effort);
153        bail!(
154            "{}",
155            tr!(
156                "{transport} 不支援執行期切換 model/effort",
157                transport = self.transport()
158            )
159        )
160    }
161}
162
163/// Checks if an effort value is valid.
164pub fn check_effort(e: &str) -> Result<()> {
165    if !EFFORT_LEVELS.contains(&e) {
166        bail!(
167            "{}",
168            tr!(
169                "未知的 effort `{e}`;可用:{list}",
170                e = e,
171                list = EFFORT_LEVELS.join(", ")
172            )
173        );
174    }
175    Ok(())
176}
177
178/// Builds arguments for `kill -s <NAME> -- <target>`.
179///
180/// Always use the `-s NAME --` form: procps-ng 4.0.4's `kill -KILL -<pgid>` misparses
181/// `-<pgid>` as `-1` (all processes for the user), equivalent to `kill -9 -1`, which logs out the entire desktop.
182fn kill_args(sig: &str, target: String) -> [String; 4] {
183    let name = sig.trim_start_matches('-').trim_start_matches("SIG");
184    ["-s".into(), name.into(), "--".into(), target]
185}
186
187fn run_kill(args: [String; 4]) -> Result<()> {
188    let status = std::process::Command::new("kill")
189        .args(&args)
190        .stderr(std::process::Stdio::null())
191        .status()
192        .with_context(|| tr!("執行 kill 失敗"))?;
193    if !status.success() {
194        bail!("{}", tr!("kill {args} 失敗", args = args.join(" ")));
195    }
196    Ok(())
197}
198
199/// Sends a Unix signal (e.g. `-STOP` / `-CONT`) to a specific PID.
200pub fn signal_pid(pid: u32, sig: &str) -> Result<()> {
201    // Never send to 0 / 1 as they refer to "own group" or init.
202    if pid <= 1 {
203        bail!("{}", tr!("拒絕對 PID {pid} 送訊號", pid = pid));
204    }
205    run_kill(kill_args(sig, pid.to_string()))
206}
207
208/// Sends a Unix signal (e.g. `-STOP` / `-CONT` / `-KILL`) to a specific process group (PGID).
209pub fn signal_pgid(pgid: u32, sig: &str) -> Result<()> {
210    // Never send to `-0` (own group) or `-1` (all processes).
211    if pgid <= 1 {
212        bail!("{}", tr!("拒絕對 PID {pid} 送訊號", pid = pgid));
213    }
214    run_kill(kill_args(sig, format!("-{pgid}")))
215}
216
217#[cfg(test)]
218mod signal_tests {
219    use super::*;
220
221    #[test]
222    fn kill_args_never_put_negative_target_before_double_dash() {
223        assert_eq!(
224            kill_args("-KILL", "-4242".into()),
225            ["-s", "KILL", "--", "-4242"]
226        );
227        assert_eq!(kill_args("-STOP", "42".into()), ["-s", "STOP", "--", "42"]);
228        assert_eq!(
229            kill_args("SIGCONT", "42".into()),
230            ["-s", "CONT", "--", "42"]
231        );
232    }
233
234    #[test]
235    fn refuses_pid_zero_and_one() {
236        assert!(signal_pgid(0, "-KILL").is_err());
237        assert!(signal_pgid(1, "-KILL").is_err());
238        assert!(signal_pid(0, "-KILL").is_err());
239        assert!(signal_pid(1, "-KILL").is_err());
240    }
241
242    #[test]
243    fn pgid_signal_hits_only_the_group() {
244        use std::os::unix::process::CommandExt;
245        let mut child = std::process::Command::new("sleep")
246            .arg("30")
247            .process_group(0)
248            .spawn()
249            .unwrap();
250        signal_pgid(child.id(), "-KILL").unwrap();
251        let st = child.wait().unwrap();
252        assert!(!st.success());
253    }
254}
255
256/// Probes whether an executable exists and returns its absolute path.
257pub fn which(prog: &str) -> Option<PathBuf> {
258    if prog.contains('/') {
259        let p = PathBuf::from(prog);
260        return p.is_file().then_some(p);
261    }
262    let path = std::env::var_os("PATH")?;
263    for dir in std::env::split_paths(&path) {
264        let cand = dir.join(prog);
265        if cand.is_file() {
266            return Some(cand);
267        }
268    }
269    None
270}
271
272/// Finds the agent executable: checks environment variable override first (for testing and custom installs), then searches PATH.
273pub fn agent_bin(prog: &str, env_var: &str) -> Option<PathBuf> {
274    match ertangle_core::env_var(env_var) {
275        Some(p) if !p.is_empty() => which(&p),
276        _ => which(prog),
277    }
278}
279
280/// Valid reasoning effort levels.
281pub const EFFORT_LEVELS: [&str; 5] = ["low", "medium", "high", "xhigh", "max"];
282
283/// Starts a session and returns a control handle; events stream through `tx`.
284///
285/// Determines whether to use native structured protocols or PTY passthrough based on `spec.transport`.
286/// `Auto` chooses the best native protocol for the agent; falls back to PTY if native startup fails.
287pub fn spawn(spec: SessionSpec, tx: Sender<AgentEvent>) -> Result<Box<dyn AgentControl>> {
288    // Explicitly reject unsupported granular permission options instead of silently ignoring them.
289    let is_claude = matches!(spec.kind, AgentKind::ClaudeCode);
290    if let Some(e) = &spec.effort {
291        if !EFFORT_LEVELS.contains(&e.as_str()) {
292            bail!(
293                "{}",
294                tr!(
295                    "未知的 effort `{e}`;可用:{list}",
296                    e = e,
297                    list = EFFORT_LEVELS.join(", ")
298                )
299            );
300        }
301    }
302    let is_codex = matches!(spec.kind, AgentKind::Codex);
303    if !is_claude && (!spec.allowed_tools.is_empty() || !spec.disallowed_tools.is_empty()) {
304        bail!(
305            "{}",
306            tr!(
307                "{kind} 尚不支援 allowed_tools/disallowed_tools;請改用 claude",
308                kind = spec.kind
309            )
310        );
311    }
312    if spec.read_only && !is_claude && !is_codex {
313        bail!(
314            "{}",
315            tr!(
316                "{kind} 尚不支援 read_only;請改用 claude 或 codex",
317                kind = spec.kind
318            )
319        );
320    }
321    if spec.sandbox.is_some() && !is_codex {
322        bail!("{}", tr!("sandbox 只適用於 codex"));
323    }
324    // Resumption is only supported via native protocols; do not silently start a new conversation.
325    if spec.resume.is_some() {
326        if spec.transport == Transport::Pty {
327            bail!("{}", tr!("PTY 模式無法接續對話"));
328        }
329        if matches!(spec.kind, AgentKind::Custom(_)) {
330            bail!(
331                "{}",
332                tr!("{kind} 沒有原生結構化協定,無法接續對話", kind = spec.kind)
333            );
334        }
335    }
336    let want_structured = match spec.transport {
337        _ if spec.resume.is_some() => true,
338        Transport::Pty => false,
339        Transport::Structured => true,
340        Transport::Auto => supports_structured(&spec.kind),
341    };
342
343    if want_structured {
344        match structured_start(spec.clone(), tx.clone()) {
345            Ok(ctl) => return Ok(ctl),
346            Err(e)
347                if spec.transport == Transport::Auto
348                    && spec.model.is_none()
349                    && spec.resume.is_none() =>
350            {
351                tracing::warn!("{} 原生協定啟動失敗,退回 PTY:{e}", spec.kind);
352            }
353            Err(e) => return Err(e),
354        }
355    }
356
357    if let Some(m) = &spec.model {
358        if spec.transport != Transport::Pty {
359            bail!(
360                "{}",
361                tr!(
362                    "{kind} 尚不支援以結構化模式指定 model ({m});請改用 --transport pty 並以參數傳入",
363                    kind = spec.kind,
364                    m = m
365                )
366            );
367        }
368    }
369    let (prog, _) = spec.kind.pty_command();
370    if which(prog).is_none() {
371        bail!("{}", tr!("找不到 `{prog}`,請先安裝", prog = prog));
372    }
373    pty::start(spec, tx)
374}
375
376/// Whether this agent has a native structured protocol available.
377pub fn supports_structured(kind: &AgentKind) -> bool {
378    match kind {
379        AgentKind::OpenCode | AgentKind::Antigravity => kind.acp_command().is_some(),
380        AgentKind::ClaudeCode => agent_bin("claude", "ERTANGLE_CLAUDE_BIN").is_some(),
381        AgentKind::Codex => which("codex").is_some(),
382        AgentKind::Custom(_) => false,
383    }
384}
385
386/// Checks whether the corresponding structured agent binary is installed in local `$PATH`.
387pub fn is_installed(kind: &AgentKind) -> bool {
388    match kind {
389        AgentKind::ClaudeCode => agent_bin("claude", "ERTANGLE_CLAUDE_BIN").is_some(),
390        _ => is_installed_with(kind, |prog| which(prog).is_some()),
391    }
392}
393
394fn is_installed_with<F: Fn(&str) -> bool>(kind: &AgentKind, has_bin: F) -> bool {
395    match kind {
396        AgentKind::OpenCode | AgentKind::Antigravity => {
397            kind.acp_command().is_some_and(|(prog, _)| has_bin(prog))
398        }
399        AgentKind::ClaudeCode => has_bin("claude"),
400        AgentKind::Codex => has_bin("codex"),
401        AgentKind::Custom(_) => false,
402    }
403}
404
405/// Starts the corresponding native structured adapter based on agent kind.
406fn structured_start(spec: SessionSpec, tx: Sender<AgentEvent>) -> Result<Box<dyn AgentControl>> {
407    match spec.kind {
408        AgentKind::OpenCode | AgentKind::Antigravity => {
409            let (prog, _) = spec
410                .kind
411                .acp_command()
412                .with_context(|| tr!("此 agent 不支援 ACP"))?;
413            let target = spec.bin.as_deref().unwrap_or(prog);
414            if which(target).is_none() {
415                bail!(
416                    "{}",
417                    tr!(
418                        "找不到 `{target}`,請先安裝或改用 --transport pty",
419                        target = target
420                    )
421                );
422            }
423            acp::start(spec, tx)
424        }
425        AgentKind::ClaudeCode => {
426            let target = spec.bin.as_deref().unwrap_or("claude");
427            if spec.bin.is_none() && ertangle_core::env_var_os("ERTANGLE_CLAUDE_BIN").is_some() {
428                // Handled by claude::start via ERTANGLE_CLAUDE_BIN
429            } else if which(target).is_none() {
430                bail!(
431                    "{}",
432                    tr!(
433                        "找不到 `{target}`,請先安裝或改用 --transport pty",
434                        target = target
435                    )
436                );
437            }
438            claude::start(spec, tx)
439        }
440        AgentKind::Codex => {
441            let target = spec.bin.as_deref().unwrap_or("codex");
442            if which(target).is_none() {
443                bail!(
444                    "{}",
445                    tr!(
446                        "找不到 `{target}`,請先安裝或改用 --transport pty",
447                        target = target
448                    )
449                );
450            }
451            codex::start(spec, tx)
452        }
453        AgentKind::Custom(_) => bail!(
454            "{}",
455            tr!("自訂 agent 沒有原生結構化協定,請用 --transport pty")
456        ),
457    }
458}
459
460#[cfg(test)]
461mod tests {
462    use super::*;
463
464    #[test]
465    fn which_finds_sh_and_misses_nonsense() {
466        assert!(which("sh").is_some());
467        assert!(which("definitely-not-a-real-binary-xyz").is_none());
468    }
469
470    #[test]
471    fn is_installed_checks_each_agent_binary() {
472        let only_agy_and_claude = |bin: &str| matches!(bin, "agy" | "claude");
473        assert!(is_installed_with(
474            &AgentKind::Antigravity,
475            only_agy_and_claude
476        ));
477        assert!(is_installed_with(
478            &AgentKind::ClaudeCode,
479            only_agy_and_claude
480        ));
481        assert!(!is_installed_with(
482            &AgentKind::OpenCode,
483            only_agy_and_claude
484        ));
485        assert!(!is_installed_with(&AgentKind::Codex, only_agy_and_claude));
486        assert!(!is_installed_with(&AgentKind::Custom("foo".into()), |_| {
487            true
488        }));
489    }
490}