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