aacode-rs 1.8.15

Rust port of the AACode ReAct coding agent, built on fastshell for mobile AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
// Copyright (c) 2026 xiefujin <490021684@qq.com>
// Licensed under GPL-3.0, see LICENSE file for full license terms.

//! Tool schema definitions + conversion to OpenAI/Anthropic native tools.
//!
//! Ported from Python `utils/tool_schemas.py` + `utils/tool_adapter.py`.

use serde_json::{json, Value};

/// JSON-schema primitive type for a parameter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParamType {
    String,
    Integer,
    Number,
    Boolean,
    Array,
    Object,
}

impl ParamType {
    pub fn json_name(&self) -> &'static str {
        match self {
            ParamType::String => "string",
            ParamType::Integer => "integer",
            ParamType::Number => "number",
            ParamType::Boolean => "boolean",
            ParamType::Array => "array",
            ParamType::Object => "object",
        }
    }

    /// Whether a serde_json Value matches this declared type (used for validation).
    pub fn matches(&self, v: &Value) -> bool {
        match self {
            ParamType::String => v.is_string(),
            ParamType::Integer => v.is_i64() || v.is_u64(),
            ParamType::Number => v.is_number(),
            ParamType::Boolean => v.is_boolean(),
            ParamType::Array => v.is_array(),
            ParamType::Object => v.is_object(),
        }
    }

    /// Best-effort coerce a value to this type. LLMs frequently send numbers /
    /// booleans as strings (e.g. `"max_output": "3000"`); non-coercible values
    /// are returned unchanged so validation still reports a clear type error.
    pub fn coerce(&self, v: &Value) -> Value {
        match (self, v) {
            (ParamType::Integer, Value::String(s)) => s
                .trim()
                .parse::<i64>()
                .map(|n| json!(n))
                .unwrap_or_else(|_| v.clone()),
            (ParamType::Number, Value::String(s)) => {
                if let Ok(n) = s.trim().parse::<i64>() {
                    json!(n)
                } else if let Ok(f) = s.trim().parse::<f64>() {
                    json!(f)
                } else {
                    v.clone()
                }
            }
            (ParamType::Boolean, Value::String(s)) => {
                match s.trim().to_ascii_lowercase().as_str() {
                    "true" | "1" | "yes" => json!(true),
                    "false" | "0" | "no" => json!(false),
                    _ => v.clone(),
                }
            }
            _ => v.clone(),
        }
    }
}

/// A single tool parameter definition.
#[derive(Debug, Clone)]
pub struct ToolParameter {
    pub name: &'static str,
    pub ty: ParamType,
    pub required: bool,
    pub description: &'static str,
    /// Alternative names that get normalized to `name`.
    pub aliases: &'static [&'static str],
}

impl ToolParameter {
    pub const fn new(
        name: &'static str,
        ty: ParamType,
        required: bool,
        description: &'static str,
        aliases: &'static [&'static str],
    ) -> Self {
        ToolParameter {
            name,
            ty,
            required,
            description,
            aliases,
        }
    }
}

/// A tool's schema: name, description, parameters.
#[derive(Debug, Clone)]
pub struct ToolSchema {
    pub name: &'static str,
    pub description: &'static str,
    pub parameters: Vec<ToolParameter>,
}

impl ToolSchema {
    pub fn new(
        name: &'static str,
        description: &'static str,
        parameters: Vec<ToolParameter>,
    ) -> Self {
        ToolSchema {
            name,
            description,
            parameters,
        }
    }

    /// Build the JSON-schema `properties` object and `required` array.
    fn json_schema(&self) -> (Value, Vec<Value>) {
        let mut props = serde_json::Map::new();
        let mut required = Vec::new();
        for p in &self.parameters {
            props.insert(
                p.name.to_string(),
                json!({"type": p.ty.json_name(), "description": p.description}),
            );
            if p.required {
                required.push(Value::String(p.name.to_string()));
            }
        }
        (Value::Object(props), required)
    }

    /// OpenAI native tool object.
    pub fn to_openai_tool(&self) -> Value {
        let (props, required) = self.json_schema();
        json!({
            "type": "function",
            "function": {
                "name": self.name,
                "description": self.description,
                "parameters": {
                    "type": "object",
                    "properties": props,
                    "required": required,
                }
            }
        })
    }

    /// Anthropic native tool object.
    pub fn to_anthropic_tool(&self) -> Value {
        let (props, required) = self.json_schema();
        json!({
            "name": self.name,
            "description": self.description,
            "input_schema": {
                "type": "object",
                "properties": props,
                "required": required,
            }
        })
    }

    /// Normalize input params: rewrite known aliases to canonical names.
    pub fn normalize_params(&self, input: &Value) -> Value {
        let obj = match input.as_object() {
            Some(o) => o,
            None => return input.clone(),
        };
        // alias -> canonical
        let mut alias_map: std::collections::HashMap<&str, &str> = std::collections::HashMap::new();
        for p in &self.parameters {
            alias_map.insert(p.name, p.name);
            for a in p.aliases {
                alias_map.insert(a, p.name);
            }
        }
        let mut out = serde_json::Map::new();
        for (k, v) in obj {
            let canonical = alias_map.get(k.as_str()).copied().unwrap_or(k.as_str());
            // Coerce string scalars to the declared numeric/boolean type.
            let coerced = self
                .parameters
                .iter()
                .find(|p| p.name == canonical)
                .map(|p| p.ty.coerce(v))
                .unwrap_or_else(|| v.clone());
            out.insert(canonical.to_string(), coerced);
        }
        Value::Object(out)
    }

    /// Validate (after normalization): required present + type match.
    /// Returns Ok(()) or Err(human message).
    pub fn validate(&self, normalized: &Value) -> std::result::Result<(), String> {
        let obj = normalized.as_object();
        // missing required
        let mut missing = Vec::new();
        for p in &self.parameters {
            if p.required {
                let present = obj.map(|o| o.contains_key(p.name)).unwrap_or(false);
                if !present {
                    missing.push(p.name);
                }
            }
        }
        if !missing.is_empty() {
            let details: Vec<String> = missing
                .iter()
                .map(|m| {
                    let p = self.parameters.iter().find(|p| &p.name == m).unwrap();
                    format!("  • {} ({}): {}", p.name, p.ty.json_name(), p.description)
                })
                .collect();
            return Err(format!(
                "❌ Missing required parameters: {}\n\n📋 Parameter details:\n{}",
                missing.join(", "),
                details.join("\n")
            ));
        }
        // type check present params
        if let Some(o) = obj {
            for p in &self.parameters {
                if let Some(v) = o.get(p.name) {
                    if !v.is_null() && !p.ty.matches(v) {
                        return Err(format!(
                            "Parameter '{}' expected type {}, got a different type",
                            p.name,
                            p.ty.json_name()
                        ));
                    }
                }
            }
        }
        Ok(())
    }

    /// Human-readable documentation for the tool (used in not-found/error hints).
    pub fn documentation(&self) -> String {
        let mut doc = format!(
            "## {}\n\n{}\n\n### Parameters\n",
            self.name, self.description
        );
        for p in &self.parameters {
            let req = if p.required { "required" } else { "optional" };
            let aliases = if p.aliases.is_empty() {
                String::new()
            } else {
                format!(" (aliases: {})", p.aliases.join(", "))
            };
            doc.push_str(&format!(
                "- {}{} ({}, {}): {}\n",
                p.name,
                aliases,
                p.ty.json_name(),
                req,
                p.description
            ));
        }
        doc
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample() -> ToolSchema {
        ToolSchema::new(
            "run_shell",
            "run a shell command",
            vec![
                ToolParameter::new(
                    "command",
                    ParamType::String,
                    true,
                    "the command",
                    &["cmd", "shell", "script", "exec"],
                ),
                ToolParameter::new(
                    "timeout",
                    ParamType::Integer,
                    false,
                    "seconds",
                    &["time_limit"],
                ),
            ],
        )
    }

    #[test]
    fn openai_tool_shape() {
        let t = sample().to_openai_tool();
        assert_eq!(t["type"], "function");
        assert_eq!(t["function"]["name"], "run_shell");
        assert_eq!(
            t["function"]["parameters"]["properties"]["command"]["type"],
            "string"
        );
        assert_eq!(t["function"]["parameters"]["required"][0], "command");
    }

    #[test]
    fn anthropic_tool_shape() {
        let t = sample().to_anthropic_tool();
        assert_eq!(t["name"], "run_shell");
        assert_eq!(
            t["input_schema"]["properties"]["timeout"]["type"],
            "integer"
        );
    }

    #[test]
    fn alias_normalization() {
        let s = sample();
        let n = s.normalize_params(&json!({"cmd": "ls", "time_limit": 5}));
        assert_eq!(n["command"], "ls");
        assert_eq!(n["timeout"], 5);
    }

    #[test]
    fn validate_missing_required() {
        let s = sample();
        let n = s.normalize_params(&json!({"timeout": 5}));
        let err = s.validate(&n).unwrap_err();
        assert!(err.contains("command"));
    }

    #[test]
    fn validate_type_error() {
        let s = sample();
        let n = s.normalize_params(&json!({"command": 123}));
        assert!(s.validate(&n).is_err());
    }

    #[test]
    fn validate_ok() {
        let s = sample();
        let n = s.normalize_params(&json!({"command": "ls", "timeout": 5}));
        assert!(s.validate(&n).is_ok());
    }

    #[test]
    fn normalize_coerces_string_scalars_to_declared_types() {
        let s = ToolSchema::new(
            "t",
            "d",
            vec![
                ToolParameter::new("n", ParamType::Integer, false, "", &[]),
                ToolParameter::new("f", ParamType::Number, false, "", &[]),
                ToolParameter::new("b", ParamType::Boolean, false, "", &[]),
            ],
        );
        let out = s.normalize_params(&json!({"n": "3000", "f": "1.5", "b": "true"}));
        assert_eq!(out["n"], json!(3000));
        assert_eq!(out["f"], json!(1.5));
        assert_eq!(out["b"], json!(true));
        assert!(s.validate(&out).is_ok(), "coerced params must validate");
        // Non-coercible strings are left as-is (validation then reports a clear error).
        let out = s.normalize_params(&json!({"n": "abc"}));
        assert_eq!(out["n"], json!("abc"));
        assert!(s.validate(&out).is_err());
    }

    #[test]
    fn coerce_handles_whitespace_and_word_booleans() {
        assert_eq!(ParamType::Integer.coerce(&json!(" 42 ")), json!(42));
        assert_eq!(ParamType::Number.coerce(&json!("42")), json!(42));
        assert_eq!(ParamType::Number.coerce(&json!("2.5")), json!(2.5));
        assert_eq!(ParamType::Boolean.coerce(&json!(" YES ")), json!(true));
        assert_eq!(ParamType::Boolean.coerce(&json!("no")), json!(false));
        assert_eq!(ParamType::Boolean.coerce(&json!("1")), json!(true));
        // Non-coercible values are returned unchanged.
        assert_eq!(ParamType::Boolean.coerce(&json!("maybe")), json!("maybe"));
        assert_eq!(ParamType::Integer.coerce(&json!(3.5)), json!(3.5));
    }

    #[test]
    fn normalize_passthrough_for_non_objects() {
        let s = sample();
        assert_eq!(s.normalize_params(&json!([1, 2])), json!([1, 2]));
        assert_eq!(s.normalize_params(&json!("x")), json!("x"));
        assert_eq!(s.normalize_params(&json!(null)), json!(null));
    }

    #[test]
    fn validate_null_optional_is_ok() {
        let s = sample();
        let n = s.normalize_params(&json!({"command": "ls", "timeout": null}));
        assert!(s.validate(&n).is_ok());
    }

    #[test]
    fn documentation_lists_params_and_aliases() {
        let doc = sample().documentation();
        assert!(doc.contains("run_shell"));
        assert!(doc.contains("command"));
        assert!(doc.contains("aliases: cmd"));
        assert!(doc.contains("required"));
    }
}