agent-commander 0.5.3

A Rust library to control agents enclosed in CLI commands like Anthropic Claude Code CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Interactive terminal launch and capture for supported agent clients.

use crate::tools::{agent, claude, codex, gemini, opencode, qwen};
use command_stream::terminal::{
    capture_terminal, TerminalCapture, TerminalCaptureError, TerminalCaptureOptions,
    TerminalInteraction, TerminalKey,
};
use std::collections::HashMap;
use std::path::PathBuf;
use std::time::Duration;
use thiserror::Error;

const READ_ONLY_OPENCODE_PERMISSION: &str = r#"{"edit":"deny","bash":"deny","task":"deny"}"#;
const SUPPORTED_TOOLS: [&str; 6] = ["claude", "codex", "opencode", "agent", "gemini", "qwen"];

/// Options for launching and driving an agent's real interactive terminal UI.
#[derive(Debug, Clone)]
pub struct AgentTuiOptions {
    /// Agent CLI name.
    pub tool: String,
    /// Directory in which the agent runs.
    pub working_directory: PathBuf,
    /// Override for the agent executable.
    pub executable: Option<String>,
    /// Arguments inserted before the generated agent arguments.
    pub prefix_args: Vec<String>,
    /// Additional agent arguments.
    pub extra_args: Vec<String>,
    /// Additional environment variables.
    pub extra_env: HashMap<String, String>,
    /// Variables removed from the inherited environment; the launch then
    /// runs through `env -u NAME`, because the terminal capture can only add
    /// variables.
    pub unset_env: Vec<String>,
    /// Optional model name or alias.
    pub model: Option<String>,
    /// Initial user prompt.
    pub prompt: Option<String>,
    /// Optional system prompt.
    pub system_prompt: Option<String>,
    /// File holding the Claude system prompt (`--append-system-prompt-file`).
    /// [`capture_agent_tui`] writes `system_prompt` to an owner-only file when
    /// unset, so the text stays off the command line (issue #60).
    pub system_prompt_file: Option<PathBuf>,
    /// Marker that must be observed before sending the initial prompt.
    pub prompt_after: Option<String>,
    /// Control key sent after the initial prompt.
    pub prompt_key: TerminalKey,
    /// Session identifier to resume.
    pub resume: Option<String>,
    /// Request the client's native read-only mode.
    pub read_only: bool,
    /// Request the client's native plan-only mode where distinct.
    pub plan_only: bool,
    /// Request approval for individual operations.
    pub approve_each: bool,
    /// Suppress the default autonomous safety-bypass flags.
    pub skip_default_safety_flags: bool,
    /// Initial terminal width.
    pub cols: u16,
    /// Initial terminal height.
    pub rows: u16,
    /// Time without output before a frame is considered settled.
    pub settle_duration: Duration,
    /// Input, control-key, and resize interactions.
    pub interactions: Vec<TerminalInteraction>,
    /// Marker after which the capture process can be stopped.
    pub stop_marker: Option<String>,
    /// Grace period after the stop marker.
    pub stop_marker_grace: Duration,
    /// Overall capture timeout.
    pub timeout: Duration,
    /// Directory for transcript, frame, cast, and animation artifacts.
    pub artifact_directory: Option<PathBuf>,
    /// Record a frame after every PTY write instead of after each settle
    /// (command-stream 1.9.0 `frames_on_write`).
    pub frames_on_write: bool,
    /// Keep the full recording; `false` keeps only the latest frame and the
    /// last 1 MB of output (command-stream 1.9.0 `recording`).
    pub recording: bool,
}

impl Default for AgentTuiOptions {
    fn default() -> Self {
        Self {
            tool: String::new(),
            working_directory: PathBuf::new(),
            executable: None,
            prefix_args: Vec::new(),
            extra_args: Vec::new(),
            extra_env: HashMap::new(),
            unset_env: Vec::new(),
            model: None,
            prompt: None,
            system_prompt: None,
            system_prompt_file: None,
            prompt_after: None,
            prompt_key: TerminalKey::Enter,
            resume: None,
            read_only: false,
            plan_only: false,
            approve_each: false,
            skip_default_safety_flags: false,
            cols: 80,
            rows: 24,
            settle_duration: Duration::from_millis(35),
            interactions: Vec::new(),
            stop_marker: None,
            stop_marker_grace: Duration::from_millis(250),
            timeout: Duration::from_secs(30),
            artifact_directory: None,
            frames_on_write: false,
            recording: true,
        }
    }
}

/// Executable, argv, cwd, and environment for an interactive agent launch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AgentTuiLaunch {
    /// Executable to launch.
    pub file: String,
    /// Shell-free argument vector.
    pub args: Vec<String>,
    /// Working directory.
    pub cwd: Option<PathBuf>,
    /// Environment overrides.
    pub env: HashMap<String, String>,
}

/// Stable semantic event extracted from an agent TUI transcript.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AgentTuiEvent {
    /// User or assistant message.
    Message {
        /// Normalized lowercase role.
        role: String,
        /// Visible message content.
        content: String,
    },
    /// Tool invocation shown by the client.
    ToolCall {
        /// Tool name.
        name: String,
        /// Visible tool input.
        input: String,
    },
}

/// Terminal capture and normalized events for one agent.
#[derive(Debug, Clone)]
pub struct AgentTuiCapture {
    /// Agent client name.
    pub tool: String,
    /// Lossless terminal capture and replay data.
    pub terminal: TerminalCapture,
    /// Stable semantic events extracted from the unrolled transcript.
    pub events: Vec<AgentTuiEvent>,
}

/// Error while preparing or capturing an interactive agent terminal.
#[derive(Debug, Error)]
pub enum AgentTuiError {
    /// Launch options are unsupported or incomplete.
    #[error("{0}")]
    Launch(String),
    /// PTY capture failed.
    #[error(transparent)]
    Capture(#[from] TerminalCaptureError),
}

fn mapped_model(tool: &str, model: &str) -> String {
    match tool {
        "claude" => claude::model_arg(model),
        "codex" => codex::map_model_to_id(model),
        "opencode" => opencode::map_model_to_id(model),
        "agent" => agent::map_model_to_id(model),
        "gemini" => gemini::map_model_to_id(model),
        "qwen" => qwen::map_model_to_id(model),
        _ => model.to_string(),
    }
}

fn push_model(args: &mut Vec<String>, options: &AgentTuiOptions) {
    if let Some(model) = &options.model {
        args.push("--model".into());
        args.push(mapped_model(&options.tool, model));
    }
}

fn claude_args(options: &AgentTuiOptions) -> Vec<String> {
    let mut args = Vec::new();
    if options.read_only {
        args.extend(["--permission-mode".into(), "plan".into()]);
    } else if options.approve_each {
        args.extend(["--permission-mode".into(), "default".into()]);
    } else if !options.skip_default_safety_flags {
        args.push("--dangerously-skip-permissions".into());
    }
    push_model(&mut args, options);
    if let Some(file) = &options.system_prompt_file {
        args.extend([
            "--append-system-prompt-file".into(),
            file.to_string_lossy().into_owned(),
        ]);
    } else if let Some(system_prompt) = &options.system_prompt {
        args.extend(["--append-system-prompt".into(), system_prompt.clone()]);
    }
    if let Some(resume) = &options.resume {
        args.extend(["--resume".into(), resume.clone()]);
    }
    args.push("--ax-screen-reader".into());
    args
}

fn codex_args(options: &AgentTuiOptions) -> Vec<String> {
    let mut args = Vec::new();
    push_model(&mut args, options);
    if options.read_only {
        args.extend([
            "--sandbox".into(),
            "read-only".into(),
            "--ask-for-approval".into(),
            "never".into(),
        ]);
    } else if options.approve_each {
        args.extend(["--ask-for-approval".into(), "on-request".into()]);
    } else if !options.skip_default_safety_flags {
        args.push("--dangerously-bypass-approvals-and-sandbox".into());
    }
    args.push("--no-alt-screen".into());
    if let Some(resume) = &options.resume {
        args.extend(["resume".into(), resume.clone()]);
    }
    args
}

fn opencode_args(options: &AgentTuiOptions) -> Vec<String> {
    let mut args = vec!["--mini".into(), "--no-replay".into()];
    push_model(&mut args, options);
    if let Some(resume) = &options.resume {
        args.extend(["--session".into(), resume.clone()]);
    }
    if !options.read_only && !options.approve_each && !options.skip_default_safety_flags {
        args.push("--auto".into());
    }
    args
}

fn agent_args(options: &AgentTuiOptions) -> Vec<String> {
    let mut args = Vec::new();
    push_model(&mut args, options);
    let permission = if options.read_only {
        Some("readonly")
    } else if options.plan_only {
        Some("plan")
    } else if options.approve_each {
        Some("ask")
    } else {
        None
    };
    if let Some(permission) = permission {
        args.extend(["--permission-mode".into(), permission.into()]);
    }
    if let Some(resume) = &options.resume {
        args.extend(["--resume".into(), resume.clone()]);
    }
    args
}

fn gemini_args(options: &AgentTuiOptions) -> Vec<String> {
    let mut args = Vec::new();
    push_model(&mut args, options);
    if options.read_only {
        args.extend(["--approval-mode".into(), "plan".into()]);
    } else if options.approve_each {
        args.extend(["--approval-mode".into(), "default".into()]);
    } else if !options.skip_default_safety_flags {
        args.push("--yolo".into());
    }
    if let Some(resume) = &options.resume {
        args.extend(["--resume".into(), resume.clone()]);
    }
    args
}

fn qwen_args(options: &AgentTuiOptions) -> Vec<String> {
    let mut args = Vec::new();
    push_model(&mut args, options);
    if options.read_only {
        args.push("--read-only".into());
    }
    if let Some(resume) = &options.resume {
        args.extend(["--resume".into(), resume.clone()]);
    }
    args
}

/// Build a shell-free interactive launch for a supported agent client.
pub fn build_agent_tui_launch(options: &AgentTuiOptions) -> Result<AgentTuiLaunch, AgentTuiError> {
    if !SUPPORTED_TOOLS.contains(&options.tool.as_str()) {
        return Err(AgentTuiError::Launch(format!(
            "unsupported TUI tool: {}",
            options.tool
        )));
    }
    if options.working_directory.as_os_str().is_empty() {
        return Err(AgentTuiError::Launch(
            "working_directory is required".into(),
        ));
    }
    let generated = match options.tool.as_str() {
        "claude" => claude_args(options),
        "codex" => codex_args(options),
        "opencode" => opencode_args(options),
        "agent" => agent_args(options),
        "gemini" => gemini_args(options),
        "qwen" => qwen_args(options),
        _ => unreachable!("supported tools were validated"),
    };
    let mut args =
        Vec::with_capacity(options.prefix_args.len() + generated.len() + options.extra_args.len());
    args.extend(options.prefix_args.clone());
    args.extend(generated);
    args.extend(options.extra_args.clone());
    let mut env = options.extra_env.clone();
    if options.tool == "opencode" && options.read_only {
        env.insert(
            "OPENCODE_PERMISSION".into(),
            READ_ONLY_OPENCODE_PERMISSION.into(),
        );
    }
    let mut file = options
        .executable
        .clone()
        .unwrap_or_else(|| options.tool.clone());
    if !options.unset_env.is_empty() {
        let mut wrapped = Vec::with_capacity(options.unset_env.len() * 2 + args.len() + 1);
        for name in &options.unset_env {
            if !crate::tools::shell::is_valid_env_name(name) {
                return Err(AgentTuiError::Launch(format!(
                    "invalid environment variable name: {name}"
                )));
            }
            env.remove(name);
            wrapped.push("-u".to_string());
            wrapped.push(name.clone());
        }
        wrapped.push(file);
        wrapped.extend(args);
        file = "env".into();
        args = wrapped;
    }
    Ok(AgentTuiLaunch {
        file,
        args,
        cwd: Some(options.working_directory.clone()),
        env,
    })
}

fn strip_marker(line: &str) -> &str {
    line.trim_start_matches(|character: char| {
        matches!(character, '│' | '┃' | '>' | '›' | '❯' | '•' | '*') || character.is_whitespace()
    })
}

/// Extract stable message and tool-call events without removing repeated states.
pub fn normalize_tui_transcript(transcript: &str) -> Vec<AgentTuiEvent> {
    transcript
        .lines()
        .filter_map(|raw_line| {
            let line = strip_marker(raw_line.trim());
            let (kind, content) = line.split_once(':')?;
            if kind.eq_ignore_ascii_case("user") || kind.eq_ignore_ascii_case("assistant") {
                return Some(AgentTuiEvent::Message {
                    role: kind.to_ascii_lowercase(),
                    content: content.trim().into(),
                });
            }
            if kind.eq_ignore_ascii_case("tool_call") || kind.eq_ignore_ascii_case("tool call") {
                let (name, input) = content
                    .trim()
                    .split_once(char::is_whitespace)
                    .unwrap_or_else(|| (content.trim(), ""));
                return Some(AgentTuiEvent::ToolCall {
                    name: name.into(),
                    input: input.trim().into(),
                });
            }
            None
        })
        .collect()
}

/// Capture and drive an agent's real interactive terminal interface.
pub fn capture_agent_tui(mut options: AgentTuiOptions) -> Result<AgentTuiCapture, AgentTuiError> {
    let mut temp_prompt = None;
    if options.tool == "claude" && options.system_prompt_file.is_none() {
        if let Some(text) = options.system_prompt.as_deref().filter(|t| !t.is_empty()) {
            let file = write_private_temp_file(text)?;
            options.system_prompt_file = Some(file.clone());
            temp_prompt = Some(file);
        }
    }
    let result = run_agent_tui(options);
    if let Some(file) = temp_prompt {
        let _ = std::fs::remove_file(file);
    }
    result
}

/// Write `content` to a new owner-only file in the temp directory.
fn write_private_temp_file(content: &str) -> Result<PathBuf, AgentTuiError> {
    use std::io::Write;
    static SEQUENCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos());
    let sequence = SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let path = std::env::temp_dir().join(format!(
        "agent-commander-tui-{}-{nanos}-{sequence}.txt",
        std::process::id()
    ));
    let mut open = std::fs::OpenOptions::new();
    open.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        open.mode(0o600);
    }
    let mut file = open
        .open(&path)
        .and_then(|mut file| file.write_all(content.as_bytes()).map(|()| file))
        .map_err(|e| AgentTuiError::Launch(format!("system prompt file: {e}")))?;
    file.flush()
        .map_err(|e| AgentTuiError::Launch(format!("system prompt file: {e}")))?;
    Ok(path)
}

fn run_agent_tui(options: AgentTuiOptions) -> Result<AgentTuiCapture, AgentTuiError> {
    let launch = build_agent_tui_launch(&options)?;
    let combined_prompt = match (&options.system_prompt, &options.prompt) {
        (Some(system), Some(prompt)) if options.tool != "claude" => {
            Some(format!("{system}\n\n{prompt}"))
        }
        (Some(system), None) if options.tool != "claude" => Some(system.clone()),
        (_, prompt) => prompt.clone(),
    };
    let mut interactions =
        Vec::with_capacity(options.interactions.len() + usize::from(combined_prompt.is_some()));
    if let Some(prompt) = combined_prompt {
        interactions.push(TerminalInteraction {
            after: options.prompt_after.clone(),
            text: Some(prompt),
            key: Some(options.prompt_key.clone()),
            ..TerminalInteraction::default()
        });
    }
    interactions.extend(options.interactions.clone());
    let terminal = capture_terminal(TerminalCaptureOptions {
        file: launch.file,
        args: launch.args,
        cwd: launch.cwd,
        env: launch.env,
        cols: options.cols,
        rows: options.rows,
        settle_duration: options.settle_duration,
        interactions,
        stop_marker: options.stop_marker,
        stop_marker_grace: options.stop_marker_grace,
        timeout: Some(options.timeout),
        artifact_directory: options.artifact_directory,
        frames_on_write: options.frames_on_write,
        recording: options.recording,
    })?;
    Ok(AgentTuiCapture {
        tool: options.tool,
        events: normalize_tui_transcript(&terminal.transcript),
        terminal,
    })
}