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