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/// SSH 相關的環境變數;agy 看到任一個就判定為 SSH session。
257const SSH_ENV_VARS: &[&str] = &["SSH_CLIENT", "SSH_CONNECTION", "SSH_TTY"];
258
259/// 啟動該 agent 前應從環境移除的變數。
260///
261/// agy 偵測到 SSH session 時會改用檔案儲存 token,讀不到桌面 keyring 裡的登入,於是一直回報
262/// 「未登入」。daemon 從 SSH 終端機啟動時會繼承這些變數,所以在 keyring 可用 (有 D-Bus session)
263/// 時移除它們,讓 agy 照常讀 keyring。
264pub fn env_removals(kind: &AgentKind) -> &'static [&'static str] {
265    let has_dbus = std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_some_and(|v| !v.is_empty());
266    env_removals_for(kind, has_dbus)
267}
268
269fn env_removals_for(kind: &AgentKind, has_dbus: bool) -> &'static [&'static str] {
270    match kind {
271        AgentKind::Antigravity if has_dbus => SSH_ENV_VARS,
272        _ => &[],
273    }
274}
275
276/// Probes whether an executable exists and returns its absolute path.
277pub fn which(prog: &str) -> Option<PathBuf> {
278    if prog.contains('/') {
279        let p = PathBuf::from(prog);
280        return p.is_file().then_some(p);
281    }
282    let path = std::env::var_os("PATH")?;
283    for dir in std::env::split_paths(&path) {
284        let cand = dir.join(prog);
285        if cand.is_file() {
286            return Some(cand);
287        }
288    }
289    None
290}
291
292/// Finds the agent executable: checks environment variable override first (for testing and custom installs), then searches PATH.
293pub fn agent_bin(prog: &str, env_var: &str) -> Option<PathBuf> {
294    match ertangle_core::env_var(env_var) {
295        Some(p) if !p.is_empty() => which(&p),
296        _ => which(prog),
297    }
298}
299
300/// Valid reasoning effort levels.
301pub const EFFORT_LEVELS: [&str; 5] = ["low", "medium", "high", "xhigh", "max"];
302
303/// Starts a session and returns a control handle; events stream through `tx`.
304///
305/// Determines whether to use native structured protocols or PTY passthrough based on `spec.transport`.
306/// `Auto` chooses the best native protocol for the agent; falls back to PTY if native startup fails.
307pub fn spawn(spec: SessionSpec, tx: Sender<AgentEvent>) -> Result<Box<dyn AgentControl>> {
308    // Explicitly reject unsupported granular permission options instead of silently ignoring them.
309    let is_claude = matches!(spec.kind, AgentKind::ClaudeCode);
310    if let Some(e) = &spec.effort {
311        if !EFFORT_LEVELS.contains(&e.as_str()) {
312            bail!(
313                "{}",
314                tr!(
315                    "未知的 effort `{e}`;可用:{list}",
316                    e = e,
317                    list = EFFORT_LEVELS.join(", ")
318                )
319            );
320        }
321    }
322    let is_codex = matches!(spec.kind, AgentKind::Codex);
323    if !is_claude && (!spec.allowed_tools.is_empty() || !spec.disallowed_tools.is_empty()) {
324        bail!(
325            "{}",
326            tr!(
327                "{kind} 尚不支援 allowed_tools/disallowed_tools;請改用 claude",
328                kind = spec.kind
329            )
330        );
331    }
332    if spec.read_only && !is_claude && !is_codex {
333        bail!(
334            "{}",
335            tr!(
336                "{kind} 尚不支援 read_only;請改用 claude 或 codex",
337                kind = spec.kind
338            )
339        );
340    }
341    if spec.sandbox.is_some() && !is_codex {
342        bail!("{}", tr!("sandbox 只適用於 codex"));
343    }
344    // Resumption is only supported via native protocols; do not silently start a new conversation.
345    if spec.resume.is_some() {
346        if spec.transport == Transport::Pty {
347            bail!("{}", tr!("PTY 模式無法接續對話"));
348        }
349        if matches!(spec.kind, AgentKind::Custom(_)) {
350            bail!(
351                "{}",
352                tr!("{kind} 沒有原生結構化協定,無法接續對話", kind = spec.kind)
353            );
354        }
355    }
356    let want_structured = match spec.transport {
357        _ if spec.resume.is_some() => true,
358        Transport::Pty => false,
359        Transport::Structured => true,
360        Transport::Auto => supports_structured(&spec.kind),
361    };
362
363    if want_structured {
364        match structured_start(spec.clone(), tx.clone()) {
365            Ok(ctl) => return Ok(ctl),
366            Err(e)
367                if spec.transport == Transport::Auto
368                    && spec.model.is_none()
369                    && spec.resume.is_none() =>
370            {
371                tracing::warn!("{} 原生協定啟動失敗,退回 PTY:{e}", spec.kind);
372            }
373            Err(e) => return Err(e),
374        }
375    }
376
377    if let Some(m) = &spec.model {
378        if spec.transport != Transport::Pty {
379            bail!(
380                "{}",
381                tr!(
382                    "{kind} 尚不支援以結構化模式指定 model ({m});請改用 --transport pty 並以參數傳入",
383                    kind = spec.kind,
384                    m = m
385                )
386            );
387        }
388    }
389    let (prog, _) = spec.kind.pty_command();
390    if which(prog).is_none() {
391        bail!("{}", tr!("找不到 `{prog}`,請先安裝", prog = prog));
392    }
393    pty::start(spec, tx)
394}
395
396/// Whether this agent has a native structured protocol available.
397pub fn supports_structured(kind: &AgentKind) -> bool {
398    match kind {
399        AgentKind::OpenCode | AgentKind::Antigravity => kind.acp_command().is_some(),
400        AgentKind::ClaudeCode => agent_bin("claude", "ERTANGLE_CLAUDE_BIN").is_some(),
401        AgentKind::Codex => which("codex").is_some(),
402        AgentKind::Custom(_) => false,
403    }
404}
405
406/// Checks whether the corresponding structured agent binary is installed in local `$PATH`.
407pub fn is_installed(kind: &AgentKind) -> bool {
408    match kind {
409        AgentKind::ClaudeCode => agent_bin("claude", "ERTANGLE_CLAUDE_BIN").is_some(),
410        _ => is_installed_with(kind, |prog| which(prog).is_some()),
411    }
412}
413
414fn is_installed_with<F: Fn(&str) -> bool>(kind: &AgentKind, has_bin: F) -> bool {
415    match kind {
416        AgentKind::OpenCode | AgentKind::Antigravity => {
417            kind.acp_command().is_some_and(|(prog, _)| has_bin(prog))
418        }
419        AgentKind::ClaudeCode => has_bin("claude"),
420        AgentKind::Codex => has_bin("codex"),
421        AgentKind::Custom(_) => false,
422    }
423}
424
425/// Starts the corresponding native structured adapter based on agent kind.
426fn structured_start(spec: SessionSpec, tx: Sender<AgentEvent>) -> Result<Box<dyn AgentControl>> {
427    match spec.kind {
428        AgentKind::OpenCode | AgentKind::Antigravity => {
429            let (prog, _) = spec
430                .kind
431                .acp_command()
432                .with_context(|| tr!("此 agent 不支援 ACP"))?;
433            let target = spec.bin.as_deref().unwrap_or(prog);
434            if which(target).is_none() {
435                bail!(
436                    "{}",
437                    tr!(
438                        "找不到 `{target}`,請先安裝或改用 --transport pty",
439                        target = target
440                    )
441                );
442            }
443            acp::start(spec, tx)
444        }
445        AgentKind::ClaudeCode => {
446            let target = spec.bin.as_deref().unwrap_or("claude");
447            if spec.bin.is_none() && ertangle_core::env_var_os("ERTANGLE_CLAUDE_BIN").is_some() {
448                // Handled by claude::start via ERTANGLE_CLAUDE_BIN
449            } else if which(target).is_none() {
450                bail!(
451                    "{}",
452                    tr!(
453                        "找不到 `{target}`,請先安裝或改用 --transport pty",
454                        target = target
455                    )
456                );
457            }
458            claude::start(spec, tx)
459        }
460        AgentKind::Codex => {
461            let target = spec.bin.as_deref().unwrap_or("codex");
462            if which(target).is_none() {
463                bail!(
464                    "{}",
465                    tr!(
466                        "找不到 `{target}`,請先安裝或改用 --transport pty",
467                        target = target
468                    )
469                );
470            }
471            codex::start(spec, tx)
472        }
473        AgentKind::Custom(_) => bail!(
474            "{}",
475            tr!("自訂 agent 沒有原生結構化協定,請用 --transport pty")
476        ),
477    }
478}
479
480#[cfg(test)]
481mod tests {
482    use super::*;
483
484    #[test]
485    fn which_finds_sh_and_misses_nonsense() {
486        assert!(which("sh").is_some());
487        assert!(which("definitely-not-a-real-binary-xyz").is_none());
488    }
489
490    #[test]
491    fn is_installed_checks_each_agent_binary() {
492        let only_agy_and_claude = |bin: &str| matches!(bin, "agy" | "claude");
493        assert!(is_installed_with(
494            &AgentKind::Antigravity,
495            only_agy_and_claude
496        ));
497        assert!(is_installed_with(
498            &AgentKind::ClaudeCode,
499            only_agy_and_claude
500        ));
501        assert!(!is_installed_with(
502            &AgentKind::OpenCode,
503            only_agy_and_claude
504        ));
505        assert!(!is_installed_with(&AgentKind::Codex, only_agy_and_claude));
506        assert!(!is_installed_with(&AgentKind::Custom("foo".into()), |_| {
507            true
508        }));
509    }
510}
511
512#[cfg(test)]
513mod env_removal_tests {
514    use super::*;
515
516    #[test]
517    fn agy_drops_ssh_vars_only_when_keyring_reachable() {
518        assert_eq!(
519            env_removals_for(&AgentKind::Antigravity, true),
520            SSH_ENV_VARS
521        );
522        assert!(env_removals_for(&AgentKind::Antigravity, false).is_empty());
523        assert!(env_removals_for(&AgentKind::OpenCode, true).is_empty());
524        assert!(env_removals_for(&AgentKind::Codex, true).is_empty());
525    }
526}