Skip to main content

agent_commander/
command_builder.rs

1//! Build command strings for different agent tools
2
3use crate::tools::shell::escape_arg;
4// The same quoting rules command-stream audits for `bash -c` strings.
5use crate::tool_overrides::ToolOverrides;
6use crate::tools::launch_options::{
7    check_launch_options_against, launch_capabilities, LaunchOptions,
8};
9use crate::tools::{
10    agent::{self, AgentBuildOptions},
11    claude::{self, ClaudeBuildOptions},
12    codex::{self, CodexBuildOptions},
13    gemini::{self, GeminiBuildOptions},
14    opencode::{self, OpencodeBuildOptions},
15    qwen::{self, QwenBuildOptions},
16};
17use command_stream::quote::{escape_for_double_quotes, escape_for_single_quotes};
18
19/// Agent command build options
20#[derive(Debug, Clone, Default)]
21pub struct AgentCommandOptions {
22    pub tool: String,
23    pub working_directory: String,
24    pub prompt: Option<String>,
25    pub prompt_file: Option<String>,
26    pub system_prompt: Option<String>,
27    pub append_system_prompt: Option<String>,
28    pub model: Option<String>,
29    pub fallback_model: Option<String>,
30    pub json: bool,
31    pub verbose: bool,
32    pub replay_user_messages: bool,
33    pub resume: Option<String>,
34    pub session_id: Option<String>,
35    pub fork_session: bool,
36    pub read_only: bool,
37    pub plan_only: bool,
38    /// Approve each mutating command (`--permission-mode ask` / `--approve-each`)
39    pub approve_each: bool,
40    /// Prompt and follow-ups arrive as stream-json stdin frames (live input;
41    /// claude, qwen and agent)
42    pub stream_input: bool,
43    pub executable: Option<String>,
44    pub extra_args: Vec<String>,
45    pub extra_env: Vec<(String, String)>,
46    /// Variables removed from the inherited environment (`env -u`)
47    pub unset_env: Vec<String>,
48    pub skip_default_safety_flags: bool,
49    pub isolation: String,
50    pub screen_name: Option<String>,
51    pub container_name: Option<String>,
52    pub detached: bool,
53    /// Shared launch options (reasoning effort, MCP servers, extra directories)
54    pub launch: LaunchOptions,
55    /// Caller replacements for the command builder or capability flags
56    pub overrides: ToolOverrides,
57}
58
59/// Check whether a tool has an enforceable native read-only/planning mode.
60pub fn supports_read_only(tool: &str) -> bool {
61    matches!(
62        tool,
63        "claude" | "codex" | "opencode" | "gemini" | "qwen" | "agent"
64    )
65}
66
67/// Build the standard error for tools without enforceable read-only mode.
68pub fn read_only_unsupported_error(tool: &str) -> String {
69    format!(
70        "Tool \"{}\" does not support enforceable read-only mode. Choose one of: claude, codex, opencode, gemini, qwen, agent; or run without --read-only.",
71        tool
72    )
73}
74
75/// Build the base tool command (generic)
76fn build_tool_command(tool: &str, prompt: Option<&str>, system_prompt: Option<&str>) -> String {
77    let mut command = tool.to_string();
78
79    if let Some(p) = prompt.filter(|p| !p.is_empty()) {
80        command.push_str(&format!(" --prompt {}", escape_arg(p)));
81    }
82
83    if let Some(sp) = system_prompt.filter(|sp| !sp.is_empty()) {
84        command.push_str(&format!(" --system-prompt {}", escape_arg(sp)));
85    }
86
87    command
88}
89
90/// Build screen isolation command
91fn build_screen_command(base_command: &str, screen_name: Option<&str>, detached: bool) -> String {
92    let session_name = screen_name.map(|s| s.to_string()).unwrap_or_else(|| {
93        format!(
94            "agent-{}",
95            std::time::SystemTime::now()
96                .duration_since(std::time::UNIX_EPOCH)
97                .unwrap()
98                .as_millis()
99        )
100    });
101
102    if detached {
103        // Start detached screen session
104        format!(
105            "screen -dmS \"{}\" bash -c '{}'",
106            session_name,
107            escape_for_single_quotes(base_command)
108        )
109    } else {
110        // Start attached screen session
111        format!(
112            "screen -S \"{}\" bash -c '{}'",
113            session_name,
114            escape_for_single_quotes(base_command)
115        )
116    }
117}
118
119/// Build docker isolation command
120fn build_docker_command(
121    base_command: &str,
122    container_name: Option<&str>,
123    working_directory: &str,
124    detached: bool,
125    env_names: &[String],
126) -> String {
127    let name = container_name.map(|s| s.to_string()).unwrap_or_else(|| {
128        format!(
129            "agent-{}",
130            std::time::SystemTime::now()
131                .duration_since(std::time::UNIX_EPOCH)
132                .unwrap()
133                .as_millis()
134        )
135    });
136
137    let mut command = "docker run".to_string();
138
139    if detached {
140        command.push_str(" -d");
141    } else {
142        command.push_str(" -it");
143    }
144
145    command.push_str(&format!(" --name \"{}\"", name));
146    command.push_str(&format!(
147        " -v \"{}:{}\"",
148        working_directory, working_directory
149    ));
150    command.push_str(&format!(" -w \"{}\"", working_directory));
151    // `-e NAME` copies the value from the docker client's environment, so it
152    // never appears on the command line (issue #60).
153    for name in env_names {
154        command.push_str(&format!(" -e {name}"));
155    }
156    command.push_str(" node:18-slim");
157    command.push_str(&format!(
158        " bash -c '{}'",
159        escape_for_single_quotes(base_command)
160    ));
161
162    command
163}
164
165/// Names forwarded into a docker container: `extra_env` plus the read-only
166/// OpenCode permission. Invalid names panic, as in `build_command_head`.
167fn docker_env_names(options: &AgentCommandOptions) -> Vec<String> {
168    let mut names: Vec<String> = Vec::new();
169    for (name, _) in &options.extra_env {
170        assert!(
171            crate::tools::shell::is_valid_env_name(name),
172            "invalid environment variable name: {name}"
173        );
174        if !names.contains(name) {
175            names.push(name.clone());
176        }
177    }
178    names
179}
180
181/// Build the command for executing an agent
182///
183/// # Arguments
184/// * `options` - Command options
185///
186/// # Returns
187/// The command string
188pub fn build_agent_command(options: &AgentCommandOptions) -> String {
189    // A planning request implies a read-only restriction for tools that do not
190    // distinguish the two modes.
191    let read_only_requested = options.read_only || options.plan_only;
192
193    assert!(
194        !(read_only_requested && !supports_read_only(&options.tool)),
195        "{}",
196        read_only_unsupported_error(&options.tool)
197    );
198
199    // Per-command approval ("ask" mode) is only enforceable on tools that expose
200    // a drivable JSON permission request/response protocol (agent, claude). Fail
201    // clearly for the rest, mirroring the --read-only gate above.
202    assert!(
203        !(options.approve_each && !crate::permissions::supports_ask(&options.tool)),
204        "{}",
205        crate::permissions::ask_unsupported_error(&options.tool)
206    );
207
208    let capabilities = options
209        .overrides
210        .launch_capabilities
211        .unwrap_or_else(|| launch_capabilities(&options.tool));
212    if let Err(error) = check_launch_options_against(&options.tool, &options.launch, &capabilities)
213    {
214        panic!("{error}");
215    }
216
217    // A caller's builder replaces the tool-specific one (issue #57).
218    let base_command = match &options.overrides.build_command {
219        Some(build) => build(options),
220        None => build_base_command(options),
221    };
222
223    // Wrap in bash -c with working directory change
224    let mut full_command = format!(
225        "bash -c \"cd {} && {}\"",
226        escape_for_double_quotes(&escape_arg(&options.working_directory)),
227        escape_for_double_quotes(&base_command)
228    );
229
230    // Apply isolation wrapper
231    match options.isolation.as_str() {
232        "screen" => {
233            full_command = build_screen_command(
234                &full_command,
235                options.screen_name.as_deref(),
236                options.detached,
237            );
238        }
239        "docker" => {
240            full_command = build_docker_command(
241                &full_command,
242                options.container_name.as_deref(),
243                &options.working_directory,
244                options.detached,
245                &docker_env_names(options),
246            );
247        }
248        _ => {}
249    }
250
251    full_command
252}
253
254/// Build the native tool command without the working-directory and isolation
255/// wrappers. A `ToolOverrides::build_command` can call it and extend the result.
256pub fn build_base_command(options: &AgentCommandOptions) -> String {
257    // A planning request implies a read-only restriction for tools that do not
258    // distinguish the two modes.
259    let read_only_requested = options.read_only || options.plan_only;
260    match options.tool.as_str() {
261        "claude" => claude::build_command(&ClaudeBuildOptions {
262            prompt: options.prompt.clone(),
263            prompt_file: options.prompt_file.clone(),
264            system_prompt: options.system_prompt.clone(),
265            append_system_prompt: options.append_system_prompt.clone(),
266            model: options.model.clone(),
267            fallback_model: options.fallback_model.clone(),
268            json: options.json,
269            json_input: options.stream_input,
270            verbose: options.verbose,
271            replay_user_messages: options.replay_user_messages,
272            resume: options.resume.clone(),
273            session_id: options.session_id.clone(),
274            fork_session: options.fork_session,
275            print: false,
276            read_only: read_only_requested,
277            approve_each: options.approve_each,
278            executable: options.executable.clone(),
279            extra_env: options.extra_env.clone(),
280            unset_env: options.unset_env.clone(),
281            extra_args: options.extra_args.clone(),
282            skip_default_safety_flags: options.skip_default_safety_flags,
283            permission_mode: None,
284            stream_input: options.stream_input,
285            launch: options.launch.clone(),
286        }),
287        "codex" => codex::build_command(&CodexBuildOptions {
288            prompt: options.prompt.clone(),
289            prompt_file: options.prompt_file.clone(),
290            system_prompt: options.system_prompt.clone(),
291            model: options.model.clone(),
292            json: options.json,
293            resume: options.resume.clone(),
294            read_only: read_only_requested,
295            executable: options.executable.clone(),
296            extra_env: options.extra_env.clone(),
297            unset_env: options.unset_env.clone(),
298            extra_args: options.extra_args.clone(),
299            skip_default_safety_flags: options.skip_default_safety_flags,
300            sandbox_mode: None,
301            approval_mode: None,
302            launch: options.launch.clone(),
303        }),
304        "opencode" => opencode::build_command(&OpencodeBuildOptions {
305            prompt: options.prompt.clone(),
306            prompt_file: options.prompt_file.clone(),
307            system_prompt: options.system_prompt.clone(),
308            model: options.model.clone(),
309            json: options.json,
310            resume: options.resume.clone(),
311            read_only: read_only_requested,
312            executable: options.executable.clone(),
313            extra_env: options.extra_env.clone(),
314            unset_env: options.unset_env.clone(),
315            extra_args: options.extra_args.clone(),
316            launch: options.launch.clone(),
317        }),
318        "agent" => agent::build_command(&AgentBuildOptions {
319            resume: options.resume.clone(),
320            prompt: options.prompt.clone(),
321            prompt_file: options.prompt_file.clone(),
322            system_prompt: options.system_prompt.clone(),
323            model: options.model.clone(),
324            temperature: options.launch.temperature,
325            compact_json: false,
326            use_existing_claude_oauth: false,
327            read_only: read_only_requested,
328            plan_only: options.plan_only,
329            approve_each: options.approve_each,
330            permission_mode: None,
331            permission: None,
332            stream_input: options.stream_input,
333            json_input: options.stream_input,
334            executable: options.executable.clone(),
335            extra_env: options.extra_env.clone(),
336            unset_env: options.unset_env.clone(),
337            extra_args: options.extra_args.clone(),
338        }),
339        "gemini" => {
340            let options = GeminiBuildOptions {
341                resume: options.resume.clone(),
342                prompt: options.prompt.clone(),
343                prompt_file: options.prompt_file.clone(),
344                system_prompt: options.system_prompt.clone(),
345                model: options.model.clone(),
346                json: options.json,
347                read_only: read_only_requested,
348                executable: options.executable.clone(),
349                extra_env: options.extra_env.clone(),
350                unset_env: options.unset_env.clone(),
351                extra_args: options.extra_args.clone(),
352                skip_default_safety_flags: options.skip_default_safety_flags,
353                launch: options.launch.clone(),
354                ..GeminiBuildOptions::new()
355            };
356            gemini::build_command(&options)
357        }
358        "qwen" => {
359            let options = QwenBuildOptions {
360                prompt: options.prompt.clone(),
361                prompt_file: options.prompt_file.clone(),
362                system_prompt: options.system_prompt.clone(),
363                model: options.model.clone(),
364                json: options.json,
365                resume: options.resume.clone(),
366                read_only: read_only_requested,
367                executable: options.executable.clone(),
368                extra_env: options.extra_env.clone(),
369                unset_env: options.unset_env.clone(),
370                extra_args: options.extra_args.clone(),
371                skip_default_safety_flags: options.skip_default_safety_flags,
372                launch: options.launch.clone(),
373                json_input: options.stream_input,
374                stream_input: options.stream_input,
375                ..QwenBuildOptions::new()
376            };
377            qwen::build_command(&options)
378        }
379        // Unknown tool, use generic command builder
380        _ => build_tool_command(
381            &options.tool,
382            options.prompt.as_deref(),
383            options.system_prompt.as_deref(),
384        ),
385    }
386}
387
388/// Build stop command for screen sessions
389///
390/// # Arguments
391/// * `screen_name` - Screen session name
392///
393/// # Returns
394/// Stop command
395pub fn build_screen_stop_command(screen_name: &str) -> String {
396    format!("screen -S \"{}\" -X quit", screen_name)
397}
398
399/// Build stop command for docker containers
400///
401/// # Arguments
402/// * `container_name` - Container name
403///
404/// # Returns
405/// Stop command
406pub fn build_docker_stop_command(container_name: &str) -> String {
407    format!(
408        "docker stop \"{}\" && docker rm \"{}\"",
409        container_name, container_name
410    )
411}
412
413/// Build stdin piping command for tools that accept input via stdin
414///
415/// # Arguments
416/// * `input` - Input to pipe
417/// * `command` - Command to pipe to
418///
419/// # Returns
420/// Piped command
421pub fn build_piped_command(input: &str, command: &str) -> String {
422    let escaped_input = escape_for_single_quotes(input);
423    format!("printf '%s' '{}' | {}", escaped_input, command)
424}
425
426#[cfg(test)]
427mod tests {
428    use super::*;
429
430    #[test]
431    fn test_build_agent_command_basic_claude() {
432        let options = AgentCommandOptions {
433            tool: "claude".to_string(),
434            working_directory: "/tmp/test".to_string(),
435            prompt: Some("Hello".to_string()),
436            isolation: "none".to_string(),
437            ..Default::default()
438        };
439
440        let command = build_agent_command(&options);
441        assert!(command.contains("bash -c"));
442        assert!(command.contains("cd"));
443        assert!(command.contains("/tmp/test"));
444        assert!(command.contains("claude"));
445        assert!(command.contains("-p"));
446        assert!(command.contains("Hello"));
447    }
448
449    #[test]
450    fn test_build_agent_command_with_system_prompt() {
451        let options = AgentCommandOptions {
452            tool: "claude".to_string(),
453            working_directory: "/tmp/test".to_string(),
454            prompt: Some("Hello".to_string()),
455            system_prompt: Some("You are helpful".to_string()),
456            isolation: "none".to_string(),
457            ..Default::default()
458        };
459
460        let command = build_agent_command(&options);
461        assert!(command.contains("-p"));
462        assert!(command.contains("--system-prompt"));
463        assert!(command.contains("You are helpful"));
464    }
465
466    #[test]
467    fn test_build_agent_command_claude_with_fallback_model() {
468        let options = AgentCommandOptions {
469            tool: "claude".to_string(),
470            working_directory: "/tmp/test".to_string(),
471            model: Some("opus".to_string()),
472            fallback_model: Some("sonnet".to_string()),
473            isolation: "none".to_string(),
474            ..Default::default()
475        };
476
477        let command = build_agent_command(&options);
478        assert!(command.contains("--model"));
479        assert!(command.contains("--model opus"));
480        assert!(command.contains("--fallback-model"));
481        assert!(command.contains("--fallback-model sonnet"));
482    }
483
484    #[test]
485    fn test_build_agent_command_claude_with_append_system_prompt() {
486        let options = AgentCommandOptions {
487            tool: "claude".to_string(),
488            working_directory: "/tmp/test".to_string(),
489            append_system_prompt: Some("Extra instructions".to_string()),
490            isolation: "none".to_string(),
491            ..Default::default()
492        };
493
494        let command = build_agent_command(&options);
495        assert!(command.contains("--append-system-prompt"));
496        assert!(command.contains("Extra instructions"));
497    }
498
499    #[test]
500    fn test_build_agent_command_claude_with_session_management() {
501        let options = AgentCommandOptions {
502            tool: "claude".to_string(),
503            working_directory: "/tmp/test".to_string(),
504            resume: Some("abc123".to_string()),
505            session_id: Some("123e4567-e89b-12d3-a456-426614174000".to_string()),
506            fork_session: true,
507            isolation: "none".to_string(),
508            ..Default::default()
509        };
510
511        let command = build_agent_command(&options);
512        assert!(command.contains("--resume"));
513        assert!(command.contains("abc123"));
514        assert!(command.contains("--session-id"));
515        assert!(command.contains("123e4567-e89b-12d3-a456-426614174000"));
516        assert!(command.contains("--fork-session"));
517    }
518
519    #[test]
520    fn test_build_agent_command_claude_with_verbose_streaming() {
521        let options = AgentCommandOptions {
522            tool: "claude".to_string(),
523            working_directory: "/tmp/test".to_string(),
524            verbose: true,
525            replay_user_messages: true,
526            isolation: "none".to_string(),
527            ..Default::default()
528        };
529
530        let command = build_agent_command(&options);
531        assert!(command.contains("--verbose"));
532        assert!(command.contains("--replay-user-messages"));
533    }
534
535    #[test]
536    fn test_build_agent_command_claude_raw_passthrough() {
537        let options = AgentCommandOptions {
538            tool: "claude".to_string(),
539            working_directory: "/tmp/test".to_string(),
540            prompt: Some("Hello".to_string()),
541            executable: Some("/opt/Claude Code/bin/claude".to_string()),
542            extra_env: vec![
543                (
544                    "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC".to_string(),
545                    "1".to_string(),
546                ),
547                ("MCP_TIMEOUT".to_string(), "10000".to_string()),
548            ],
549            extra_args: vec![
550                "--mcp-config".to_string(),
551                "/tmp/mcp config.json".to_string(),
552                "--permission-mode".to_string(),
553                "default".to_string(),
554            ],
555            skip_default_safety_flags: true,
556            isolation: "none".to_string(),
557            ..Default::default()
558        };
559
560        let command = build_agent_command(&options);
561        // Environment values travel through spawn, not argv (issue #60).
562        assert!(!command.contains("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"));
563        assert!(!command.contains("MCP_TIMEOUT"));
564        assert!(command.contains("/opt/Claude Code/bin/claude"));
565        assert!(command.contains("--mcp-config"));
566        assert!(command.contains("/tmp/mcp config.json"));
567        assert!(command.contains("--permission-mode"));
568        assert!(command.contains("default"));
569        assert!(!command.contains("--dangerously-skip-permissions"));
570    }
571
572    #[test]
573    fn test_docker_forwards_extra_env_by_name_only() {
574        let options = AgentCommandOptions {
575            tool: "claude".to_string(),
576            working_directory: "/tmp/test".to_string(),
577            prompt: Some("Hello".to_string()),
578            extra_env: vec![("API_TOKEN".to_string(), "sk-secret".to_string())],
579            isolation: "docker".to_string(),
580            container_name: Some("c".to_string()),
581            ..Default::default()
582        };
583        let command = build_agent_command(&options);
584        assert!(command.contains(" -e API_TOKEN "));
585        assert!(!command.contains("sk-secret"));
586    }
587
588    #[test]
589    fn test_claude_prompt_and_schema_files_replace_inline_values() {
590        let options = AgentCommandOptions {
591            tool: "claude".to_string(),
592            working_directory: "/tmp/test".to_string(),
593            prompt: Some("Hello".to_string()),
594            system_prompt: Some("PRIVATE-SYSTEM".to_string()),
595            append_system_prompt: Some("PRIVATE-APPEND".to_string()),
596            launch: crate::tools::launch_options::LaunchOptions {
597                json_schema: Some(r#"{"type":"object","secretField":1}"#.to_string()),
598                json_schema_file: Some("/tmp/d/schema.json".to_string()),
599                system_prompt_file: Some("/tmp/d/system-prompt.txt".to_string()),
600                append_system_prompt_file: Some("/tmp/d/append.txt".to_string()),
601                ..Default::default()
602            },
603            ..Default::default()
604        };
605        let command = build_agent_command(&options);
606        assert!(!command.contains("PRIVATE"));
607        assert!(!command.contains("secretField"));
608        assert!(command.contains("--system-prompt-file /tmp/d/system-prompt.txt"));
609        assert!(command.contains("--append-system-prompt-file /tmp/d/append.txt"));
610        assert!(
611            command.contains("--json-schema \\\"\\$(cat /tmp/d/schema.json)\\\""),
612            "{command}"
613        );
614    }
615
616    #[test]
617    fn test_build_agent_command_qwen_raw_passthrough() {
618        let options = AgentCommandOptions {
619            tool: "qwen".to_string(),
620            working_directory: "/tmp/test".to_string(),
621            prompt_file: Some("/tmp/prompt.txt".to_string()),
622            executable: Some("/opt/qwen code/qwen".to_string()),
623            extra_env: vec![("QWEN_HOME".to_string(), "/tmp/qwen home".to_string())],
624            extra_args: vec![
625                "--checkpointing".to_string(),
626                "--approval-mode".to_string(),
627                "default".to_string(),
628            ],
629            skip_default_safety_flags: true,
630            isolation: "none".to_string(),
631            ..Default::default()
632        };
633
634        let command = build_agent_command(&options);
635        assert!(command.contains("cat"));
636        assert!(command.contains("/tmp/prompt.txt"));
637        assert!(!command.contains("QWEN_HOME"));
638        assert!(command.contains("/opt/qwen code/qwen"));
639        assert!(command.contains("--checkpointing"));
640        assert!(command.contains("--approval-mode"));
641        assert!(command.contains("default"));
642        assert!(!command.contains("--yolo"));
643    }
644
645    #[test]
646    fn test_build_agent_command_gemini_raw_passthrough() {
647        let options = AgentCommandOptions {
648            tool: "gemini".to_string(),
649            working_directory: "/tmp/test".to_string(),
650            prompt_file: Some("/tmp/prompt.txt".to_string()),
651            executable: Some("/opt/gemini cli/gemini".to_string()),
652            extra_env: vec![("GEMINI_HOME".to_string(), "/tmp/gemini home".to_string())],
653            extra_args: vec!["--telemetry".to_string(), "false".to_string()],
654            skip_default_safety_flags: true,
655            isolation: "none".to_string(),
656            ..Default::default()
657        };
658
659        let command = build_agent_command(&options);
660        assert!(command.contains("cat"));
661        assert!(command.contains("/tmp/prompt.txt"));
662        assert!(!command.contains("GEMINI_HOME"));
663        assert!(command.contains("/opt/gemini cli/gemini"));
664        assert!(command.contains("--telemetry"));
665        assert!(command.contains("false"));
666        assert!(!command.contains("--yolo"));
667    }
668
669    #[test]
670    fn test_build_agent_command_unknown_tool() {
671        let options = AgentCommandOptions {
672            tool: "unknown-tool".to_string(),
673            working_directory: "/tmp/test".to_string(),
674            prompt: Some("Hello".to_string()),
675            isolation: "none".to_string(),
676            ..Default::default()
677        };
678
679        let command = build_agent_command(&options);
680        assert!(command.contains("bash -c"));
681        assert!(command.contains("unknown-tool"));
682        assert!(command.contains("--prompt"));
683    }
684
685    #[test]
686    fn test_build_agent_command_screen_isolation() {
687        let options = AgentCommandOptions {
688            tool: "claude".to_string(),
689            working_directory: "/tmp/test".to_string(),
690            isolation: "screen".to_string(),
691            screen_name: Some("my-session".to_string()),
692            detached: true,
693            ..Default::default()
694        };
695
696        let command = build_agent_command(&options);
697        assert!(command.contains("screen"));
698        assert!(command.contains("-dmS"));
699        assert!(command.contains("my-session"));
700    }
701
702    #[test]
703    fn test_build_agent_command_docker_isolation() {
704        let options = AgentCommandOptions {
705            tool: "claude".to_string(),
706            working_directory: "/tmp/test".to_string(),
707            isolation: "docker".to_string(),
708            container_name: Some("my-container".to_string()),
709            detached: true,
710            ..Default::default()
711        };
712
713        let command = build_agent_command(&options);
714        assert!(command.contains("docker run"));
715        assert!(command.contains("-d"));
716        assert!(command.contains("--name \"my-container\""));
717        assert!(command.contains("-v \"/tmp/test:/tmp/test\""));
718    }
719
720    #[test]
721    fn test_build_agent_command_with_model() {
722        let options = AgentCommandOptions {
723            tool: "claude".to_string(),
724            working_directory: "/tmp/test".to_string(),
725            model: Some("opus".to_string()),
726            isolation: "none".to_string(),
727            ..Default::default()
728        };
729
730        let command = build_agent_command(&options);
731        assert!(command.contains("--model"));
732        assert!(command.contains("--model opus"));
733    }
734
735    #[test]
736    fn test_build_agent_command_codex() {
737        let options = AgentCommandOptions {
738            tool: "codex".to_string(),
739            working_directory: "/tmp/test".to_string(),
740            prompt: Some("Hello".to_string()),
741            json: true,
742            isolation: "none".to_string(),
743            ..Default::default()
744        };
745
746        let command = build_agent_command(&options);
747        assert!(command.contains("codex"));
748        assert!(command.contains("exec"));
749        assert!(command.contains("--json"));
750    }
751
752    #[test]
753    fn test_build_agent_command_codex_prompt_file() {
754        let inline_prompt = "Secret prompt with 'quotes', $HOME, and `pwd`";
755        let options = AgentCommandOptions {
756            tool: "codex".to_string(),
757            working_directory: "/tmp/test".to_string(),
758            prompt: Some(inline_prompt.to_string()),
759            system_prompt: Some("System instructions".to_string()),
760            prompt_file: Some("/tmp/agent prompt.txt".to_string()),
761            json: true,
762            isolation: "none".to_string(),
763            ..Default::default()
764        };
765
766        let command = build_agent_command(&options);
767        assert!(command.contains("cat"));
768        assert!(command.contains("/tmp/agent prompt.txt"));
769        assert!(command.contains("codex"));
770        assert!(!command.contains(inline_prompt));
771        assert!(!command.contains("System instructions"));
772    }
773
774    #[test]
775    fn test_build_agent_command_claude_prompt_file() {
776        let inline_prompt = "Secret prompt with 'quotes', $HOME, and `pwd`";
777        let options = AgentCommandOptions {
778            tool: "claude".to_string(),
779            working_directory: "/tmp/test".to_string(),
780            prompt: Some(inline_prompt.to_string()),
781            system_prompt: Some("You are helpful".to_string()),
782            prompt_file: Some("/tmp/agent prompt.txt".to_string()),
783            isolation: "none".to_string(),
784            ..Default::default()
785        };
786
787        let command = build_agent_command(&options);
788        assert!(command.contains("cat"));
789        assert!(command.contains("/tmp/agent prompt.txt"));
790        assert!(command.contains("claude"));
791        assert!(command.contains("--system-prompt"));
792        assert!(command.contains("You are helpful"));
793        assert!(!command.contains(inline_prompt));
794    }
795
796    #[test]
797    fn test_build_agent_command_qwen_prompt_file() {
798        let inline_prompt = "Secret prompt with 'quotes', $HOME, and `pwd`";
799        let options = AgentCommandOptions {
800            tool: "qwen".to_string(),
801            working_directory: "/tmp/test".to_string(),
802            prompt: Some(inline_prompt.to_string()),
803            system_prompt: Some("System instructions".to_string()),
804            prompt_file: Some("/tmp/agent prompt.txt".to_string()),
805            isolation: "none".to_string(),
806            ..Default::default()
807        };
808
809        let command = build_agent_command(&options);
810        assert!(command.contains("cat"));
811        assert!(command.contains("/tmp/agent prompt.txt"));
812        assert!(command.contains("qwen"));
813        assert!(!command.contains(inline_prompt));
814        assert!(!command.contains("System instructions"));
815    }
816
817    #[test]
818    fn test_build_agent_command_gemini_prompt_file() {
819        let inline_prompt = "Secret prompt with 'quotes', $HOME, and `pwd`";
820        let options = AgentCommandOptions {
821            tool: "gemini".to_string(),
822            working_directory: "/tmp/test".to_string(),
823            prompt: Some(inline_prompt.to_string()),
824            system_prompt: Some("System instructions".to_string()),
825            prompt_file: Some("/tmp/agent prompt.txt".to_string()),
826            isolation: "none".to_string(),
827            ..Default::default()
828        };
829
830        let command = build_agent_command(&options);
831        assert!(command.contains("cat"));
832        assert!(command.contains("/tmp/agent prompt.txt"));
833        assert!(command.contains("gemini"));
834        assert!(!command.contains(inline_prompt));
835        assert!(!command.contains("System instructions"));
836    }
837
838    #[test]
839    fn test_build_agent_command_opencode() {
840        let options = AgentCommandOptions {
841            tool: "opencode".to_string(),
842            working_directory: "/tmp/test".to_string(),
843            prompt: Some("Hello".to_string()),
844            json: true,
845            isolation: "none".to_string(),
846            ..Default::default()
847        };
848
849        let command = build_agent_command(&options);
850        assert!(command.contains("opencode"));
851        assert!(command.contains("run"));
852        assert!(command.contains("--format"));
853    }
854
855    #[test]
856    fn test_build_agent_command_agent_tool() {
857        let options = AgentCommandOptions {
858            tool: "agent".to_string(),
859            working_directory: "/tmp/test".to_string(),
860            model: Some("grok".to_string()),
861            isolation: "none".to_string(),
862            ..Default::default()
863        };
864
865        let command = build_agent_command(&options);
866        assert!(command.contains("agent"));
867        assert!(command.contains("--model"));
868        assert!(command.contains("opencode/grok-code"));
869    }
870
871    #[test]
872    fn test_build_screen_stop_command() {
873        let command = build_screen_stop_command("my-session");
874        assert!(command.contains("screen"));
875        assert!(command.contains("-S \"my-session\""));
876        assert!(command.contains("-X quit"));
877    }
878
879    #[test]
880    fn test_build_docker_stop_command() {
881        let command = build_docker_stop_command("my-container");
882        assert!(command.contains("docker stop \"my-container\""));
883        assert!(command.contains("docker rm \"my-container\""));
884    }
885
886    #[test]
887    fn test_build_piped_command_basic() {
888        let command = build_piped_command("Hello World", "mycommand --flag");
889        assert!(command.contains("printf '%s'"));
890        assert!(command.contains("Hello World"));
891        assert!(command.contains("mycommand --flag"));
892    }
893
894    #[test]
895    fn test_build_piped_command_escapes_quotes() {
896        let command = build_piped_command("It's working", "mycommand");
897        assert!(command.contains("'\\''"));
898    }
899}