1use crate::tools::{agent, claude, codex, gemini, opencode, qwen};
4use command_stream::terminal::{
5 capture_terminal, TerminalCapture, TerminalCaptureError, TerminalCaptureOptions,
6 TerminalInteraction, TerminalKey,
7};
8use std::collections::HashMap;
9use std::path::PathBuf;
10use std::time::Duration;
11use thiserror::Error;
12
13const READ_ONLY_OPENCODE_PERMISSION: &str = r#"{"edit":"deny","bash":"deny","task":"deny"}"#;
14const SUPPORTED_TOOLS: [&str; 6] = ["claude", "codex", "opencode", "agent", "gemini", "qwen"];
15
16#[derive(Debug, Clone)]
18pub struct AgentTuiOptions {
19 pub tool: String,
21 pub working_directory: PathBuf,
23 pub executable: Option<String>,
25 pub prefix_args: Vec<String>,
27 pub extra_args: Vec<String>,
29 pub extra_env: HashMap<String, String>,
31 pub unset_env: Vec<String>,
35 pub model: Option<String>,
37 pub prompt: Option<String>,
39 pub system_prompt: Option<String>,
41 pub system_prompt_file: Option<PathBuf>,
45 pub prompt_after: Option<String>,
47 pub prompt_key: TerminalKey,
49 pub resume: Option<String>,
51 pub read_only: bool,
53 pub plan_only: bool,
55 pub approve_each: bool,
57 pub skip_default_safety_flags: bool,
59 pub cols: u16,
61 pub rows: u16,
63 pub settle_duration: Duration,
65 pub interactions: Vec<TerminalInteraction>,
67 pub stop_marker: Option<String>,
69 pub stop_marker_grace: Duration,
71 pub timeout: Duration,
73 pub artifact_directory: Option<PathBuf>,
75 pub frames_on_write: bool,
78 pub recording: bool,
81}
82
83impl Default for AgentTuiOptions {
84 fn default() -> Self {
85 Self {
86 tool: String::new(),
87 working_directory: PathBuf::new(),
88 executable: None,
89 prefix_args: Vec::new(),
90 extra_args: Vec::new(),
91 extra_env: HashMap::new(),
92 unset_env: Vec::new(),
93 model: None,
94 prompt: None,
95 system_prompt: None,
96 system_prompt_file: None,
97 prompt_after: None,
98 prompt_key: TerminalKey::Enter,
99 resume: None,
100 read_only: false,
101 plan_only: false,
102 approve_each: false,
103 skip_default_safety_flags: false,
104 cols: 80,
105 rows: 24,
106 settle_duration: Duration::from_millis(35),
107 interactions: Vec::new(),
108 stop_marker: None,
109 stop_marker_grace: Duration::from_millis(250),
110 timeout: Duration::from_secs(30),
111 artifact_directory: None,
112 frames_on_write: false,
113 recording: true,
114 }
115 }
116}
117
118#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct AgentTuiLaunch {
121 pub file: String,
123 pub args: Vec<String>,
125 pub cwd: Option<PathBuf>,
127 pub env: HashMap<String, String>,
129}
130
131#[derive(Debug, Clone, PartialEq, Eq)]
133pub enum AgentTuiEvent {
134 Message {
136 role: String,
138 content: String,
140 },
141 ToolCall {
143 name: String,
145 input: String,
147 },
148}
149
150#[derive(Debug, Clone)]
152pub struct AgentTuiCapture {
153 pub tool: String,
155 pub terminal: TerminalCapture,
157 pub events: Vec<AgentTuiEvent>,
159}
160
161#[derive(Debug, Error)]
163pub enum AgentTuiError {
164 #[error("{0}")]
166 Launch(String),
167 #[error(transparent)]
169 Capture(#[from] TerminalCaptureError),
170}
171
172fn mapped_model(tool: &str, model: &str) -> String {
173 match tool {
174 "claude" => claude::model_arg(model),
175 "codex" => codex::map_model_to_id(model),
176 "opencode" => opencode::map_model_to_id(model),
177 "agent" => agent::map_model_to_id(model),
178 "gemini" => gemini::map_model_to_id(model),
179 "qwen" => qwen::map_model_to_id(model),
180 _ => model.to_string(),
181 }
182}
183
184fn push_model(args: &mut Vec<String>, options: &AgentTuiOptions) {
185 if let Some(model) = &options.model {
186 args.push("--model".into());
187 args.push(mapped_model(&options.tool, model));
188 }
189}
190
191fn claude_args(options: &AgentTuiOptions) -> Vec<String> {
192 let mut args = Vec::new();
193 if options.read_only {
194 args.extend(["--permission-mode".into(), "plan".into()]);
195 } else if options.approve_each {
196 args.extend(["--permission-mode".into(), "default".into()]);
197 } else if !options.skip_default_safety_flags {
198 args.push("--dangerously-skip-permissions".into());
199 }
200 push_model(&mut args, options);
201 if let Some(file) = &options.system_prompt_file {
202 args.extend([
203 "--append-system-prompt-file".into(),
204 file.to_string_lossy().into_owned(),
205 ]);
206 } else if let Some(system_prompt) = &options.system_prompt {
207 args.extend(["--append-system-prompt".into(), system_prompt.clone()]);
208 }
209 if let Some(resume) = &options.resume {
210 args.extend(["--resume".into(), resume.clone()]);
211 }
212 args.push("--ax-screen-reader".into());
213 args
214}
215
216fn codex_args(options: &AgentTuiOptions) -> Vec<String> {
217 let mut args = Vec::new();
218 push_model(&mut args, options);
219 if options.read_only {
220 args.extend([
221 "--sandbox".into(),
222 "read-only".into(),
223 "--ask-for-approval".into(),
224 "never".into(),
225 ]);
226 } else if options.approve_each {
227 args.extend(["--ask-for-approval".into(), "on-request".into()]);
228 } else if !options.skip_default_safety_flags {
229 args.push("--dangerously-bypass-approvals-and-sandbox".into());
230 }
231 args.push("--no-alt-screen".into());
232 if let Some(resume) = &options.resume {
233 args.extend(["resume".into(), resume.clone()]);
234 }
235 args
236}
237
238fn opencode_args(options: &AgentTuiOptions) -> Vec<String> {
239 let mut args = vec!["--mini".into(), "--no-replay".into()];
240 push_model(&mut args, options);
241 if let Some(resume) = &options.resume {
242 args.extend(["--session".into(), resume.clone()]);
243 }
244 if !options.read_only && !options.approve_each && !options.skip_default_safety_flags {
245 args.push("--auto".into());
246 }
247 args
248}
249
250fn agent_args(options: &AgentTuiOptions) -> Vec<String> {
251 let mut args = Vec::new();
252 push_model(&mut args, options);
253 let permission = if options.read_only {
254 Some("readonly")
255 } else if options.plan_only {
256 Some("plan")
257 } else if options.approve_each {
258 Some("ask")
259 } else {
260 None
261 };
262 if let Some(permission) = permission {
263 args.extend(["--permission-mode".into(), permission.into()]);
264 }
265 if let Some(resume) = &options.resume {
266 args.extend(["--resume".into(), resume.clone()]);
267 }
268 args
269}
270
271fn gemini_args(options: &AgentTuiOptions) -> Vec<String> {
272 let mut args = Vec::new();
273 push_model(&mut args, options);
274 if options.read_only {
275 args.extend(["--approval-mode".into(), "plan".into()]);
276 } else if options.approve_each {
277 args.extend(["--approval-mode".into(), "default".into()]);
278 } else if !options.skip_default_safety_flags {
279 args.push("--yolo".into());
280 }
281 if let Some(resume) = &options.resume {
282 args.extend(["--resume".into(), resume.clone()]);
283 }
284 args
285}
286
287fn qwen_args(options: &AgentTuiOptions) -> Vec<String> {
288 let mut args = Vec::new();
289 push_model(&mut args, options);
290 if options.read_only {
291 args.push("--read-only".into());
292 }
293 if let Some(resume) = &options.resume {
294 args.extend(["--resume".into(), resume.clone()]);
295 }
296 args
297}
298
299pub fn build_agent_tui_launch(options: &AgentTuiOptions) -> Result<AgentTuiLaunch, AgentTuiError> {
301 if !SUPPORTED_TOOLS.contains(&options.tool.as_str()) {
302 return Err(AgentTuiError::Launch(format!(
303 "unsupported TUI tool: {}",
304 options.tool
305 )));
306 }
307 if options.working_directory.as_os_str().is_empty() {
308 return Err(AgentTuiError::Launch(
309 "working_directory is required".into(),
310 ));
311 }
312 let generated = match options.tool.as_str() {
313 "claude" => claude_args(options),
314 "codex" => codex_args(options),
315 "opencode" => opencode_args(options),
316 "agent" => agent_args(options),
317 "gemini" => gemini_args(options),
318 "qwen" => qwen_args(options),
319 _ => unreachable!("supported tools were validated"),
320 };
321 let mut args =
322 Vec::with_capacity(options.prefix_args.len() + generated.len() + options.extra_args.len());
323 args.extend(options.prefix_args.clone());
324 args.extend(generated);
325 args.extend(options.extra_args.clone());
326 let mut env = options.extra_env.clone();
327 if options.tool == "opencode" && options.read_only {
328 env.insert(
329 "OPENCODE_PERMISSION".into(),
330 READ_ONLY_OPENCODE_PERMISSION.into(),
331 );
332 }
333 let mut file = options
334 .executable
335 .clone()
336 .unwrap_or_else(|| options.tool.clone());
337 if !options.unset_env.is_empty() {
338 let mut wrapped = Vec::with_capacity(options.unset_env.len() * 2 + args.len() + 1);
339 for name in &options.unset_env {
340 if !crate::tools::shell::is_valid_env_name(name) {
341 return Err(AgentTuiError::Launch(format!(
342 "invalid environment variable name: {name}"
343 )));
344 }
345 env.remove(name);
346 wrapped.push("-u".to_string());
347 wrapped.push(name.clone());
348 }
349 wrapped.push(file);
350 wrapped.extend(args);
351 file = "env".into();
352 args = wrapped;
353 }
354 Ok(AgentTuiLaunch {
355 file,
356 args,
357 cwd: Some(options.working_directory.clone()),
358 env,
359 })
360}
361
362fn strip_marker(line: &str) -> &str {
363 line.trim_start_matches(|character: char| {
364 matches!(character, '│' | '┃' | '>' | '›' | '❯' | '•' | '*') || character.is_whitespace()
365 })
366}
367
368pub fn normalize_tui_transcript(transcript: &str) -> Vec<AgentTuiEvent> {
370 transcript
371 .lines()
372 .filter_map(|raw_line| {
373 let line = strip_marker(raw_line.trim());
374 let (kind, content) = line.split_once(':')?;
375 if kind.eq_ignore_ascii_case("user") || kind.eq_ignore_ascii_case("assistant") {
376 return Some(AgentTuiEvent::Message {
377 role: kind.to_ascii_lowercase(),
378 content: content.trim().into(),
379 });
380 }
381 if kind.eq_ignore_ascii_case("tool_call") || kind.eq_ignore_ascii_case("tool call") {
382 let (name, input) = content
383 .trim()
384 .split_once(char::is_whitespace)
385 .unwrap_or_else(|| (content.trim(), ""));
386 return Some(AgentTuiEvent::ToolCall {
387 name: name.into(),
388 input: input.trim().into(),
389 });
390 }
391 None
392 })
393 .collect()
394}
395
396pub fn capture_agent_tui(mut options: AgentTuiOptions) -> Result<AgentTuiCapture, AgentTuiError> {
398 let mut temp_prompt = None;
399 if options.tool == "claude" && options.system_prompt_file.is_none() {
400 if let Some(text) = options.system_prompt.as_deref().filter(|t| !t.is_empty()) {
401 let file = write_private_temp_file(text)?;
402 options.system_prompt_file = Some(file.clone());
403 temp_prompt = Some(file);
404 }
405 }
406 let result = run_agent_tui(options);
407 if let Some(file) = temp_prompt {
408 let _ = std::fs::remove_file(file);
409 }
410 result
411}
412
413fn write_private_temp_file(content: &str) -> Result<PathBuf, AgentTuiError> {
415 use std::io::Write;
416 static SEQUENCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
417 let nanos = std::time::SystemTime::now()
418 .duration_since(std::time::UNIX_EPOCH)
419 .map_or(0, |d| d.as_nanos());
420 let sequence = SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
421 let path = std::env::temp_dir().join(format!(
422 "agent-commander-tui-{}-{nanos}-{sequence}.txt",
423 std::process::id()
424 ));
425 let mut open = std::fs::OpenOptions::new();
426 open.write(true).create_new(true);
427 #[cfg(unix)]
428 {
429 use std::os::unix::fs::OpenOptionsExt;
430 open.mode(0o600);
431 }
432 let mut file = open
433 .open(&path)
434 .and_then(|mut file| file.write_all(content.as_bytes()).map(|()| file))
435 .map_err(|e| AgentTuiError::Launch(format!("system prompt file: {e}")))?;
436 file.flush()
437 .map_err(|e| AgentTuiError::Launch(format!("system prompt file: {e}")))?;
438 Ok(path)
439}
440
441fn run_agent_tui(options: AgentTuiOptions) -> Result<AgentTuiCapture, AgentTuiError> {
442 let launch = build_agent_tui_launch(&options)?;
443 let combined_prompt = match (&options.system_prompt, &options.prompt) {
444 (Some(system), Some(prompt)) if options.tool != "claude" => {
445 Some(format!("{system}\n\n{prompt}"))
446 }
447 (Some(system), None) if options.tool != "claude" => Some(system.clone()),
448 (_, prompt) => prompt.clone(),
449 };
450 let mut interactions =
451 Vec::with_capacity(options.interactions.len() + usize::from(combined_prompt.is_some()));
452 if let Some(prompt) = combined_prompt {
453 interactions.push(TerminalInteraction {
454 after: options.prompt_after.clone(),
455 text: Some(prompt),
456 key: Some(options.prompt_key.clone()),
457 ..TerminalInteraction::default()
458 });
459 }
460 interactions.extend(options.interactions.clone());
461 let terminal = capture_terminal(TerminalCaptureOptions {
462 file: launch.file,
463 args: launch.args,
464 cwd: launch.cwd,
465 env: launch.env,
466 cols: options.cols,
467 rows: options.rows,
468 settle_duration: options.settle_duration,
469 interactions,
470 stop_marker: options.stop_marker,
471 stop_marker_grace: options.stop_marker_grace,
472 timeout: Some(options.timeout),
473 artifact_directory: options.artifact_directory,
474 frames_on_write: options.frames_on_write,
475 recording: options.recording,
476 })?;
477 Ok(AgentTuiCapture {
478 tool: options.tool,
479 events: normalize_tui_transcript(&terminal.transcript),
480 terminal,
481 })
482}