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 gateway
166/// token variable. 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    if let Some(gateway) = &options.launch.gateway {
179        if !names.contains(&gateway.token_env) {
180            names.push(gateway.token_env.clone());
181        }
182    }
183    names
184}
185
186/// Build the command for executing an agent
187///
188/// # Arguments
189/// * `options` - Command options
190///
191/// # Returns
192/// The command string
193pub fn build_agent_command(options: &AgentCommandOptions) -> String {
194    // A planning request implies a read-only restriction for tools that do not
195    // distinguish the two modes.
196    let read_only_requested = options.read_only || options.plan_only;
197
198    assert!(
199        !(read_only_requested && !supports_read_only(&options.tool)),
200        "{}",
201        read_only_unsupported_error(&options.tool)
202    );
203
204    // Per-command approval ("ask" mode) is only enforceable on tools that expose
205    // a drivable JSON permission request/response protocol (agent, claude). Fail
206    // clearly for the rest, mirroring the --read-only gate above.
207    assert!(
208        !(options.approve_each && !crate::permissions::supports_ask(&options.tool)),
209        "{}",
210        crate::permissions::ask_unsupported_error(&options.tool)
211    );
212
213    let capabilities = options
214        .overrides
215        .launch_capabilities
216        .unwrap_or_else(|| launch_capabilities(&options.tool));
217    if let Err(error) = check_launch_options_against(&options.tool, &options.launch, &capabilities)
218    {
219        panic!("{error}");
220    }
221
222    // A caller's builder replaces the tool-specific one (issue #57).
223    let base_command = match &options.overrides.build_command {
224        Some(build) => build(options),
225        None => build_base_command(options),
226    };
227
228    // Wrap in bash -c with working directory change
229    let mut full_command = format!(
230        "bash -c \"cd {} && {}\"",
231        escape_for_double_quotes(&escape_arg(&options.working_directory)),
232        escape_for_double_quotes(&base_command)
233    );
234
235    // Apply isolation wrapper
236    match options.isolation.as_str() {
237        "screen" => {
238            full_command = build_screen_command(
239                &full_command,
240                options.screen_name.as_deref(),
241                options.detached,
242            );
243        }
244        "docker" => {
245            full_command = build_docker_command(
246                &full_command,
247                options.container_name.as_deref(),
248                &options.working_directory,
249                options.detached,
250                &docker_env_names(options),
251            );
252        }
253        _ => {}
254    }
255
256    full_command
257}
258
259/// Build the native tool command without the working-directory and isolation
260/// wrappers. A `ToolOverrides::build_command` can call it and extend the result.
261pub fn build_base_command(options: &AgentCommandOptions) -> String {
262    // A planning request implies a read-only restriction for tools that do not
263    // distinguish the two modes.
264    let read_only_requested = options.read_only || options.plan_only;
265    match options.tool.as_str() {
266        "claude" => claude::build_command(&ClaudeBuildOptions {
267            prompt: options.prompt.clone(),
268            prompt_file: options.prompt_file.clone(),
269            system_prompt: options.system_prompt.clone(),
270            append_system_prompt: options.append_system_prompt.clone(),
271            model: options.model.clone(),
272            fallback_model: options.fallback_model.clone(),
273            json: options.json,
274            json_input: options.stream_input,
275            verbose: options.verbose,
276            replay_user_messages: options.replay_user_messages,
277            resume: options.resume.clone(),
278            session_id: options.session_id.clone(),
279            fork_session: options.fork_session,
280            print: false,
281            read_only: read_only_requested,
282            approve_each: options.approve_each,
283            executable: options.executable.clone(),
284            extra_env: options.extra_env.clone(),
285            unset_env: options.unset_env.clone(),
286            extra_args: options.extra_args.clone(),
287            skip_default_safety_flags: options.skip_default_safety_flags,
288            permission_mode: None,
289            stream_input: options.stream_input,
290            launch: options.launch.clone(),
291        }),
292        "codex" => codex::build_command(&CodexBuildOptions {
293            prompt: options.prompt.clone(),
294            prompt_file: options.prompt_file.clone(),
295            system_prompt: options.system_prompt.clone(),
296            model: options.model.clone(),
297            json: options.json,
298            resume: options.resume.clone(),
299            read_only: read_only_requested,
300            executable: options.executable.clone(),
301            extra_env: options.extra_env.clone(),
302            unset_env: options.unset_env.clone(),
303            extra_args: options.extra_args.clone(),
304            skip_default_safety_flags: options.skip_default_safety_flags,
305            sandbox_mode: None,
306            approval_mode: None,
307            launch: options.launch.clone(),
308        }),
309        "opencode" => opencode::build_command(&OpencodeBuildOptions {
310            prompt: options.prompt.clone(),
311            prompt_file: options.prompt_file.clone(),
312            system_prompt: options.system_prompt.clone(),
313            model: options.model.clone(),
314            json: options.json,
315            resume: options.resume.clone(),
316            read_only: read_only_requested,
317            executable: options.executable.clone(),
318            extra_env: options.extra_env.clone(),
319            unset_env: options.unset_env.clone(),
320            extra_args: options.extra_args.clone(),
321            launch: options.launch.clone(),
322        }),
323        "agent" => agent::build_command(&AgentBuildOptions {
324            resume: options.resume.clone(),
325            prompt: options.prompt.clone(),
326            prompt_file: options.prompt_file.clone(),
327            system_prompt: options.system_prompt.clone(),
328            model: options.model.clone(),
329            temperature: options.launch.temperature,
330            compact_json: false,
331            use_existing_claude_oauth: false,
332            read_only: read_only_requested,
333            plan_only: options.plan_only,
334            approve_each: options.approve_each,
335            permission_mode: None,
336            permission: None,
337            stream_input: options.stream_input,
338            json_input: options.stream_input,
339            executable: options.executable.clone(),
340            extra_env: options.extra_env.clone(),
341            unset_env: options.unset_env.clone(),
342            extra_args: options.extra_args.clone(),
343        }),
344        "gemini" => {
345            let options = GeminiBuildOptions {
346                resume: options.resume.clone(),
347                prompt: options.prompt.clone(),
348                prompt_file: options.prompt_file.clone(),
349                system_prompt: options.system_prompt.clone(),
350                model: options.model.clone(),
351                json: options.json,
352                read_only: read_only_requested,
353                executable: options.executable.clone(),
354                extra_env: options.extra_env.clone(),
355                unset_env: options.unset_env.clone(),
356                extra_args: options.extra_args.clone(),
357                skip_default_safety_flags: options.skip_default_safety_flags,
358                launch: options.launch.clone(),
359                ..GeminiBuildOptions::new()
360            };
361            gemini::build_command(&options)
362        }
363        "qwen" => {
364            let options = QwenBuildOptions {
365                prompt: options.prompt.clone(),
366                prompt_file: options.prompt_file.clone(),
367                system_prompt: options.system_prompt.clone(),
368                model: options.model.clone(),
369                json: options.json,
370                resume: options.resume.clone(),
371                read_only: read_only_requested,
372                executable: options.executable.clone(),
373                extra_env: options.extra_env.clone(),
374                unset_env: options.unset_env.clone(),
375                extra_args: options.extra_args.clone(),
376                skip_default_safety_flags: options.skip_default_safety_flags,
377                launch: options.launch.clone(),
378                json_input: options.stream_input,
379                stream_input: options.stream_input,
380                ..QwenBuildOptions::new()
381            };
382            qwen::build_command(&options)
383        }
384        // Unknown tool, use generic command builder
385        _ => build_tool_command(
386            &options.tool,
387            options.prompt.as_deref(),
388            options.system_prompt.as_deref(),
389        ),
390    }
391}
392
393/// Build stop command for screen sessions
394///
395/// # Arguments
396/// * `screen_name` - Screen session name
397///
398/// # Returns
399/// Stop command
400pub fn build_screen_stop_command(screen_name: &str) -> String {
401    format!("screen -S \"{}\" -X quit", screen_name)
402}
403
404/// Build stop command for docker containers
405///
406/// # Arguments
407/// * `container_name` - Container name
408///
409/// # Returns
410/// Stop command
411pub fn build_docker_stop_command(container_name: &str) -> String {
412    format!(
413        "docker stop \"{}\" && docker rm \"{}\"",
414        container_name, container_name
415    )
416}
417
418/// Build stdin piping command for tools that accept input via stdin
419///
420/// # Arguments
421/// * `input` - Input to pipe
422/// * `command` - Command to pipe to
423///
424/// # Returns
425/// Piped command
426pub fn build_piped_command(input: &str, command: &str) -> String {
427    let escaped_input = escape_for_single_quotes(input);
428    format!("printf '%s' '{}' | {}", escaped_input, command)
429}
430
431#[cfg(test)]
432mod tests {
433    use super::*;
434
435    #[test]
436    fn test_build_agent_command_basic_claude() {
437        let options = AgentCommandOptions {
438            tool: "claude".to_string(),
439            working_directory: "/tmp/test".to_string(),
440            prompt: Some("Hello".to_string()),
441            isolation: "none".to_string(),
442            ..Default::default()
443        };
444
445        let command = build_agent_command(&options);
446        assert!(command.contains("bash -c"));
447        assert!(command.contains("cd"));
448        assert!(command.contains("/tmp/test"));
449        assert!(command.contains("claude"));
450        assert!(command.contains("-p"));
451        assert!(command.contains("Hello"));
452    }
453
454    #[test]
455    fn test_build_agent_command_with_system_prompt() {
456        let options = AgentCommandOptions {
457            tool: "claude".to_string(),
458            working_directory: "/tmp/test".to_string(),
459            prompt: Some("Hello".to_string()),
460            system_prompt: Some("You are helpful".to_string()),
461            isolation: "none".to_string(),
462            ..Default::default()
463        };
464
465        let command = build_agent_command(&options);
466        assert!(command.contains("-p"));
467        assert!(command.contains("--system-prompt"));
468        assert!(command.contains("You are helpful"));
469    }
470
471    #[test]
472    fn test_build_agent_command_claude_with_fallback_model() {
473        let options = AgentCommandOptions {
474            tool: "claude".to_string(),
475            working_directory: "/tmp/test".to_string(),
476            model: Some("opus".to_string()),
477            fallback_model: Some("sonnet".to_string()),
478            isolation: "none".to_string(),
479            ..Default::default()
480        };
481
482        let command = build_agent_command(&options);
483        assert!(command.contains("--model"));
484        assert!(command.contains("--model opus"));
485        assert!(command.contains("--fallback-model"));
486        assert!(command.contains("--fallback-model sonnet"));
487    }
488
489    #[test]
490    fn test_build_agent_command_claude_with_append_system_prompt() {
491        let options = AgentCommandOptions {
492            tool: "claude".to_string(),
493            working_directory: "/tmp/test".to_string(),
494            append_system_prompt: Some("Extra instructions".to_string()),
495            isolation: "none".to_string(),
496            ..Default::default()
497        };
498
499        let command = build_agent_command(&options);
500        assert!(command.contains("--append-system-prompt"));
501        assert!(command.contains("Extra instructions"));
502    }
503
504    #[test]
505    fn test_build_agent_command_claude_with_session_management() {
506        let options = AgentCommandOptions {
507            tool: "claude".to_string(),
508            working_directory: "/tmp/test".to_string(),
509            resume: Some("abc123".to_string()),
510            session_id: Some("123e4567-e89b-12d3-a456-426614174000".to_string()),
511            fork_session: true,
512            isolation: "none".to_string(),
513            ..Default::default()
514        };
515
516        let command = build_agent_command(&options);
517        assert!(command.contains("--resume"));
518        assert!(command.contains("abc123"));
519        assert!(command.contains("--session-id"));
520        assert!(command.contains("123e4567-e89b-12d3-a456-426614174000"));
521        assert!(command.contains("--fork-session"));
522    }
523
524    #[test]
525    fn test_build_agent_command_claude_with_verbose_streaming() {
526        let options = AgentCommandOptions {
527            tool: "claude".to_string(),
528            working_directory: "/tmp/test".to_string(),
529            verbose: true,
530            replay_user_messages: true,
531            isolation: "none".to_string(),
532            ..Default::default()
533        };
534
535        let command = build_agent_command(&options);
536        assert!(command.contains("--verbose"));
537        assert!(command.contains("--replay-user-messages"));
538    }
539
540    #[test]
541    fn test_build_agent_command_claude_raw_passthrough() {
542        let options = AgentCommandOptions {
543            tool: "claude".to_string(),
544            working_directory: "/tmp/test".to_string(),
545            prompt: Some("Hello".to_string()),
546            executable: Some("/opt/Claude Code/bin/claude".to_string()),
547            extra_env: vec![
548                (
549                    "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC".to_string(),
550                    "1".to_string(),
551                ),
552                ("MCP_TIMEOUT".to_string(), "10000".to_string()),
553            ],
554            extra_args: vec![
555                "--mcp-config".to_string(),
556                "/tmp/mcp config.json".to_string(),
557                "--permission-mode".to_string(),
558                "default".to_string(),
559            ],
560            skip_default_safety_flags: true,
561            isolation: "none".to_string(),
562            ..Default::default()
563        };
564
565        let command = build_agent_command(&options);
566        // Environment values travel through spawn, not argv (issue #60).
567        assert!(!command.contains("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"));
568        assert!(!command.contains("MCP_TIMEOUT"));
569        assert!(command.contains("/opt/Claude Code/bin/claude"));
570        assert!(command.contains("--mcp-config"));
571        assert!(command.contains("/tmp/mcp config.json"));
572        assert!(command.contains("--permission-mode"));
573        assert!(command.contains("default"));
574        assert!(!command.contains("--dangerously-skip-permissions"));
575    }
576
577    #[test]
578    fn test_docker_forwards_extra_env_by_name_only() {
579        let options = AgentCommandOptions {
580            tool: "claude".to_string(),
581            working_directory: "/tmp/test".to_string(),
582            prompt: Some("Hello".to_string()),
583            extra_env: vec![("API_TOKEN".to_string(), "sk-secret".to_string())],
584            isolation: "docker".to_string(),
585            container_name: Some("c".to_string()),
586            ..Default::default()
587        };
588        let command = build_agent_command(&options);
589        assert!(command.contains(" -e API_TOKEN "));
590        assert!(!command.contains("sk-secret"));
591    }
592
593    #[test]
594    fn test_claude_prompt_and_schema_files_replace_inline_values() {
595        let options = AgentCommandOptions {
596            tool: "claude".to_string(),
597            working_directory: "/tmp/test".to_string(),
598            prompt: Some("Hello".to_string()),
599            system_prompt: Some("PRIVATE-SYSTEM".to_string()),
600            append_system_prompt: Some("PRIVATE-APPEND".to_string()),
601            launch: crate::tools::launch_options::LaunchOptions {
602                json_schema: Some(r#"{"type":"object","secretField":1}"#.to_string()),
603                json_schema_file: Some("/tmp/d/schema.json".to_string()),
604                system_prompt_file: Some("/tmp/d/system-prompt.txt".to_string()),
605                append_system_prompt_file: Some("/tmp/d/append.txt".to_string()),
606                ..Default::default()
607            },
608            ..Default::default()
609        };
610        let command = build_agent_command(&options);
611        assert!(!command.contains("PRIVATE"));
612        assert!(!command.contains("secretField"));
613        assert!(command.contains("--system-prompt-file /tmp/d/system-prompt.txt"));
614        assert!(command.contains("--append-system-prompt-file /tmp/d/append.txt"));
615        assert!(
616            command.contains("--json-schema \\\"\\$(cat /tmp/d/schema.json)\\\""),
617            "{command}"
618        );
619    }
620
621    #[test]
622    fn test_build_agent_command_qwen_raw_passthrough() {
623        let options = AgentCommandOptions {
624            tool: "qwen".to_string(),
625            working_directory: "/tmp/test".to_string(),
626            prompt_file: Some("/tmp/prompt.txt".to_string()),
627            executable: Some("/opt/qwen code/qwen".to_string()),
628            extra_env: vec![("QWEN_HOME".to_string(), "/tmp/qwen home".to_string())],
629            extra_args: vec![
630                "--checkpointing".to_string(),
631                "--approval-mode".to_string(),
632                "default".to_string(),
633            ],
634            skip_default_safety_flags: true,
635            isolation: "none".to_string(),
636            ..Default::default()
637        };
638
639        let command = build_agent_command(&options);
640        assert!(command.contains("cat"));
641        assert!(command.contains("/tmp/prompt.txt"));
642        assert!(!command.contains("QWEN_HOME"));
643        assert!(command.contains("/opt/qwen code/qwen"));
644        assert!(command.contains("--checkpointing"));
645        assert!(command.contains("--approval-mode"));
646        assert!(command.contains("default"));
647        assert!(!command.contains("--yolo"));
648    }
649
650    #[test]
651    fn test_build_agent_command_gemini_raw_passthrough() {
652        let options = AgentCommandOptions {
653            tool: "gemini".to_string(),
654            working_directory: "/tmp/test".to_string(),
655            prompt_file: Some("/tmp/prompt.txt".to_string()),
656            executable: Some("/opt/gemini cli/gemini".to_string()),
657            extra_env: vec![("GEMINI_HOME".to_string(), "/tmp/gemini home".to_string())],
658            extra_args: vec!["--telemetry".to_string(), "false".to_string()],
659            skip_default_safety_flags: true,
660            isolation: "none".to_string(),
661            ..Default::default()
662        };
663
664        let command = build_agent_command(&options);
665        assert!(command.contains("cat"));
666        assert!(command.contains("/tmp/prompt.txt"));
667        assert!(!command.contains("GEMINI_HOME"));
668        assert!(command.contains("/opt/gemini cli/gemini"));
669        assert!(command.contains("--telemetry"));
670        assert!(command.contains("false"));
671        assert!(!command.contains("--yolo"));
672    }
673
674    #[test]
675    fn test_build_agent_command_unknown_tool() {
676        let options = AgentCommandOptions {
677            tool: "unknown-tool".to_string(),
678            working_directory: "/tmp/test".to_string(),
679            prompt: Some("Hello".to_string()),
680            isolation: "none".to_string(),
681            ..Default::default()
682        };
683
684        let command = build_agent_command(&options);
685        assert!(command.contains("bash -c"));
686        assert!(command.contains("unknown-tool"));
687        assert!(command.contains("--prompt"));
688    }
689
690    #[test]
691    fn test_build_agent_command_screen_isolation() {
692        let options = AgentCommandOptions {
693            tool: "claude".to_string(),
694            working_directory: "/tmp/test".to_string(),
695            isolation: "screen".to_string(),
696            screen_name: Some("my-session".to_string()),
697            detached: true,
698            ..Default::default()
699        };
700
701        let command = build_agent_command(&options);
702        assert!(command.contains("screen"));
703        assert!(command.contains("-dmS"));
704        assert!(command.contains("my-session"));
705    }
706
707    #[test]
708    fn test_build_agent_command_docker_isolation() {
709        let options = AgentCommandOptions {
710            tool: "claude".to_string(),
711            working_directory: "/tmp/test".to_string(),
712            isolation: "docker".to_string(),
713            container_name: Some("my-container".to_string()),
714            detached: true,
715            ..Default::default()
716        };
717
718        let command = build_agent_command(&options);
719        assert!(command.contains("docker run"));
720        assert!(command.contains("-d"));
721        assert!(command.contains("--name \"my-container\""));
722        assert!(command.contains("-v \"/tmp/test:/tmp/test\""));
723    }
724
725    #[test]
726    fn test_build_agent_command_with_model() {
727        let options = AgentCommandOptions {
728            tool: "claude".to_string(),
729            working_directory: "/tmp/test".to_string(),
730            model: Some("opus".to_string()),
731            isolation: "none".to_string(),
732            ..Default::default()
733        };
734
735        let command = build_agent_command(&options);
736        assert!(command.contains("--model"));
737        assert!(command.contains("--model opus"));
738    }
739
740    #[test]
741    fn test_build_agent_command_codex() {
742        let options = AgentCommandOptions {
743            tool: "codex".to_string(),
744            working_directory: "/tmp/test".to_string(),
745            prompt: Some("Hello".to_string()),
746            json: true,
747            isolation: "none".to_string(),
748            ..Default::default()
749        };
750
751        let command = build_agent_command(&options);
752        assert!(command.contains("codex"));
753        assert!(command.contains("exec"));
754        assert!(command.contains("--json"));
755    }
756
757    #[test]
758    fn test_build_agent_command_codex_prompt_file() {
759        let inline_prompt = "Secret prompt with 'quotes', $HOME, and `pwd`";
760        let options = AgentCommandOptions {
761            tool: "codex".to_string(),
762            working_directory: "/tmp/test".to_string(),
763            prompt: Some(inline_prompt.to_string()),
764            system_prompt: Some("System instructions".to_string()),
765            prompt_file: Some("/tmp/agent prompt.txt".to_string()),
766            json: true,
767            isolation: "none".to_string(),
768            ..Default::default()
769        };
770
771        let command = build_agent_command(&options);
772        assert!(command.contains("cat"));
773        assert!(command.contains("/tmp/agent prompt.txt"));
774        assert!(command.contains("codex"));
775        assert!(!command.contains(inline_prompt));
776        assert!(!command.contains("System instructions"));
777    }
778
779    #[test]
780    fn test_build_agent_command_claude_prompt_file() {
781        let inline_prompt = "Secret prompt with 'quotes', $HOME, and `pwd`";
782        let options = AgentCommandOptions {
783            tool: "claude".to_string(),
784            working_directory: "/tmp/test".to_string(),
785            prompt: Some(inline_prompt.to_string()),
786            system_prompt: Some("You are helpful".to_string()),
787            prompt_file: Some("/tmp/agent prompt.txt".to_string()),
788            isolation: "none".to_string(),
789            ..Default::default()
790        };
791
792        let command = build_agent_command(&options);
793        assert!(command.contains("cat"));
794        assert!(command.contains("/tmp/agent prompt.txt"));
795        assert!(command.contains("claude"));
796        assert!(command.contains("--system-prompt"));
797        assert!(command.contains("You are helpful"));
798        assert!(!command.contains(inline_prompt));
799    }
800
801    #[test]
802    fn test_build_agent_command_qwen_prompt_file() {
803        let inline_prompt = "Secret prompt with 'quotes', $HOME, and `pwd`";
804        let options = AgentCommandOptions {
805            tool: "qwen".to_string(),
806            working_directory: "/tmp/test".to_string(),
807            prompt: Some(inline_prompt.to_string()),
808            system_prompt: Some("System instructions".to_string()),
809            prompt_file: Some("/tmp/agent prompt.txt".to_string()),
810            isolation: "none".to_string(),
811            ..Default::default()
812        };
813
814        let command = build_agent_command(&options);
815        assert!(command.contains("cat"));
816        assert!(command.contains("/tmp/agent prompt.txt"));
817        assert!(command.contains("qwen"));
818        assert!(!command.contains(inline_prompt));
819        assert!(!command.contains("System instructions"));
820    }
821
822    #[test]
823    fn test_build_agent_command_gemini_prompt_file() {
824        let inline_prompt = "Secret prompt with 'quotes', $HOME, and `pwd`";
825        let options = AgentCommandOptions {
826            tool: "gemini".to_string(),
827            working_directory: "/tmp/test".to_string(),
828            prompt: Some(inline_prompt.to_string()),
829            system_prompt: Some("System instructions".to_string()),
830            prompt_file: Some("/tmp/agent prompt.txt".to_string()),
831            isolation: "none".to_string(),
832            ..Default::default()
833        };
834
835        let command = build_agent_command(&options);
836        assert!(command.contains("cat"));
837        assert!(command.contains("/tmp/agent prompt.txt"));
838        assert!(command.contains("gemini"));
839        assert!(!command.contains(inline_prompt));
840        assert!(!command.contains("System instructions"));
841    }
842
843    #[test]
844    fn test_build_agent_command_opencode() {
845        let options = AgentCommandOptions {
846            tool: "opencode".to_string(),
847            working_directory: "/tmp/test".to_string(),
848            prompt: Some("Hello".to_string()),
849            json: true,
850            isolation: "none".to_string(),
851            ..Default::default()
852        };
853
854        let command = build_agent_command(&options);
855        assert!(command.contains("opencode"));
856        assert!(command.contains("run"));
857        assert!(command.contains("--format"));
858    }
859
860    #[test]
861    fn test_build_agent_command_agent_tool() {
862        let options = AgentCommandOptions {
863            tool: "agent".to_string(),
864            working_directory: "/tmp/test".to_string(),
865            model: Some("grok".to_string()),
866            isolation: "none".to_string(),
867            ..Default::default()
868        };
869
870        let command = build_agent_command(&options);
871        assert!(command.contains("agent"));
872        assert!(command.contains("--model"));
873        assert!(command.contains("opencode/grok-code"));
874    }
875
876    #[test]
877    fn test_build_screen_stop_command() {
878        let command = build_screen_stop_command("my-session");
879        assert!(command.contains("screen"));
880        assert!(command.contains("-S \"my-session\""));
881        assert!(command.contains("-X quit"));
882    }
883
884    #[test]
885    fn test_build_docker_stop_command() {
886        let command = build_docker_stop_command("my-container");
887        assert!(command.contains("docker stop \"my-container\""));
888        assert!(command.contains("docker rm \"my-container\""));
889    }
890
891    #[test]
892    fn test_build_piped_command_basic() {
893        let command = build_piped_command("Hello World", "mycommand --flag");
894        assert!(command.contains("printf '%s'"));
895        assert!(command.contains("Hello World"));
896        assert!(command.contains("mycommand --flag"));
897    }
898
899    #[test]
900    fn test_build_piped_command_escapes_quotes() {
901        let command = build_piped_command("It's working", "mycommand");
902        assert!(command.contains("'\\''"));
903    }
904}