Skip to main content

agent_commander/
docker.rs

1//! Docker arguments shared by the library and CLI.
2
3use crate::tools::shell::escape_arg;
4use crate::AgentCommandOptions;
5use command_stream::quote::escape_for_single_quotes;
6use std::path::Path;
7
8/// Settings for `isolation: "docker"`.
9#[derive(Debug, Clone, Default)]
10pub struct DockerOptions {
11    /// Image containing Bash and the selected agent CLI.
12    pub image: Option<String>,
13    /// Network name or mode, for example `none`.
14    pub network: Option<String>,
15    /// Docker memory limit, for example `512m`.
16    pub memory: Option<String>,
17    /// Docker CPU allocation, for example `1.5`.
18    pub cpus: Option<String>,
19    /// Extra `docker run` arguments, one string per argv entry.
20    pub args: Vec<String>,
21    /// Leave the container after it exits. By default Docker removes it.
22    pub keep_container: bool,
23}
24
25impl DockerOptions {
26    /// Check Docker settings before building or launching a container.
27    pub fn validate(&self) -> Result<(), String> {
28        if self
29            .image
30            .as_deref()
31            .is_none_or(|image| image.trim().is_empty() || image.starts_with('-'))
32        {
33            return Err("dockerImage (--docker-image) is required for docker isolation".into());
34        }
35        for (flag, value) in [
36            ("--docker-network", &self.network),
37            ("--docker-memory", &self.memory),
38            ("--docker-cpus", &self.cpus),
39        ] {
40            if value.as_ref().is_some_and(|value| value.trim().is_empty()) {
41                return Err(format!("{flag} must have a value"));
42            }
43        }
44        Ok(())
45    }
46}
47
48pub(crate) fn build_command(
49    base: &str,
50    options: &AgentCommandOptions,
51    env_names: &[String],
52) -> String {
53    let settings = &options.docker;
54    settings
55        .validate()
56        .unwrap_or_else(|error| panic!("{error}"));
57    let name = options.container_name.clone().unwrap_or_else(|| {
58        format!(
59            "agent-{}",
60            std::time::SystemTime::now()
61                .duration_since(std::time::UNIX_EPOCH)
62                .unwrap()
63                .as_millis()
64        )
65    });
66    let directory = &options.working_directory;
67    let mut args = vec![
68        "run".to_owned(),
69        "--init".into(),
70        "--entrypoint".into(),
71        "bash".into(),
72    ];
73    if !settings.keep_container {
74        args.push("--rm".into());
75    }
76    if options.detached {
77        args.push("-d".into());
78    } else if options.stream_input {
79        args.push("-i".into());
80    } else if options.docker_tty {
81        args.push("-t".into());
82    }
83    args.extend([
84        "--name".into(),
85        name,
86        "-v".into(),
87        format!("{directory}:{directory}"),
88        "-w".into(),
89        directory.clone(),
90    ]);
91    for (flag, value) in [
92        ("--network", &settings.network),
93        ("--memory", &settings.memory),
94        ("--cpus", &settings.cpus),
95        ("--cidfile", &options.docker_cid_file),
96    ] {
97        if let Some(value) = value {
98            args.extend([flag.into(), value.clone()]);
99        }
100    }
101    for name in env_names {
102        args.extend(["-e".into(), name.clone()]);
103    }
104    for file in [
105        &options.prompt_file,
106        &options.launch.system_prompt_file,
107        &options.launch.append_system_prompt_file,
108        &options.launch.json_schema_file,
109    ]
110    .into_iter()
111    .flatten()
112    {
113        let path = Path::new(directory).join(file);
114        let path = path.to_string_lossy();
115        args.extend(["-v".into(), format!("{path}:{path}:ro")]);
116    }
117    args.extend(settings.args.iter().cloned());
118    args.extend(["--".into(), settings.image.clone().unwrap(), "-c".into()]);
119    let quoted: Vec<_> = args.iter().map(|arg| escape_arg(arg)).collect();
120    format!(
121        "docker {} '{}'",
122        quoted.join(" "),
123        escape_for_single_quotes(base)
124    )
125}