Skip to main content

openmoat_core/
arguments.rs

1//! A tool call's arguments as `when:` conditions read them (ADR-113): each
2//! string value with the path of keys that leads to it. The core does no JSON;
3//! the caller flattens what the host sent (the CLI's `arguments.rs`), and the
4//! engine adds what the action itself names (a host tool's path, URL or
5//! command). Bounded: past [`MAX_VALUES`] values the rest are left out and the
6//! arguments are marked cut, which makes a negated condition hold.
7
8/// The most values kept of one call's arguments.
9pub const MAX_VALUES: usize = 1024;
10
11/// The most bytes of one value kept; a longer value is cut there.
12pub const MAX_VALUE_BYTES: usize = 64 * 1024;
13
14/// One call's argument values, each under its key path (`to`, `message.to`),
15/// keys in snake case.
16#[derive(Debug, Clone, Default, PartialEq, Eq)]
17pub struct Arguments {
18    values: Vec<(String, String)>,
19    cut: bool,
20}
21
22impl Arguments {
23    /// No arguments.
24    #[must_use]
25    pub fn new() -> Self {
26        Self::default()
27    }
28
29    /// Add `value` under the keys `path` (outermost first; an array's items
30    /// take the key that holds the array). Past [`MAX_VALUES`] the value is
31    /// left out and the arguments are marked cut.
32    pub fn push(&mut self, path: &[&str], value: &str) {
33        if self.values.len() >= MAX_VALUES {
34            self.cut = true;
35            return;
36        }
37        let key: Vec<String> = path.iter().map(|k| snake(k)).collect();
38        let mut end = value.len().min(MAX_VALUE_BYTES);
39        while !value.is_char_boundary(end) {
40            end -= 1;
41        }
42        self.values.push((key.join("."), value[..end].to_owned()));
43    }
44
45    /// Mark the arguments as not read in full (nested too deep, not parsed).
46    pub fn mark_cut(&mut self) {
47        self.cut = true;
48    }
49
50    /// Whether some values were left out.
51    #[must_use]
52    pub fn is_cut(&self) -> bool {
53        self.cut
54    }
55
56    /// Whether there are no values.
57    #[must_use]
58    pub fn is_empty(&self) -> bool {
59        self.values.is_empty()
60    }
61
62    /// The values under any of `names`, each with its key: a name matches a
63    /// key that is it or ends in `.<name>`; `*` matches every key.
64    pub(crate) fn values_of<'a>(
65        &'a self,
66        names: &'a [String],
67    ) -> impl Iterator<Item = (&'a str, &'a str)> + 'a {
68        self.values
69            .iter()
70            .filter(move |(key, _)| {
71                names.iter().any(|name| {
72                    name == "*"
73                        || key == name
74                        || key
75                            .strip_suffix(name.as_str())
76                            .is_some_and(|head| head.ends_with('.'))
77                })
78            })
79            .map(|(key, value)| (key.as_str(), value.as_str()))
80    }
81
82    /// Every value of `other` added to these.
83    pub(crate) fn extend(&mut self, other: &Self) {
84        for (key, value) in &other.values {
85            if self.values.len() >= MAX_VALUES {
86                self.cut = true;
87                return;
88            }
89            self.values.push((key.clone(), value.clone()));
90        }
91        self.cut |= other.cut;
92    }
93}
94
95/// `key` in snake case: `sourcePath`, `source-path` and `SOURCE_PATH` are all
96/// `source_path`, as the MCP argument scanner spells keys.
97#[must_use]
98pub fn snake(key: &str) -> String {
99    let mut out = String::with_capacity(key.len() + 4);
100    let mut previous_lower = false;
101    for c in key.chars() {
102        if c == '-' {
103            out.push('_');
104            previous_lower = false;
105        } else if c.is_ascii_uppercase() {
106            if previous_lower {
107                out.push('_');
108            }
109            out.push(c.to_ascii_lowercase());
110            previous_lower = false;
111        } else {
112            out.push(c);
113            previous_lower = c.is_ascii_lowercase() || c.is_ascii_digit();
114        }
115    }
116    out
117}
118
119#[cfg(test)]
120mod tests {
121    use super::{Arguments, MAX_VALUES, snake};
122
123    #[test]
124    fn keys_are_snake_case_paths_and_names_match_their_end() {
125        let mut args = Arguments::new();
126        args.push(&["To"], "a@example.com");
127        args.push(&["message", "ccList"], "b@example.com");
128        args.push(&["subject"], "hi");
129        let names = |n: &[&str]| n.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();
130        let to_names = names(&["to"]);
131        let to: Vec<_> = args.values_of(&to_names).collect();
132        assert_eq!(to, [("to", "a@example.com")]);
133        let cc_names = names(&["cc_list"]);
134        let cc: Vec<_> = args.values_of(&cc_names).collect();
135        assert_eq!(cc, [("message.cc_list", "b@example.com")]);
136        assert_eq!(args.values_of(&names(&["*"])).count(), 3);
137        assert_eq!(args.values_of(&names(&["list"])).count(), 0);
138        assert_eq!(snake("sourcePath"), "source_path");
139        assert_eq!(snake("SOURCE-PATH"), "source_path");
140    }
141
142    #[test]
143    fn past_the_limit_values_are_cut() {
144        let mut args = Arguments::new();
145        for n in 0..=MAX_VALUES {
146            args.push(&["v"], &n.to_string());
147        }
148        assert!(args.is_cut());
149        assert_eq!(args.values_of(&["v".to_owned()]).count(), MAX_VALUES);
150    }
151}