Skip to main content

agent_commander/
tui.rs

1//! Interactive terminal launch and capture for supported agent clients.
2
3use 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/// Options for launching and driving an agent's real interactive terminal UI.
17#[derive(Debug, Clone)]
18pub struct AgentTuiOptions {
19    /// Agent CLI name.
20    pub tool: String,
21    /// Directory in which the agent runs.
22    pub working_directory: PathBuf,
23    /// Override for the agent executable.
24    pub executable: Option<String>,
25    /// Arguments inserted before the generated agent arguments.
26    pub prefix_args: Vec<String>,
27    /// Additional agent arguments.
28    pub extra_args: Vec<String>,
29    /// Additional environment variables.
30    pub extra_env: HashMap<String, String>,
31    /// Variables removed from the inherited environment; the launch then
32    /// runs through `env -u NAME`, because the terminal capture can only add
33    /// variables.
34    pub unset_env: Vec<String>,
35    /// Optional model name or alias.
36    pub model: Option<String>,
37    /// Initial user prompt.
38    pub prompt: Option<String>,
39    /// Optional system prompt.
40    pub system_prompt: Option<String>,
41    /// Marker that must be observed before sending the initial prompt.
42    pub prompt_after: Option<String>,
43    /// Control key sent after the initial prompt.
44    pub prompt_key: TerminalKey,
45    /// Session identifier to resume.
46    pub resume: Option<String>,
47    /// Request the client's native read-only mode.
48    pub read_only: bool,
49    /// Request the client's native plan-only mode where distinct.
50    pub plan_only: bool,
51    /// Request approval for individual operations.
52    pub approve_each: bool,
53    /// Suppress the default autonomous safety-bypass flags.
54    pub skip_default_safety_flags: bool,
55    /// Initial terminal width.
56    pub cols: u16,
57    /// Initial terminal height.
58    pub rows: u16,
59    /// Time without output before a frame is considered settled.
60    pub settle_duration: Duration,
61    /// Input, control-key, and resize interactions.
62    pub interactions: Vec<TerminalInteraction>,
63    /// Marker after which the capture process can be stopped.
64    pub stop_marker: Option<String>,
65    /// Grace period after the stop marker.
66    pub stop_marker_grace: Duration,
67    /// Overall capture timeout.
68    pub timeout: Duration,
69    /// Directory for transcript, frame, cast, and animation artifacts.
70    pub artifact_directory: Option<PathBuf>,
71    /// Record a frame after every PTY write instead of after each settle
72    /// (command-stream 1.9.0 `frames_on_write`).
73    pub frames_on_write: bool,
74    /// Keep the full recording; `false` keeps only the latest frame and the
75    /// last 1 MB of output (command-stream 1.9.0 `recording`).
76    pub recording: bool,
77}
78
79impl Default for AgentTuiOptions {
80    fn default() -> Self {
81        Self {
82            tool: String::new(),
83            working_directory: PathBuf::new(),
84            executable: None,
85            prefix_args: Vec::new(),
86            extra_args: Vec::new(),
87            extra_env: HashMap::new(),
88            unset_env: Vec::new(),
89            model: None,
90            prompt: None,
91            system_prompt: None,
92            prompt_after: None,
93            prompt_key: TerminalKey::Enter,
94            resume: None,
95            read_only: false,
96            plan_only: false,
97            approve_each: false,
98            skip_default_safety_flags: false,
99            cols: 80,
100            rows: 24,
101            settle_duration: Duration::from_millis(35),
102            interactions: Vec::new(),
103            stop_marker: None,
104            stop_marker_grace: Duration::from_millis(250),
105            timeout: Duration::from_secs(30),
106            artifact_directory: None,
107            frames_on_write: false,
108            recording: true,
109        }
110    }
111}
112
113/// Executable, argv, cwd, and environment for an interactive agent launch.
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct AgentTuiLaunch {
116    /// Executable to launch.
117    pub file: String,
118    /// Shell-free argument vector.
119    pub args: Vec<String>,
120    /// Working directory.
121    pub cwd: Option<PathBuf>,
122    /// Environment overrides.
123    pub env: HashMap<String, String>,
124}
125
126/// Stable semantic event extracted from an agent TUI transcript.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub enum AgentTuiEvent {
129    /// User or assistant message.
130    Message {
131        /// Normalized lowercase role.
132        role: String,
133        /// Visible message content.
134        content: String,
135    },
136    /// Tool invocation shown by the client.
137    ToolCall {
138        /// Tool name.
139        name: String,
140        /// Visible tool input.
141        input: String,
142    },
143}
144
145/// Terminal capture and normalized events for one agent.
146#[derive(Debug, Clone)]
147pub struct AgentTuiCapture {
148    /// Agent client name.
149    pub tool: String,
150    /// Lossless terminal capture and replay data.
151    pub terminal: TerminalCapture,
152    /// Stable semantic events extracted from the unrolled transcript.
153    pub events: Vec<AgentTuiEvent>,
154}
155
156/// Error while preparing or capturing an interactive agent terminal.
157#[derive(Debug, Error)]
158pub enum AgentTuiError {
159    /// Launch options are unsupported or incomplete.
160    #[error("{0}")]
161    Launch(String),
162    /// PTY capture failed.
163    #[error(transparent)]
164    Capture(#[from] TerminalCaptureError),
165}
166
167fn mapped_model(tool: &str, model: &str) -> String {
168    match tool {
169        "claude" => claude::model_arg(model),
170        "codex" => codex::map_model_to_id(model),
171        "opencode" => opencode::map_model_to_id(model),
172        "agent" => agent::map_model_to_id(model),
173        "gemini" => gemini::map_model_to_id(model),
174        "qwen" => qwen::map_model_to_id(model),
175        _ => model.to_string(),
176    }
177}
178
179fn push_model(args: &mut Vec<String>, options: &AgentTuiOptions) {
180    if let Some(model) = &options.model {
181        args.push("--model".into());
182        args.push(mapped_model(&options.tool, model));
183    }
184}
185
186fn claude_args(options: &AgentTuiOptions) -> Vec<String> {
187    let mut args = Vec::new();
188    if options.read_only {
189        args.extend(["--permission-mode".into(), "plan".into()]);
190    } else if options.approve_each {
191        args.extend(["--permission-mode".into(), "default".into()]);
192    } else if !options.skip_default_safety_flags {
193        args.push("--dangerously-skip-permissions".into());
194    }
195    push_model(&mut args, options);
196    if let Some(system_prompt) = &options.system_prompt {
197        args.extend(["--append-system-prompt".into(), system_prompt.clone()]);
198    }
199    if let Some(resume) = &options.resume {
200        args.extend(["--resume".into(), resume.clone()]);
201    }
202    args.push("--ax-screen-reader".into());
203    args
204}
205
206fn codex_args(options: &AgentTuiOptions) -> Vec<String> {
207    let mut args = Vec::new();
208    push_model(&mut args, options);
209    if options.read_only {
210        args.extend([
211            "--sandbox".into(),
212            "read-only".into(),
213            "--ask-for-approval".into(),
214            "never".into(),
215        ]);
216    } else if options.approve_each {
217        args.extend(["--ask-for-approval".into(), "on-request".into()]);
218    } else if !options.skip_default_safety_flags {
219        args.push("--dangerously-bypass-approvals-and-sandbox".into());
220    }
221    args.push("--no-alt-screen".into());
222    if let Some(resume) = &options.resume {
223        args.extend(["resume".into(), resume.clone()]);
224    }
225    args
226}
227
228fn opencode_args(options: &AgentTuiOptions) -> Vec<String> {
229    let mut args = vec!["--mini".into(), "--no-replay".into()];
230    push_model(&mut args, options);
231    if let Some(resume) = &options.resume {
232        args.extend(["--session".into(), resume.clone()]);
233    }
234    if !options.read_only && !options.approve_each && !options.skip_default_safety_flags {
235        args.push("--auto".into());
236    }
237    args
238}
239
240fn agent_args(options: &AgentTuiOptions) -> Vec<String> {
241    let mut args = Vec::new();
242    push_model(&mut args, options);
243    let permission = if options.read_only {
244        Some("readonly")
245    } else if options.plan_only {
246        Some("plan")
247    } else if options.approve_each {
248        Some("ask")
249    } else {
250        None
251    };
252    if let Some(permission) = permission {
253        args.extend(["--permission-mode".into(), permission.into()]);
254    }
255    if let Some(resume) = &options.resume {
256        args.extend(["--resume".into(), resume.clone()]);
257    }
258    args
259}
260
261fn gemini_args(options: &AgentTuiOptions) -> Vec<String> {
262    let mut args = Vec::new();
263    push_model(&mut args, options);
264    if options.read_only {
265        args.extend(["--approval-mode".into(), "plan".into()]);
266    } else if options.approve_each {
267        args.extend(["--approval-mode".into(), "default".into()]);
268    } else if !options.skip_default_safety_flags {
269        args.push("--yolo".into());
270    }
271    if let Some(resume) = &options.resume {
272        args.extend(["--resume".into(), resume.clone()]);
273    }
274    args
275}
276
277fn qwen_args(options: &AgentTuiOptions) -> Vec<String> {
278    let mut args = Vec::new();
279    push_model(&mut args, options);
280    if options.read_only {
281        args.push("--read-only".into());
282    }
283    if let Some(resume) = &options.resume {
284        args.extend(["--resume".into(), resume.clone()]);
285    }
286    args
287}
288
289/// Build a shell-free interactive launch for a supported agent client.
290pub fn build_agent_tui_launch(options: &AgentTuiOptions) -> Result<AgentTuiLaunch, AgentTuiError> {
291    if !SUPPORTED_TOOLS.contains(&options.tool.as_str()) {
292        return Err(AgentTuiError::Launch(format!(
293            "unsupported TUI tool: {}",
294            options.tool
295        )));
296    }
297    if options.working_directory.as_os_str().is_empty() {
298        return Err(AgentTuiError::Launch(
299            "working_directory is required".into(),
300        ));
301    }
302    let generated = match options.tool.as_str() {
303        "claude" => claude_args(options),
304        "codex" => codex_args(options),
305        "opencode" => opencode_args(options),
306        "agent" => agent_args(options),
307        "gemini" => gemini_args(options),
308        "qwen" => qwen_args(options),
309        _ => unreachable!("supported tools were validated"),
310    };
311    let mut args =
312        Vec::with_capacity(options.prefix_args.len() + generated.len() + options.extra_args.len());
313    args.extend(options.prefix_args.clone());
314    args.extend(generated);
315    args.extend(options.extra_args.clone());
316    let mut env = options.extra_env.clone();
317    if options.tool == "opencode" && options.read_only {
318        env.insert(
319            "OPENCODE_PERMISSION".into(),
320            READ_ONLY_OPENCODE_PERMISSION.into(),
321        );
322    }
323    let mut file = options
324        .executable
325        .clone()
326        .unwrap_or_else(|| options.tool.clone());
327    if !options.unset_env.is_empty() {
328        let mut wrapped = Vec::with_capacity(options.unset_env.len() * 2 + args.len() + 1);
329        for name in &options.unset_env {
330            if !crate::tools::shell::is_valid_env_name(name) {
331                return Err(AgentTuiError::Launch(format!(
332                    "invalid environment variable name: {name}"
333                )));
334            }
335            env.remove(name);
336            wrapped.push("-u".to_string());
337            wrapped.push(name.clone());
338        }
339        wrapped.push(file);
340        wrapped.extend(args);
341        file = "env".into();
342        args = wrapped;
343    }
344    Ok(AgentTuiLaunch {
345        file,
346        args,
347        cwd: Some(options.working_directory.clone()),
348        env,
349    })
350}
351
352fn strip_marker(line: &str) -> &str {
353    line.trim_start_matches(|character: char| {
354        matches!(character, '│' | '┃' | '>' | '›' | '❯' | '•' | '*') || character.is_whitespace()
355    })
356}
357
358/// Extract stable message and tool-call events without removing repeated states.
359pub fn normalize_tui_transcript(transcript: &str) -> Vec<AgentTuiEvent> {
360    transcript
361        .lines()
362        .filter_map(|raw_line| {
363            let line = strip_marker(raw_line.trim());
364            let (kind, content) = line.split_once(':')?;
365            if kind.eq_ignore_ascii_case("user") || kind.eq_ignore_ascii_case("assistant") {
366                return Some(AgentTuiEvent::Message {
367                    role: kind.to_ascii_lowercase(),
368                    content: content.trim().into(),
369                });
370            }
371            if kind.eq_ignore_ascii_case("tool_call") || kind.eq_ignore_ascii_case("tool call") {
372                let (name, input) = content
373                    .trim()
374                    .split_once(char::is_whitespace)
375                    .unwrap_or_else(|| (content.trim(), ""));
376                return Some(AgentTuiEvent::ToolCall {
377                    name: name.into(),
378                    input: input.trim().into(),
379                });
380            }
381            None
382        })
383        .collect()
384}
385
386/// Capture and drive an agent's real interactive terminal interface.
387pub fn capture_agent_tui(options: AgentTuiOptions) -> Result<AgentTuiCapture, AgentTuiError> {
388    let launch = build_agent_tui_launch(&options)?;
389    let combined_prompt = match (&options.system_prompt, &options.prompt) {
390        (Some(system), Some(prompt)) if options.tool != "claude" => {
391            Some(format!("{system}\n\n{prompt}"))
392        }
393        (Some(system), None) if options.tool != "claude" => Some(system.clone()),
394        (_, prompt) => prompt.clone(),
395    };
396    let mut interactions =
397        Vec::with_capacity(options.interactions.len() + usize::from(combined_prompt.is_some()));
398    if let Some(prompt) = combined_prompt {
399        interactions.push(TerminalInteraction {
400            after: options.prompt_after.clone(),
401            text: Some(prompt),
402            key: Some(options.prompt_key.clone()),
403            ..TerminalInteraction::default()
404        });
405    }
406    interactions.extend(options.interactions.clone());
407    let terminal = capture_terminal(TerminalCaptureOptions {
408        file: launch.file,
409        args: launch.args,
410        cwd: launch.cwd,
411        env: launch.env,
412        cols: options.cols,
413        rows: options.rows,
414        settle_duration: options.settle_duration,
415        interactions,
416        stop_marker: options.stop_marker,
417        stop_marker_grace: options.stop_marker_grace,
418        timeout: Some(options.timeout),
419        artifact_directory: options.artifact_directory,
420        frames_on_write: options.frames_on_write,
421        recording: options.recording,
422    })?;
423    Ok(AgentTuiCapture {
424        tool: options.tool,
425        events: normalize_tui_transcript(&terminal.transcript),
426        terminal,
427    })
428}