agent-commander 0.7.0

A Rust library to control agents enclosed in CLI commands like Anthropic Claude Code CLI
Documentation
//! Docker arguments shared by the library and CLI.

use crate::tools::shell::escape_arg;
use crate::AgentCommandOptions;
use command_stream::quote::escape_for_single_quotes;
use std::path::Path;

/// Settings for `isolation: "docker"`.
#[derive(Debug, Clone, Default)]
pub struct DockerOptions {
    /// Image containing Bash and the selected agent CLI.
    pub image: Option<String>,
    /// Network name or mode, for example `none`.
    pub network: Option<String>,
    /// Docker memory limit, for example `512m`.
    pub memory: Option<String>,
    /// Docker CPU allocation, for example `1.5`.
    pub cpus: Option<String>,
    /// Extra `docker run` arguments, one string per argv entry.
    pub args: Vec<String>,
    /// Leave the container after it exits. By default Docker removes it.
    pub keep_container: bool,
}

impl DockerOptions {
    /// Check Docker settings before building or launching a container.
    pub fn validate(&self) -> Result<(), String> {
        if self
            .image
            .as_deref()
            .is_none_or(|image| image.trim().is_empty() || image.starts_with('-'))
        {
            return Err("dockerImage (--docker-image) is required for docker isolation".into());
        }
        for (flag, value) in [
            ("--docker-network", &self.network),
            ("--docker-memory", &self.memory),
            ("--docker-cpus", &self.cpus),
        ] {
            if value.as_ref().is_some_and(|value| value.trim().is_empty()) {
                return Err(format!("{flag} must have a value"));
            }
        }
        Ok(())
    }
}

pub(crate) fn build_command(
    base: &str,
    options: &AgentCommandOptions,
    env_names: &[String],
) -> String {
    let settings = &options.docker;
    settings
        .validate()
        .unwrap_or_else(|error| panic!("{error}"));
    let name = options.container_name.clone().unwrap_or_else(|| {
        format!(
            "agent-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_millis()
        )
    });
    let directory = &options.working_directory;
    let mut args = vec![
        "run".to_owned(),
        "--init".into(),
        "--entrypoint".into(),
        "bash".into(),
    ];
    if !settings.keep_container {
        args.push("--rm".into());
    }
    if options.detached {
        args.push("-d".into());
    } else if options.stream_input {
        args.push("-i".into());
    } else if options.docker_tty {
        args.push("-t".into());
    }
    args.extend([
        "--name".into(),
        name,
        "-v".into(),
        format!("{directory}:{directory}"),
        "-w".into(),
        directory.clone(),
    ]);
    for (flag, value) in [
        ("--network", &settings.network),
        ("--memory", &settings.memory),
        ("--cpus", &settings.cpus),
        ("--cidfile", &options.docker_cid_file),
    ] {
        if let Some(value) = value {
            args.extend([flag.into(), value.clone()]);
        }
    }
    for name in env_names {
        args.extend(["-e".into(), name.clone()]);
    }
    for file in [
        &options.prompt_file,
        &options.launch.system_prompt_file,
        &options.launch.append_system_prompt_file,
        &options.launch.json_schema_file,
    ]
    .into_iter()
    .flatten()
    {
        let path = Path::new(directory).join(file);
        let path = path.to_string_lossy();
        args.extend(["-v".into(), format!("{path}:{path}:ro")]);
    }
    args.extend(settings.args.iter().cloned());
    args.extend(["--".into(), settings.image.clone().unwrap(), "-c".into()]);
    let quoted: Vec<_> = args.iter().map(|arg| escape_arg(arg)).collect();
    format!(
        "docker {} '{}'",
        quoted.join(" "),
        escape_for_single_quotes(base)
    )
}