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] {
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
276pub 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
292pub 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
300pub const EFFORT_LEVELS: [&str; 5] = ["low", "medium", "high", "xhigh", "max"];
302
303pub fn spawn(spec: SessionSpec, tx: Sender<AgentEvent>) -> Result<Box<dyn AgentControl>> {
308 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 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
396pub 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
406pub 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
425fn 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 } 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}