Skip to main content

agent_commander/tools/
shell.rs

1//! Shared shell helpers for tool command builders.
2
3/// Escape an argument for shell usage.
4pub fn escape_arg(arg: &str) -> String {
5    if arg.is_empty()
6        || !arg
7            .chars()
8            .all(|c| c.is_ascii_alphanumeric() || "-_./:=+,@%".contains(c))
9    {
10        let escaped = arg
11            .replace('\\', "\\\\")
12            .replace('"', "\\\"")
13            .replace('$', "\\$")
14            .replace('`', "\\`");
15        format!("\"{}\"", escaped)
16    } else {
17        arg.to_string()
18    }
19}
20
21/// Escape single quotes for printf (command-stream's
22/// [`escape_for_single_quotes`](command_stream::quote::escape_for_single_quotes)).
23pub fn escape_single_quotes(s: &str) -> String {
24    command_stream::quote::escape_for_single_quotes(s)
25}
26
27/// Look a model alias up, exactly first and then case-insensitively
28/// (`Opus` is `opus`, as in Hive Mind).
29pub fn lookup_model_alias(
30    model_map: &std::collections::HashMap<&'static str, &'static str>,
31    model: &str,
32) -> Option<String> {
33    model_map
34        .get(model)
35        .or_else(|| {
36            model_map
37                .iter()
38                .find(|(alias, _)| alias.eq_ignore_ascii_case(model))
39                .map(|(_, id)| id)
40        })
41        .map(|id| (*id).to_string())
42}
43
44pub fn is_valid_env_name(name: &str) -> bool {
45    let mut chars = name.chars();
46    let Some(first) = chars.next() else {
47        return false;
48    };
49    if first != '_' && !first.is_ascii_alphabetic() {
50        return false;
51    }
52    chars.all(|c| c == '_' || c.is_ascii_alphanumeric())
53}
54
55/// Render `flag "$(cat file)"`: the value reaches the tool as one argument,
56/// but the shell command line only holds the file path (issue #60).
57pub fn file_content_arg(flag: &str, file: &str) -> String {
58    format!("{} \"$(cat {})\"", flag, escape_arg(file))
59}
60
61/// Which variables of the host environment a tool inherits (issue #60)
62#[derive(Debug, Clone, Default, PartialEq, Eq)]
63pub enum InheritEnv {
64    /// Inherit everything (default)
65    #[default]
66    All,
67    /// Inherit nothing
68    None,
69    /// Inherit only these variable names
70    Only(Vec<String>),
71}
72
73/// Build the child environment passed to `spawn`.
74///
75/// `env` replaces the inherited environment; otherwise `inherit_env` selects
76/// what is copied from `parent`. `unset_env` is then removed and `extra_env`
77/// applied on top. Values never appear on the command line.
78///
79/// # Errors
80/// Returns an error for an invalid variable name.
81pub fn build_child_environment(
82    parent: impl IntoIterator<Item = (String, String)>,
83    inherit_env: &InheritEnv,
84    env: Option<&[(String, String)]>,
85    unset_env: &[String],
86    extra_env: &[(String, String)],
87) -> Result<Vec<(String, String)>, String> {
88    let check = |name: &str| {
89        if is_valid_env_name(name) {
90            Ok(())
91        } else {
92            Err(format!("invalid environment variable name: {name}"))
93        }
94    };
95    let mut result: Vec<(String, String)> = match env {
96        Some(env) => env.to_vec(),
97        None => match inherit_env {
98            InheritEnv::All => parent.into_iter().collect(),
99            InheritEnv::None => Vec::new(),
100            InheritEnv::Only(names) => {
101                for name in names {
102                    check(name)?;
103                }
104                parent
105                    .into_iter()
106                    .filter(|(key, _)| names.contains(key))
107                    .collect()
108            }
109        },
110    };
111    for name in unset_env {
112        check(name)?;
113        result.retain(|(key, _)| key != name);
114    }
115    for (key, value) in extra_env {
116        check(key)?;
117        result.retain(|(existing, _)| existing != key);
118        result.push((key.clone(), value.clone()));
119    }
120    Ok(result)
121}
122
123/// Build a command head with optional env vars and executable prefix args;
124/// `unset_env` is removed from the inherited environment (Hive Mind drops `GH_TOKEN`, `MAX_THINKING_TOKENS`, ... per run).
125pub fn build_command_head(
126    executable: &str,
127    unset_env: &[String],
128    extra_env: &[(String, String)],
129    prefix_args: &[String],
130) -> String {
131    let mut parts = Vec::new();
132
133    if !extra_env.is_empty() || !unset_env.is_empty() {
134        parts.push("env".to_string());
135        for key in unset_env {
136            assert!(
137                is_valid_env_name(key),
138                "invalid environment variable name: {}",
139                key
140            );
141            parts.push(format!("-u {key}"));
142        }
143        for (key, value) in extra_env {
144            assert!(
145                is_valid_env_name(key),
146                "invalid environment variable name: {}",
147                key
148            );
149            parts.push(format!("{}={}", key, escape_arg(value)));
150        }
151    }
152
153    parts.push(escape_arg(executable));
154    parts.extend(prefix_args.iter().map(|arg| escape_arg(arg)));
155    parts.join(" ")
156}