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    build_child_environment_passing(parent, inherit_env, env, &[], unset_env, extra_env)
89}
90
91/// [`build_child_environment`] with names always inherited from `parent`.
92///
93/// Each `pass_env` name is copied from `parent` when the base environment
94/// lacks it, before `unset_env` and
95/// `extra_env` apply (the gateway token variable is inherited implicitly,
96/// issue #65).
97///
98/// # Errors
99/// Returns an error for an invalid variable name.
100pub fn build_child_environment_passing(
101    parent: impl IntoIterator<Item = (String, String)>,
102    inherit_env: &InheritEnv,
103    env: Option<&[(String, String)]>,
104    pass_env: &[String],
105    unset_env: &[String],
106    extra_env: &[(String, String)],
107) -> Result<Vec<(String, String)>, String> {
108    let check = |name: &str| {
109        if is_valid_env_name(name) {
110            Ok(())
111        } else {
112            Err(format!("invalid environment variable name: {name}"))
113        }
114    };
115    let parent: Vec<(String, String)> = parent.into_iter().collect();
116    let mut result: Vec<(String, String)> = match env {
117        Some(env) => env.to_vec(),
118        None => match inherit_env {
119            InheritEnv::All => parent.clone(),
120            InheritEnv::None => Vec::new(),
121            InheritEnv::Only(names) => {
122                for name in names {
123                    check(name)?;
124                }
125                parent
126                    .iter()
127                    .filter(|(key, _)| names.contains(key))
128                    .cloned()
129                    .collect()
130            }
131        },
132    };
133    for name in pass_env {
134        check(name)?;
135        if !result.iter().any(|(key, _)| key == name) {
136            if let Some(entry) = parent.iter().find(|(key, _)| key == name) {
137                result.push(entry.clone());
138            }
139        }
140    }
141    for name in unset_env {
142        check(name)?;
143        result.retain(|(key, _)| key != name);
144    }
145    for (key, value) in extra_env {
146        check(key)?;
147        result.retain(|(existing, _)| existing != key);
148        result.push((key.clone(), value.clone()));
149    }
150    Ok(result)
151}
152
153/// Build a command head with optional env vars and executable prefix args;
154/// `unset_env` is removed from the inherited environment (Hive Mind drops `GH_TOKEN`, `MAX_THINKING_TOKENS`, ... per run).
155pub fn build_command_head(
156    executable: &str,
157    unset_env: &[String],
158    extra_env: &[(String, String)],
159    prefix_args: &[String],
160) -> String {
161    let mut parts = Vec::new();
162
163    if !extra_env.is_empty() || !unset_env.is_empty() {
164        parts.push("env".to_string());
165        for key in unset_env {
166            assert!(
167                is_valid_env_name(key),
168                "invalid environment variable name: {}",
169                key
170            );
171            parts.push(format!("-u {key}"));
172        }
173        for (key, value) in extra_env {
174            assert!(
175                is_valid_env_name(key),
176                "invalid environment variable name: {}",
177                key
178            );
179            parts.push(format!("{}={}", key, escape_arg(value)));
180        }
181    }
182
183    parts.push(escape_arg(executable));
184    parts.extend(prefix_args.iter().map(|arg| escape_arg(arg)));
185    parts.join(" ")
186}