Skip to main content

agentmux_srv_core/agents/
tool_limit.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a Drone Agent block's one-shot `claude` may use (docs/specs/SPEC_DRONE_REAL_WORLD_JOBS_2026_11_11.md ยง5).
5//!
6//! The block's `allow_commands` is the whole answer, and the runner passes it to the CLI as flags:
7//!   - nothing, `false` or an empty list: the tools that read (`Read`, `Grep`, `Glob`) and no MCP server;
8//!   - a command line, or a list of them: those and `Bash` for exactly those command lines, no MCP server, and none of the
9//!     user's, project's or local settings (their `permissions.allow` rules would add to the list);
10//!   - `true`: no limit from AgentMux (the check that turns a job on asks the person about it).
11//!
12//! A tool the CLI is not given is not there for the model to call, and a command line that is not listed is not run
13//! (`--permission-mode dontAsk` answers no to anything that is not allowed, where `--print` has nobody to ask).
14
15use serde_json::Value;
16
17/// The tools a native Agent block may use.
18#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
19#[serde(tag = "kind", rename_all = "snake_case")]
20pub enum ToolLimit {
21    /// The reading tools, and `Bash` for exactly these command lines (none: no `Bash`).
22    Limited { commands: Vec<String> },
23    /// The CLI's own permission settings are the only limit.
24    Unlimited,
25}
26
27impl Default for ToolLimit {
28    /// A task that says nothing about its tools is limited to reading.
29    fn default() -> Self {
30        ToolLimit::Limited { commands: Vec::new() }
31    }
32}
33
34/// The tools that read and change nothing.
35const READING: &str = "Read,Grep,Glob";
36
37impl ToolLimit {
38    /// From a block's `allow_commands`: absent or `false`, a command line, a list of them, or `true`.
39    pub fn from_allow_commands(value: Option<&Value>) -> Self {
40        let line = |s: &str| (!s.trim().is_empty()).then(|| s.trim().to_string());
41        match value {
42            Some(Value::Bool(true)) => ToolLimit::Unlimited,
43            Some(Value::String(s)) => ToolLimit::Limited { commands: line(s).into_iter().collect() },
44            Some(Value::Array(list)) => ToolLimit::Limited { commands: list.iter().filter_map(Value::as_str).filter_map(line).collect() },
45            _ => ToolLimit::default(),
46        }
47    }
48
49    /// The flags that carry the limit to the CLI.
50    pub fn args(&self) -> Vec<String> {
51        let ToolLimit::Limited { commands } = self else { return Vec::new() };
52        let mut args = vec!["--strict-mcp-config".to_string(), "--permission-mode".to_string(), "dontAsk".to_string()];
53        if commands.is_empty() {
54            args.extend(["--tools".to_string(), READING.to_string()]);
55            return args;
56        }
57        // A settings file may allow more than the list, and an allow rule adds to the list instead of replacing it.
58        args.extend(["--setting-sources".to_string(), String::new()]);
59        args.extend(["--tools".to_string(), format!("{READING},Bash")]);
60        args.push("--allowedTools".to_string());
61        args.extend(commands.iter().map(|c| format!("Bash({})", escaped(c))));
62        args
63    }
64}
65
66/// A command line as the CLI's permission rule reads it exactly: a `(`, `)`, `*` or `\` in it is itself.
67fn escaped(command: &str) -> String {
68    let mut out = String::with_capacity(command.len());
69    for c in command.chars() {
70        if matches!(c, '\\' | '(' | ')' | '*') {
71            out.push('\\');
72        }
73        out.push(c);
74    }
75    out
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81    use serde_json::json;
82
83    fn of(v: Value) -> ToolLimit {
84        ToolLimit::from_allow_commands(Some(&v))
85    }
86
87    #[test]
88    fn a_block_with_no_commands_is_limited_to_reading_and_has_no_mcp_server() {
89        for v in [None, Some(json!(false)), Some(json!([])), Some(json!("  ")), Some(Value::Null)] {
90            let args = ToolLimit::from_allow_commands(v.as_ref()).args();
91            assert_eq!(args, ["--strict-mcp-config", "--permission-mode", "dontAsk", "--tools", "Read,Grep,Glob"], "{v:?}");
92            assert!(!args.iter().any(|a| a == "--setting-sources"), "Bash is not there to be allowed by a settings file: {args:?}");
93        }
94    }
95
96    #[test]
97    fn listed_command_lines_are_the_only_commands() {
98        let args = of(json!(["git status", "cargo test (fast)", 7])).args();
99        let sources = args.iter().position(|a| a == "--setting-sources").unwrap();
100        assert_eq!(args[sources + 1], "", "no settings file adds to the list");
101        let tools = args.iter().position(|a| a == "--tools").unwrap();
102        assert_eq!(args[tools + 1], "Read,Grep,Glob,Bash");
103        let allowed = args.iter().position(|a| a == "--allowedTools").unwrap();
104        assert_eq!(args[allowed + 1..], ["Bash(git status)", r"Bash(cargo test \(fast\))"], "a value that is not a line is left out");
105        assert!(args.iter().any(|a| a == "--strict-mcp-config"));
106        assert_eq!(of(json!("make check")).args().last().unwrap(), "Bash(make check)", "a single line is a list of one");
107    }
108
109    #[test]
110    fn a_star_in_a_command_line_is_not_a_pattern() {
111        assert_eq!(escaped(r"rm -rf *"), r"rm -rf \*");
112        assert_eq!(escaped(r"a\b"), r"a\\b");
113    }
114
115    #[test]
116    fn only_true_lifts_the_limit_and_it_adds_no_flag() {
117        assert_eq!(of(json!(true)), ToolLimit::Unlimited);
118        assert!(ToolLimit::Unlimited.args().is_empty());
119        assert_eq!(ToolLimit::default(), ToolLimit::from_allow_commands(None), "a task that says nothing is limited");
120        assert_eq!(of(json!(1)), ToolLimit::default(), "a value of another kind is not a way out");
121    }
122}