mermaid-model 0.30.0

Model-layer core for Mermaid: provider adapters, wire types, capability catalog, and the shared utilities they need.
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Anthropic's own tools: the text editor and bash.
//!
//! Claude is trained on these two definitions, so sending them beats any
//! schema Mermaid writes, and they improve with each model without Mermaid
//! changing. They are declared by `type` alone; the model knows the input
//! shape.
//!
//! Only the wire changes. A native call is rewritten onto the Mermaid tool it
//! stands for as it arrives (`str_replace` becomes `edit_file`, `bash`
//! becomes `execute_command`), so the policy gate, the read-only sandbox,
//! checkpoints, approvals and the transcript all see a tool they already
//! know. The ids of those calls ride on the turn's continuation, and history
//! sends them back in the native form the model wrote.
//!
//! `bash` sits beside `execute_command` rather than replacing it: the native
//! tool has no timeout or background mode, and servers still need both.

use serde_json::{Value, json};

use super::computer_toolset;
use crate::constants::COMMAND_MAX_TIMEOUT_SECS;
use crate::models::config::NativeTools;
use crate::models::tool_call::FunctionCall;

pub(super) const TEXT_EDITOR_NAME: &str = "str_replace_based_edit_tool";
const TEXT_EDITOR_TYPE: &str = "text_editor_20250728";
pub(super) const BASH_NAME: &str = "bash";
const BASH_TYPE: &str = "bash_20250124";

/// What a refusal of these tools is remembered as, and the words it names
/// them by.
pub(super) const REJECTION: &str = "native_tools";
pub(super) const REJECTION_NAMES: &[&str] = &[
    TEXT_EDITOR_TYPE,
    BASH_TYPE,
    TEXT_EDITOR_NAME,
    "text_editor_",
    "bash_",
];

/// The Mermaid tools the text editor stands in for. All three must be
/// registered: an editor offering `create` to a registry without
/// `write_file` would promise what the harness cannot do.
const EDITOR_TOOLS: [&str; 3] = ["read_file", "write_file", "edit_file"];
const SHELL_TOOL: &str = "execute_command";

/// The native tools one request actually advertises.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(super) struct Advertised {
    pub(super) text_editor: bool,
    pub(super) bash: bool,
    pub(super) computer: bool,
}

impl Advertised {
    /// What `wanted` allows, given the Mermaid tools this request carries.
    pub(super) fn resolve(wanted: NativeTools, registered: &[&str]) -> Self {
        Self {
            text_editor: wanted.text_editor && EDITOR_TOOLS.iter().all(|t| registered.contains(t)),
            bash: wanted.shell && registered.contains(&SHELL_TOOL),
            computer: wanted.computer && registered.contains(&computer_toolset::TOOL),
        }
    }

    /// Without the computer toolset: what a model that refused it is offered.
    pub(super) fn without_computer(self) -> Self {
        Self {
            computer: false,
            ..self
        }
    }

    /// Without the text editor and bash: what a model that refused them is
    /// offered.
    pub(super) fn without_editor_and_bash(self) -> Self {
        Self {
            text_editor: false,
            bash: false,
            ..self
        }
    }

    /// Whether the Mermaid tool `name` goes out as its native stand-in
    /// instead of its own schema.
    pub(super) fn replaces(self, name: &str) -> bool {
        (self.text_editor && EDITOR_TOOLS.contains(&name))
            || (self.computer && name == computer_toolset::TOOL)
    }

    /// The `tools` entries to send.
    pub(super) fn declarations(self) -> Vec<Value> {
        let mut out = Vec::new();
        if self.text_editor {
            out.push(json!({"type": TEXT_EDITOR_TYPE, "name": TEXT_EDITOR_NAME}));
        }
        if self.bash {
            out.push(json!({"type": BASH_TYPE, "name": BASH_NAME}));
        }
        if self.computer {
            out.push(computer_toolset::declaration());
        }
        out
    }

    /// The member call a `computer` call was rewritten from, when the
    /// toolset is on offer in this request.
    pub(super) fn to_computer_member(self, call: &FunctionCall) -> Option<(String, Value)> {
        self.computer
            .then(|| computer_toolset::to_native(call))
            .flatten()
    }

    /// `call` in the native form, when it was made natively and that tool is
    /// on offer in this request.
    pub(super) fn to_native(self, call: &FunctionCall) -> Option<(&'static str, Value)> {
        let (name, input) = to_native(call)?;
        let offered = match name {
            TEXT_EDITOR_NAME => self.text_editor,
            _ => self.bash,
        };
        offered.then_some((name, input))
    }
}

/// Rewrite a native call onto the Mermaid tool it stands for. `false` when
/// `call` is not a native call, or is one whose input names no operation
/// Mermaid can run; it is left untouched then, and the registry answers it
/// with the reason.
pub(super) fn canonicalize(call: &mut FunctionCall) -> bool {
    let translated = match call.name.as_str() {
        TEXT_EDITOR_NAME => editor_to_canonical(&call.arguments),
        BASH_NAME => bash_to_canonical(&call.arguments),
        _ => None,
    };
    let Some((name, arguments)) = translated else {
        return false;
    };
    call.name = name.to_string();
    call.arguments = arguments;
    true
}

fn str_field<'a>(input: &'a Value, key: &str) -> Option<&'a str> {
    input.get(key).and_then(Value::as_str)
}

fn editor_to_canonical(input: &Value) -> Option<(&'static str, Value)> {
    let path = str_field(input, "path")?;
    match str_field(input, "command")? {
        "view" => {
            let mut args = json!({"path": path, "line_numbers": true});
            if let Some(range) = input.get("view_range").filter(|r| !r.is_null()) {
                args["view_range"] = range.clone();
            }
            Some(("read_file", args))
        },
        "create" => Some((
            "write_file",
            json!({"path": path, "content": str_field(input, "file_text")?}),
        )),
        "str_replace" => Some((
            "edit_file",
            json!({
                "path": path,
                "target_content": str_field(input, "old_str")?,
                // An absent `new_str` deletes the match.
                "replacement_content": str_field(input, "new_str").unwrap_or_default(),
            }),
        )),
        "insert" => Some((
            "edit_file",
            json!({
                "path": path,
                "insert_line": input.get("insert_line")?.as_u64()?,
                "replacement_content": str_field(input, "insert_text")
                    .or_else(|| str_field(input, "new_str"))?,
            }),
        )),
        _ => None,
    }
}

fn bash_to_canonical(input: &Value) -> Option<(&'static str, Value)> {
    if input.get("restart").and_then(Value::as_bool) == Some(true) {
        return Some((SHELL_TOOL, json!({"restart": true})));
    }
    // The native tool has no timeout of its own, so a build must not die at
    // the short default: it gets the longest foreground run there is.
    Some((
        SHELL_TOOL,
        json!({
            "command": str_field(input, "command")?,
            "timeout": COMMAND_MAX_TIMEOUT_SECS,
        }),
    ))
}

/// Why a native call that reached the tool runner untranslated ran nothing:
/// its input named no operation Mermaid runs. `None` for any other tool.
#[must_use]
pub fn unrunnable(name: &str) -> Option<&'static str> {
    match name {
        TEXT_EDITOR_NAME => Some(
            "nothing ran: Mermaid runs the text editor's view (path, optional \
             view_range), create (path, file_text), str_replace (path, old_str, \
             new_str) and insert (path, insert_line, insert_text) commands, and this \
             call is none of them with its required fields",
        ),
        BASH_NAME => Some("nothing ran: a bash call needs `command`, or `restart: true`"),
        _ => None,
    }
}

/// The native form of a call [`canonicalize`] produced.
fn to_native(call: &FunctionCall) -> Option<(&'static str, Value)> {
    let args = &call.arguments;
    let path = || str_field(args, "path");
    match call.name.as_str() {
        "read_file" => {
            let mut input = json!({"command": "view", "path": path()?});
            if let Some(range) = args.get("view_range") {
                input["view_range"] = range.clone();
            }
            Some((TEXT_EDITOR_NAME, input))
        },
        "write_file" => Some((
            TEXT_EDITOR_NAME,
            json!({
                "command": "create",
                "path": path()?,
                "file_text": str_field(args, "content")?,
            }),
        )),
        "edit_file" => {
            let text = str_field(args, "replacement_content")?;
            let input = match args.get("insert_line") {
                Some(line) => json!({
                    "command": "insert",
                    "path": path()?,
                    "insert_line": line,
                    "insert_text": text,
                }),
                None => json!({
                    "command": "str_replace",
                    "path": path()?,
                    "old_str": str_field(args, "target_content")?,
                    "new_str": text,
                }),
            };
            Some((TEXT_EDITOR_NAME, input))
        },
        SHELL_TOOL if args.get("restart").is_some() => Some((BASH_NAME, json!({"restart": true}))),
        SHELL_TOOL => Some((BASH_NAME, json!({"command": str_field(args, "command")?}))),
        _ => None,
    }
}

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

    fn call(name: &str, arguments: Value) -> FunctionCall {
        FunctionCall {
            name: name.to_string(),
            arguments,
        }
    }

    fn all() -> NativeTools {
        NativeTools {
            text_editor: true,
            shell: true,
            computer: false,
        }
    }

    const FULL: [&str; 5] = [
        "read_file",
        "write_file",
        "edit_file",
        "apply_patch",
        "execute_command",
    ];

    #[test]
    fn each_native_command_maps_onto_the_tool_it_stands_for() {
        let cases = [
            (
                json!({"command": "view", "path": "a.rs"}),
                "read_file",
                json!({"path": "a.rs", "line_numbers": true}),
            ),
            (
                json!({"command": "view", "path": "a.rs", "view_range": [3, -1]}),
                "read_file",
                json!({"path": "a.rs", "line_numbers": true, "view_range": [3, -1]}),
            ),
            (
                json!({"command": "create", "path": "n.rs", "file_text": "x\n"}),
                "write_file",
                json!({"path": "n.rs", "content": "x\n"}),
            ),
            (
                json!({"command": "str_replace", "path": "a.rs", "old_str": "a", "new_str": "b"}),
                "edit_file",
                json!({"path": "a.rs", "target_content": "a", "replacement_content": "b"}),
            ),
            (
                json!({"command": "str_replace", "path": "a.rs", "old_str": "a"}),
                "edit_file",
                json!({"path": "a.rs", "target_content": "a", "replacement_content": ""}),
            ),
            (
                json!({"command": "insert", "path": "a.rs", "insert_line": 0, "insert_text": "top\n"}),
                "edit_file",
                json!({"path": "a.rs", "insert_line": 0, "replacement_content": "top\n"}),
            ),
        ];
        for (input, name, args) in cases {
            let mut c = call(TEXT_EDITOR_NAME, input.clone());
            assert!(canonicalize(&mut c), "{input}");
            assert_eq!(c.name, name, "{input}");
            assert_eq!(c.arguments, args, "{input}");
        }
    }

    #[test]
    fn bash_runs_through_execute_command_with_the_longest_timeout() {
        let mut c = call(BASH_NAME, json!({"command": "cargo build"}));
        assert!(canonicalize(&mut c));
        assert_eq!(c.name, "execute_command");
        assert_eq!(
            c.arguments,
            json!({"command": "cargo build", "timeout": COMMAND_MAX_TIMEOUT_SECS})
        );
        let mut restart = call(BASH_NAME, json!({"restart": true}));
        assert!(canonicalize(&mut restart));
        assert_eq!(restart.arguments, json!({"restart": true}));
    }

    #[test]
    fn a_call_mermaid_cannot_run_is_left_for_the_registry_to_answer() {
        for input in [
            json!({"command": "undo_edit", "path": "a.rs"}),
            json!({"command": "create", "path": "a.rs"}),
            json!({"command": "view"}),
        ] {
            let mut c = call(TEXT_EDITOR_NAME, input.clone());
            assert!(!canonicalize(&mut c), "{input}");
            assert_eq!(c.name, TEXT_EDITOR_NAME);
            assert_eq!(c.arguments, input);
        }
        let mut other = call("read_file", json!({"path": "a"}));
        assert!(!canonicalize(&mut other));
        assert_eq!(other.name, "read_file");
    }

    #[test]
    fn history_gets_back_exactly_what_the_model_sent() {
        let adv = Advertised::resolve(all(), &FULL);
        for (name, input) in [
            (TEXT_EDITOR_NAME, json!({"command": "view", "path": "a.rs"})),
            (
                TEXT_EDITOR_NAME,
                json!({"command": "view", "path": "a.rs", "view_range": [1, 9]}),
            ),
            (
                TEXT_EDITOR_NAME,
                json!({"command": "create", "path": "n.rs", "file_text": "x"}),
            ),
            (
                TEXT_EDITOR_NAME,
                json!({"command": "str_replace", "path": "a", "old_str": "o", "new_str": "n"}),
            ),
            (
                TEXT_EDITOR_NAME,
                json!({"command": "insert", "path": "a", "insert_line": 4, "insert_text": "t"}),
            ),
            (BASH_NAME, json!({"command": "ls"})),
            (BASH_NAME, json!({"restart": true})),
        ] {
            let mut c = call(name, input.clone());
            assert!(canonicalize(&mut c));
            assert_eq!(adv.to_native(&c), Some((name, input)));
        }
    }

    #[test]
    fn the_editor_needs_every_tool_it_stands_for() {
        let adv = Advertised::resolve(all(), &["read_file", "execute_command"]);
        assert!(!adv.text_editor, "a read-only toolset cannot offer create");
        assert!(adv.bash);
        assert!(!adv.replaces("read_file"));
        assert_eq!(adv.declarations().len(), 1);

        let none = Advertised::resolve(NativeTools::default(), &FULL);
        assert_eq!(none, Advertised::default());
        assert!(none.declarations().is_empty());
    }

    #[test]
    fn declarations_carry_only_type_and_name() {
        let adv = Advertised::resolve(all(), &FULL);
        assert_eq!(
            adv.declarations(),
            vec![
                json!({"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}),
                json!({"type": "bash_20250124", "name": "bash"}),
            ]
        );
        assert!(adv.replaces("edit_file"));
        assert!(!adv.replaces("execute_command"), "bash sits beside it");
        assert!(!adv.replaces("apply_patch"));
    }

    #[test]
    fn a_call_is_replayed_natively_only_while_its_tool_is_offered() {
        let mut c = call(BASH_NAME, json!({"command": "ls"}));
        assert!(canonicalize(&mut c));
        let editor_only = Advertised::resolve(
            NativeTools {
                text_editor: true,
                shell: false,
                computer: false,
            },
            &FULL,
        );
        assert_eq!(editor_only.to_native(&c), None);
    }
}