1pub 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#[derive(Debug, Clone)]
35pub enum AgentEvent {
36 Status(SessionStatus),
37 Output(String),
39 OutputAppend(String),
42 ToolCall {
43 name: String,
44 input: String,
45 ok: Option<bool>,
47 output: Option<String>,
48 },
49 Permission(PermissionRequest),
50 Question(ertangle_core::UserQuestion),
51 Cost(Cost),
52 Model(String),
53 Commands(Vec<String>),
55 NativeId(String),
57 Limited(String),
59 Note(String),
61 Context {
63 used: u64,
64 window: Option<u64>,
65 },
66 Quota(ertangle_core::Quota),
68 Exited(Option<i32>),
70}
71
72#[derive(Debug, Clone)]
74pub struct SessionSpec {
75 pub id: SessionId,
76 pub kind: AgentKind,
77 pub cwd: PathBuf,
78 pub transport: Transport,
79 pub bin: Option<String>,
81 pub args: Vec<String>,
83 pub model: Option<String>,
85 pub effort: Option<String>,
87 pub allowed_tools: Vec<String>,
89 pub disallowed_tools: Vec<String>,
90 pub read_only: bool,
92 pub sandbox: Option<String>,
94 pub env: Vec<(String, String)>,
96 pub permission: PermissionPolicy,
98 pub mcp_exe: Option<PathBuf>,
100 pub system_append: Option<String>,
103 pub initial_prompt: Option<String>,
105 pub initial_attachments: Vec<ertangle_core::Attachment>,
107 pub resume: Option<String>,
109 pub cols: u16,
110 pub rows: u16,
111}
112
113pub trait AgentControl: Send + Sync {
115 fn send_input(&self, text: &str) -> Result<()>;
117 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 fn cancel(&self) -> Result<()>;
123 fn kill(&self) -> Result<()>;
125 fn sleep(&self) -> Result<()> {
127 Ok(())
128 }
129 fn wake(&self) -> Result<()> {
131 Ok(())
132 }
133 fn resolve_permission(&self, req: &str, decision: Decision) -> Result<()>;
135 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 fn transport(&self) -> &'static str;
145 fn pid(&self) -> Option<u32> {
147 None
148 }
149 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
163pub 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
178fn 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
199pub fn signal_pid(pid: u32, sig: &str) -> Result<()> {
201 if pid <= 1 {
203 bail!("{}", tr!("拒絕對 PID {pid} 送訊號", pid = pid));
204 }
205 run_kill(kill_args(sig, pid.to_string()))
206}
207
208pub fn signal_pgid(pgid: u32, sig: &str) -> Result<()> {
210 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
256const SSH_ENV_VARS: &[&str] = &["SSH_CLIENT", "SSH_CONNECTION", "SSH_TTY"];
258
259pub fn env_removals(kind: &AgentKind) -> &'static [&'static str] {
266 let has_dbus = std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_some_and(|v| !v.is_empty());
267 env_removals_for(kind, has_dbus)
268}
269
270fn env_removals_for(kind: &AgentKind, has_dbus: bool) -> &'static [&'static str] {
271 match kind {
272 AgentKind::Antigravity if has_dbus => SSH_ENV_VARS,
273 _ => &[],
274 }
275}
276
277pub fn which(prog: &str) -> Option<PathBuf> {
279 if prog.contains('/') {
280 let p = PathBuf::from(prog);
281 return p.is_file().then_some(p);
282 }
283 let path = std::env::var_os("PATH")?;
284 for dir in std::env::split_paths(&path) {
285 let cand = dir.join(prog);
286 if cand.is_file() {
287 return Some(cand);
288 }
289 }
290 None
291}
292
293pub fn agent_bin(prog: &str, env_var: &str) -> Option<PathBuf> {
295 match ertangle_core::env_var(env_var) {
296 Some(p) if !p.is_empty() => which(&p),
297 _ => which(prog),
298 }
299}
300
301pub const EFFORT_LEVELS: [&str; 5] = ["low", "medium", "high", "xhigh", "max"];
303
304pub fn spawn(spec: SessionSpec, tx: Sender<AgentEvent>) -> Result<Box<dyn AgentControl>> {
309 let is_claude = matches!(spec.kind, AgentKind::ClaudeCode);
311 if let Some(e) = &spec.effort {
312 if !EFFORT_LEVELS.contains(&e.as_str()) {
313 bail!(
314 "{}",
315 tr!(
316 "未知的 effort `{e}`;可用:{list}",
317 e = e,
318 list = EFFORT_LEVELS.join(", ")
319 )
320 );
321 }
322 }
323 let is_codex = matches!(spec.kind, AgentKind::Codex);
324 if !is_claude && (!spec.allowed_tools.is_empty() || !spec.disallowed_tools.is_empty()) {
325 bail!(
326 "{}",
327 tr!(
328 "{kind} 尚不支援 allowed_tools/disallowed_tools;請改用 claude",
329 kind = spec.kind
330 )
331 );
332 }
333 if spec.read_only && !is_claude && !is_codex {
334 bail!(
335 "{}",
336 tr!(
337 "{kind} 尚不支援 read_only;請改用 claude 或 codex",
338 kind = spec.kind
339 )
340 );
341 }
342 if spec.sandbox.is_some() && !is_codex {
343 bail!("{}", tr!("sandbox 只適用於 codex"));
344 }
345 if spec.resume.is_some() {
347 if spec.transport == Transport::Pty {
348 bail!("{}", tr!("PTY 模式無法接續對話"));
349 }
350 if matches!(spec.kind, AgentKind::Custom(_)) {
351 bail!(
352 "{}",
353 tr!("{kind} 沒有原生結構化協定,無法接續對話", kind = spec.kind)
354 );
355 }
356 }
357 let want_structured = match spec.transport {
358 _ if spec.resume.is_some() => true,
359 Transport::Pty => false,
360 Transport::Structured => true,
361 Transport::Auto => supports_structured(&spec.kind),
362 };
363
364 if want_structured {
365 match structured_start(spec.clone(), tx.clone()) {
366 Ok(ctl) => return Ok(ctl),
367 Err(e)
368 if spec.transport == Transport::Auto
369 && spec.model.is_none()
370 && spec.resume.is_none() =>
371 {
372 tracing::warn!("{} 原生協定啟動失敗,退回 PTY:{e}", spec.kind);
373 }
374 Err(e) => return Err(e),
375 }
376 }
377
378 if let Some(m) = &spec.model {
379 if spec.transport != Transport::Pty {
380 bail!(
381 "{}",
382 tr!(
383 "{kind} 尚不支援以結構化模式指定 model ({m});請改用 --transport pty 並以參數傳入",
384 kind = spec.kind,
385 m = m
386 )
387 );
388 }
389 }
390 let (prog, _) = spec.kind.pty_command();
391 if which(prog).is_none() {
392 bail!("{}", tr!("找不到 `{prog}`,請先安裝", prog = prog));
393 }
394 pty::start(spec, tx)
395}
396
397pub fn supports_structured(kind: &AgentKind) -> bool {
399 match kind {
400 AgentKind::OpenCode | AgentKind::Antigravity | AgentKind::Copilot => {
401 kind.acp_command().is_some()
402 }
403 AgentKind::ClaudeCode => agent_bin("claude", "ERTANGLE_CLAUDE_BIN").is_some(),
404 AgentKind::Codex => which("codex").is_some(),
405 AgentKind::Custom(_) => false,
406 }
407}
408
409pub fn is_installed(kind: &AgentKind) -> bool {
411 match kind {
412 AgentKind::ClaudeCode => agent_bin("claude", "ERTANGLE_CLAUDE_BIN").is_some(),
413 _ => is_installed_with(kind, |prog| which(prog).is_some()),
414 }
415}
416
417fn is_installed_with<F: Fn(&str) -> bool>(kind: &AgentKind, has_bin: F) -> bool {
418 match kind {
419 AgentKind::OpenCode | AgentKind::Antigravity | AgentKind::Copilot => {
420 kind.acp_command().is_some_and(|(prog, _)| has_bin(prog))
421 }
422 AgentKind::ClaudeCode => has_bin("claude"),
423 AgentKind::Codex => has_bin("codex"),
424 AgentKind::Custom(_) => false,
425 }
426}
427
428fn structured_start(spec: SessionSpec, tx: Sender<AgentEvent>) -> Result<Box<dyn AgentControl>> {
430 match spec.kind {
431 AgentKind::OpenCode | AgentKind::Antigravity | AgentKind::Copilot => {
432 let (prog, _) = spec
433 .kind
434 .acp_command()
435 .with_context(|| tr!("此 agent 不支援 ACP"))?;
436 let target = spec.bin.as_deref().unwrap_or(prog);
437 if which(target).is_none() {
438 bail!(
439 "{}",
440 tr!(
441 "找不到 `{target}`,請先安裝或改用 --transport pty",
442 target = target
443 )
444 );
445 }
446 acp::start(spec, tx)
447 }
448 AgentKind::ClaudeCode => {
449 let target = spec.bin.as_deref().unwrap_or("claude");
450 if spec.bin.is_none() && ertangle_core::env_var_os("ERTANGLE_CLAUDE_BIN").is_some() {
451 } else if which(target).is_none() {
453 bail!(
454 "{}",
455 tr!(
456 "找不到 `{target}`,請先安裝或改用 --transport pty",
457 target = target
458 )
459 );
460 }
461 claude::start(spec, tx)
462 }
463 AgentKind::Codex => {
464 let target = spec.bin.as_deref().unwrap_or("codex");
465 if which(target).is_none() {
466 bail!(
467 "{}",
468 tr!(
469 "找不到 `{target}`,請先安裝或改用 --transport pty",
470 target = target
471 )
472 );
473 }
474 codex::start(spec, tx)
475 }
476 AgentKind::Custom(_) => bail!(
477 "{}",
478 tr!("自訂 agent 沒有原生結構化協定,請用 --transport pty")
479 ),
480 }
481}
482
483#[cfg(test)]
484mod tests {
485 use super::*;
486
487 #[test]
488 fn which_finds_sh_and_misses_nonsense() {
489 assert!(which("sh").is_some());
490 assert!(which("definitely-not-a-real-binary-xyz").is_none());
491 }
492
493 #[test]
494 fn is_installed_checks_each_agent_binary() {
495 let only_agy_and_claude = |bin: &str| matches!(bin, "agy" | "claude");
496 assert!(is_installed_with(
497 &AgentKind::Antigravity,
498 only_agy_and_claude
499 ));
500 assert!(is_installed_with(
501 &AgentKind::ClaudeCode,
502 only_agy_and_claude
503 ));
504 assert!(!is_installed_with(
505 &AgentKind::OpenCode,
506 only_agy_and_claude
507 ));
508 assert!(!is_installed_with(&AgentKind::Codex, only_agy_and_claude));
509 assert!(!is_installed_with(&AgentKind::Copilot, only_agy_and_claude));
510 assert!(is_installed_with(&AgentKind::Copilot, |bin| bin == "copilot"));
511 assert!(!is_installed_with(&AgentKind::Custom("foo".into()), |_| {
512 true
513 }));
514 }
515}
516
517#[cfg(test)]
518mod env_removal_tests {
519 use super::*;
520
521 #[test]
522 fn agy_drops_ssh_vars_only_when_keyring_reachable() {
523 assert_eq!(
524 env_removals_for(&AgentKind::Antigravity, true),
525 SSH_ENV_VARS
526 );
527 assert!(env_removals_for(&AgentKind::Antigravity, false).is_empty());
528 assert!(env_removals_for(&AgentKind::OpenCode, true).is_empty());
529 assert!(env_removals_for(&AgentKind::Codex, true).is_empty());
530 }
531}