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            compact_json: false,
325            use_existing_claude_oauth: false,
326            read_only: read_only_requested,
327            plan_only: options.plan_only,
328            approve_each: options.approve_each,
329            permission_mode: None,
330            permission: None,
331            stream_input: options.stream_input,
332            json_input: options.stream_input,
333            executable: options.executable.clone(),
334            extra_env: options.extra_env.clone(),
335            unset_env: options.unset_env.clone(),
336            extra_args: options.extra_args.clone(),
337        }),
338        "gemini" => {
339            let options = GeminiBuildOptions {
340                resume: options.resume.clone(),
341                prompt: options.prompt.clone(),
342                prompt_file: options.prompt_file.clone(),
343                system_prompt: options.system_prompt.clone(),
344                model: options.model.clone(),
345                json: options.json,
346                read_only: read_only_requested,
347                executable: options.executable.clone(),
348                extra_env: options.extra_env.clone(),
349                unset_env: options.unset_env.clone(),
350                extra_args: options.extra_args.clone(),
351                skip_default_safety_flags: options.skip_default_safety_flags,
352                launch: options.launch.clone(),
353                ..GeminiBuildOptions::new()
354            };
355            gemini::build_command(&options)
356        }
357        "qwen" => {
358            let options = QwenBuildOptions {
359                prompt: options.prompt.clone(),
360                prompt_file: options.prompt_file.clone(),
361                system_prompt: options.system_prompt.clone(),
362                model: options.model.clone(),
363                json: options.json,
364                resume: options.resume.clone(),
365                read_only: read_only_requested,
366                executable: options.executable.clone(),
367                extra_env: options.extra_env.clone(),
368                unset_env: options.unset_env.clone(),
369                extra_args: options.extra_args.clone(),
370                skip_default_safety_flags: options.skip_default_safety_flags,
371                launch: options.launch.clone(),
372                json_input: options.stream_input,
373                stream_input: options.stream_input,
374                ..QwenBuildOptions::new()
375            };
376            qwen::build_command(&options)
377        }
378        // Unknown tool, use generic command builder
379        _ => build_tool_command(
380            &options.tool,
381            options.prompt.as_deref(),
382            options.system_prompt.as_deref(),
383        ),
384    }
385}
386
387/// Build stop command for screen sessions
388///
389/// # Arguments
390/// * `screen_name` - Screen session name
391///
392/// # Returns
393/// Stop command
394pub fn build_screen_stop_command(screen_name: &str) -> String {
395    format!("screen -S \"{}\" -X quit", screen_name)
396}
397
398/// Build stop command for docker containers
399///
400/// # Arguments
401/// * `container_name` - Container name
402///
403/// # Returns
404/// Stop command
405pub fn build_docker_stop_command(container_name: &str) -> String {
406    format!(
407        "docker stop \"{}\" && docker rm \"{}\"",
408        container_name, container_name
409    )
410}
411
412/// Build stdin piping command for tools that accept input via stdin
413///
414/// # Arguments
415/// * `input` - Input to pipe
416/// * `command` - Command to pipe to
417///
418/// # Returns
419/// Piped command
420pub fn build_piped_command(input: &str, command: &str) -> String {
421    let escaped_input = escape_for_single_quotes(input);
422    format!("printf '%s' '{}' | {}", escaped_input, command)
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428
429    #[test]
430    fn test_build_agent_command_basic_claude() {
431        let options = AgentCommandOptions {
432            tool: "claude".to_string(),
433            working_directory: "/tmp/test".to_string(),
434            prompt: Some("Hello".to_string()),
435            isolation: "none".to_string(),
436            ..Default::default()
437        };
438
439        let command = build_agent_command(&options);
440        assert!(command.contains("bash -c"));
441        assert!(command.contains("cd"));
442        assert!(command.contains("/tmp/test"));
443        assert!(command.contains("claude"));
444        assert!(command.contains("-p"));
445        assert!(command.contains("Hello"));
446    }
447
448    #[test]
449    fn test_build_agent_command_with_system_prompt() {
450        let options = AgentCommandOptions {
451            tool: "claude".to_string(),
452            working_directory: "/tmp/test".to_string(),
453            prompt: Some("Hello".to_string()),
454            system_prompt: Some("You are helpful".to_string()),
455            isolation: "none".to_string(),
456            ..Default::default()
457        };
458
459        let command = build_agent_command(&options);
460        assert!(command.contains("-p"));
461        assert!(command.contains("--system-prompt"));
462        assert!(command.contains("You are helpful"));
463    }
464
465    #[test]
466    fn test_build_agent_command_claude_with_fallback_model() {
467        let options = AgentCommandOptions {
468            tool: "claude".to_string(),
469            working_directory: "/tmp/test".to_string(),
470            model: Some("opus".to_string()),
471            fallback_model: Some("sonnet".to_string()),
472            isolation: "none".to_string(),
473            ..Default::default()
474        };
475
476        let command = build_agent_command(&options);
477        assert!(command.contains("--model"));
478        assert!(command.contains("--model opus"));
479        assert!(command.contains("--fallback-model"));
480        assert!(command.contains("--fallback-model sonnet"));
481    }
482
483    #[test]
484    fn test_build_agent_command_claude_with_append_system_prompt() {
485        let options = AgentCommandOptions {
486            tool: "claude".to_string(),
487            working_directory: "/tmp/test".to_string(),
488            append_system_prompt: Some("Extra instructions".to_string()),
489            isolation: "none".to_string(),
490            ..Default::default()
491        };
492
493        let command = build_agent_command(&options);
494        assert!(command.contains("--append-system-prompt"));
495        assert!(command.contains("Extra instructions"));
496    }
497
498    #[test]
499    fn test_build_agent_command_claude_with_session_management() {
500        let options = AgentCommandOptions {
501            tool: "claude".to_string(),
502            working_directory: "/tmp/test".to_string(),
503            resume: Some("abc123".to_string()),
504            session_id: Some("123e4567-e89b-12d3-a456-426614174000".to_string()),
505            fork_session: true,
506            isolation: "none".to_string(),
507            ..Default::default()
508        };
509
510        let command = build_agent_command(&options);
511        assert!(command.contains("--resume"));
512        assert!(command.contains("abc123"));
513        assert!(command.contains("--session-id"));
514        assert!(command.contains("123e4567-e89b-12d3-a456-426614174000"));
515        assert!(command.contains("--fork-session"));
516    }
517
518    #[test]
519    fn test_build_agent_command_claude_with_verbose_streaming() {
520        let options = AgentCommandOptions {
521            tool: "claude".to_string(),
522            working_directory: "/tmp/test".to_string(),
523            verbose: true,
524            replay_user_messages: true,
525            isolation: "none".to_string(),
526            ..Default::default()
527        };
528
529        let command = build_agent_command(&options);
530        assert!(command.contains("--verbose"));
531        assert!(command.contains("--replay-user-messages"));
532    }
533
534    #[test]
535    fn test_build_agent_command_claude_raw_passthrough() {
536        let options = AgentCommandOptions {
537            tool: "claude".to_string(),
538            working_directory: "/tmp/test".to_string(),
539            prompt: Some("Hello".to_string()),
540            executable: Some("/opt/Claude Code/bin/claude".to_string()),
541            extra_env: vec![
542                (
543                    "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC".to_string(),
544                    "1".to_string(),
545                ),
546                ("MCP_TIMEOUT".to_string(), "10000".to_string()),
547            ],
548            extra_args: vec![
549                "--mcp-config".to_string(),
550                "/tmp/mcp config.json".to_string(),
551                "--permission-mode".to_string(),
552                "default".to_string(),
553            ],
554            skip_default_safety_flags: true,
555            isolation: "none".to_string(),
556            ..Default::default()
557        };
558
559        let command = build_agent_command(&options);
560        // Environment values travel through spawn, not argv (issue #60).
561        assert!(!command.contains("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"));
562        assert!(!command.contains("MCP_TIMEOUT"));
563        assert!(command.contains("/opt/Claude Code/bin/claude"));
564        assert!(command.contains("--mcp-config"));
565        assert!(command.contains("/tmp/mcp config.json"));
566        assert!(command.contains("--permission-mode"));
567        assert!(command.contains("default"));
568        assert!(!command.contains("--dangerously-skip-permissions"));
569    }
570
571    #[test]
572    fn test_docker_forwards_extra_env_by_name_only() {
573        let options = AgentCommandOptions {
574            tool: "claude".to_string(),
575            working_directory: "/tmp/test".to_string(),
576            prompt: Some("Hello".to_string()),
577            extra_env: vec![("API_TOKEN".to_string(), "sk-secret".to_string())],
578            isolation: "docker".to_string(),
579            container_name: Some("c".to_string()),
580            ..Default::default()
581        };
582        let command = build_agent_command(&options);
583        assert!(command.contains(" -e API_TOKEN "));
584        assert!(!command.contains("sk-secret"));
585    }
586
587    #[test]
588    fn test_claude_prompt_and_schema_files_replace_inline_values() {
589        let options = AgentCommandOptions {
590            tool: "claude".to_string(),
591            working_directory: "/tmp/test".to_string(),
592            prompt: Some("Hello".to_string()),
593            system_prompt: Some("PRIVATE-SYSTEM".to_string()),
594            append_system_prompt: Some("PRIVATE-APPEND".to_string()),
595            launch: crate::tools::launch_options::LaunchOptions {
596                json_schema: Some(r#"{"type":"object","secretField":1}"#.to_string()),
597                json_schema_file: Some("/tmp/d/schema.json".to_string()),
598                system_prompt_file: Some("/tmp/d/system-prompt.txt".to_string()),
599                append_system_prompt_file: Some("/tmp/d/append.txt".to_string()),
600                ..Default::default()
601            },
602            ..Default::default()
603        };
604        let command = build_agent_command(&options);
605        assert!(!command.contains("PRIVATE"));
606        assert!(!command.contains("secretField"));
607        assert!(command.contains("--system-prompt-file /tmp/d/system-prompt.txt"));
608        assert!(command.contains("--append-system-prompt-file /tmp/d/append.txt"));
609        assert!(
610            command.contains("--json-schema \\\"\\$(cat /tmp/d/schema.json)\\\""),
611            "{command}"
612        );
613    }
614
615    #[test]
616    fn test_build_agent_command_qwen_raw_passthrough() {
617        let options = AgentCommandOptions {
618            tool: "qwen".to_string(),
619            working_directory: "/tmp/test".to_string(),
620            prompt_file: Some("/tmp/prompt.txt".to_string()),
621            executable: Some("/opt/qwen code/qwen".to_string()),
622            extra_env: vec![("QWEN_HOME".to_string(), "/tmp/qwen home".to_string())],
623            extra_args: vec![
624                "--checkpointing".to_string(),
625                "--approval-mode".to_string(),
626                "default".to_string(),
627            ],
628            skip_default_safety_flags: true,
629            isolation: "none".to_string(),
630            ..Default::default()
631        };
632
633        let command = build_agent_command(&options);
634        assert!(command.contains("cat"));
635        assert!(command.contains("/tmp/prompt.txt"));
636        assert!(!command.contains("QWEN_HOME"));
637        assert!(command.contains("/opt/qwen code/qwen"));
638        assert!(command.contains("--checkpointing"));
639        assert!(command.contains("--approval-mode"));
640        assert!(command.contains("default"));
641        assert!(!command.contains("--yolo"));
642    }
643
644    #[test]
645    fn test_build_agent_command_gemini_raw_passthrough() {
646        let options = AgentCommandOptions {
647            tool: "gemini".to_string(),
648            working_directory: "/tmp/test".to_string(),
649            prompt_file: Some("/tmp/prompt.txt".to_string()),
650            executable: Some("/opt/gemini cli/gemini".to_string()),
651            extra_env: vec![("GEMINI_HOME".to_string(), "/tmp/gemini home".to_string())],
652            extra_args: vec!["--telemetry".to_string(), "false".to_string()],
653            skip_default_safety_flags: true,
654            isolation: "none".to_string(),
655            ..Default::default()
656        };
657
658        let command = build_agent_command(&options);
659        assert!(command.contains("cat"));
660        assert!(command.contains("/tmp/prompt.txt"));
661        assert!(!command.contains("GEMINI_HOME"));
662        assert!(command.contains("/opt/gemini cli/gemini"));
663        assert!(command.contains("--telemetry"));
664        assert!(command.contains("false"));
665        assert!(!command.contains("--yolo"));
666    }
667
668    #[test]
669    fn test_build_agent_command_unknown_tool() {
670        let options = AgentCommandOptions {
671            tool: "unknown-tool".to_string(),
672            working_directory: "/tmp/test".to_string(),
673            prompt: Some("Hello".to_string()),
674            isolation: "none".to_string(),
675            ..Default::default()
676        };
677
678        let command = build_agent_command(&options);
679        assert!(command.contains("bash -c"));
680        assert!(command.contains("unknown-tool"));
681        assert!(command.contains("--prompt"));
682    }
683
684    #[test]
685    fn test_build_agent_command_screen_isolation() {
686        let options = AgentCommandOptions {
687            tool: "claude".to_string(),
688            working_directory: "/tmp/test".to_string(),
689            isolation: "screen".to_string(),
690            screen_name: Some("my-session".to_string()),
691            detached: true,
692            ..Default::default()
693        };
694
695        let command = build_agent_command(&options);
696        assert!(command.contains("screen"));
697        assert!(command.contains("-dmS"));
698        assert!(command.contains("my-session"));
699    }
700
701    #[test]
702    fn test_build_agent_command_docker_isolation() {
703        let options = AgentCommandOptions {
704            tool: "claude".to_string(),
705            working_directory: "/tmp/test".to_string(),
706            isolation: "docker".to_string(),
707            container_name: Some("my-container".to_string()),
708            detached: true,
709            ..Default::default()
710        };
711
712        let command = build_agent_command(&options);
713        assert!(command.contains("docker run"));
714        assert!(command.contains("-d"));
715        assert!(command.contains("--name \"my-container\""));
716        assert!(command.contains("-v \"/tmp/test:/tmp/test\""));
717    }
718
719    #[test]
720    fn test_build_agent_command_with_model() {
721        let options = AgentCommandOptions {
722            tool: "claude".to_string(),
723            working_directory: "/tmp/test".to_string(),
724            model: Some("opus".to_string()),
725            isolation: "none".to_string(),
726            ..Default::default()
727        };
728
729        let command = build_agent_command(&options);
730        assert!(command.contains("--model"));
731        assert!(command.contains("--model opus"));
732    }
733
734    #[test]
735    fn test_build_agent_command_codex() {
736        let options = AgentCommandOptions {
737            tool: "codex".to_string(),
738            working_directory: "/tmp/test".to_string(),
739            prompt: Some("Hello".to_string()),
740            json: true,
741            isolation: "none".to_string(),
742            ..Default::default()
743        };
744
745        let command = build_agent_command(&options);
746        assert!(command.contains("codex"));
747        assert!(command.contains("exec"));
748        assert!(command.contains("--json"));
749    }
750
751    #[test]
752    fn test_build_agent_command_codex_prompt_file() {
753        let inline_prompt = "Secret prompt with 'quotes', $HOME, and `pwd`";
754        let options = AgentCommandOptions {
755            tool: "codex".to_string(),
756            working_directory: "/tmp/test".to_string(),
757            prompt: Some(inline_prompt.to_string()),
758            system_prompt: Some("System instructions".to_string()),
759            prompt_file: Some("/tmp/agent prompt.txt".to_string()),
760            json: true,
761            isolation: "none".to_string(),
762            ..Default::default()
763        };
764
765        let command = build_agent_command(&options);
766        assert!(command.contains("cat"));
767        assert!(command.contains("/tmp/agent prompt.txt"));
768        assert!(command.contains("codex"));
769        assert!(!command.contains(inline_prompt));
770        assert!(!command.contains("System instructions"));
771    }
772
773    #[test]
774    fn test_build_agent_command_claude_prompt_file() {
775        let inline_prompt = "Secret prompt with 'quotes', $HOME, and `pwd`";
776        let options = AgentCommandOptions {
777            tool: "claude".to_string(),
778            working_directory: "/tmp/test".to_string(),
779            prompt: Some(inline_prompt.to_string()),
780            system_prompt: Some("You are helpful".to_string()),
781            prompt_file: Some("/tmp/agent prompt.txt".to_string()),
782            isolation: "none".to_string(),
783            ..Default::default()
784        };
785
786        let command = build_agent_command(&options);
787        assert!(command.contains("cat"));
788        assert!(command.contains("/tmp/agent prompt.txt"));
789        assert!(command.contains("claude"));
790        assert!(command.contains("--system-prompt"));
791        assert!(command.contains("You are helpful"));
792        assert!(!command.contains(inline_prompt));
793    }
794
795    #[test]
796    fn test_build_agent_command_qwen_prompt_file() {
797        let inline_prompt = "Secret prompt with 'quotes', $HOME, and `pwd`";
798        let options = AgentCommandOptions {
799            tool: "qwen".to_string(),
800            working_directory: "/tmp/test".to_string(),
801            prompt: Some(inline_prompt.to_string()),
802            system_prompt: Some("System instructions".to_string()),
803            prompt_file: Some("/tmp/agent prompt.txt".to_string()),
804            isolation: "none".to_string(),
805            ..Default::default()
806        };
807
808        let command = build_agent_command(&options);
809        assert!(command.contains("cat"));
810        assert!(command.contains("/tmp/agent prompt.txt"));
811        assert!(command.contains("qwen"));
812        assert!(!command.contains(inline_prompt));
813        assert!(!command.contains("System instructions"));
814    }
815
816    #[test]
817    fn test_build_agent_command_gemini_prompt_file() {
818        let inline_prompt = "Secret prompt with 'quotes', $HOME, and `pwd`";
819        let options = AgentCommandOptions {
820            tool: "gemini".to_string(),
821            working_directory: "/tmp/test".to_string(),
822            prompt: Some(inline_prompt.to_string()),
823            system_prompt: Some("System instructions".to_string()),
824            prompt_file: Some("/tmp/agent prompt.txt".to_string()),
825            isolation: "none".to_string(),
826            ..Default::default()
827        };
828
829        let command = build_agent_command(&options);
830        assert!(command.contains("cat"));
831        assert!(command.contains("/tmp/agent prompt.txt"));
832        assert!(command.contains("gemini"));
833        assert!(!command.contains(inline_prompt));
834        assert!(!command.contains("System instructions"));
835    }
836
837    #[test]
838    fn test_build_agent_command_opencode() {
839        let options = AgentCommandOptions {
840            tool: "opencode".to_string(),
841            working_directory: "/tmp/test".to_string(),
842            prompt: Some("Hello".to_string()),
843            json: true,
844            isolation: "none".to_string(),
845            ..Default::default()
846        };
847
848        let command = build_agent_command(&options);
849        assert!(command.contains("opencode"));
850        assert!(command.contains("run"));
851        assert!(command.contains("--format"));
852    }
853
854    #[test]
855    fn test_build_agent_command_agent_tool() {
856        let options = AgentCommandOptions {
857            tool: "agent".to_string(),
858            working_directory: "/tmp/test".to_string(),
859            model: Some("grok".to_string()),
860            isolation: "none".to_string(),
861            ..Default::default()
862        };
863
864        let command = build_agent_command(&options);
865        assert!(command.contains("agent"));
866        assert!(command.contains("--model"));
867        assert!(command.contains("opencode/grok-code"));
868    }
869
870    #[test]
871    fn test_build_screen_stop_command() {
872        let command = build_screen_stop_command("my-session");
873        assert!(command.contains("screen"));
874        assert!(command.contains("-S \"my-session\""));
875        assert!(command.contains("-X quit"));
876    }
877
878    #[test]
879    fn test_build_docker_stop_command() {
880        let command = build_docker_stop_command("my-container");
881        assert!(command.contains("docker stop \"my-container\""));
882        assert!(command.contains("docker rm \"my-container\""));
883    }
884
885    #[test]
886    fn test_build_piped_command_basic() {
887        let command = build_piped_command("Hello World", "mycommand --flag");
888        assert!(command.contains("printf '%s'"));
889        assert!(command.contains("Hello World"));
890        assert!(command.contains("mycommand --flag"));
891    }
892
893    #[test]
894    fn test_build_piped_command_escapes_quotes() {
895        let command = build_piped_command("It's working", "mycommand");
896        assert!(command.contains("'\\''"));
897    }
898}