clawgarden-agent 0.17.0

Agent runtime with persona/memory loader, judge, and pi RPC for ClawGarden
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//! LLM response parser — Function Calling parsing
//!
//! Extracts structured actions from OpenAI Function Calling responses.

/// Structured action extracted from LLM response
#[derive(Debug, Clone, PartialEq)]
pub enum ToolCallAction {
    /// Regular text response
    Message { content: String },
    /// Silence (do not respond)
    Silence,
    /// Execute local command (exec tool)
    Exec {
        command: String,
        workdir: Option<String>,
        timeout_secs: Option<u64>,
    },
    /// Read file (read_file tool)
    ReadFile { path: String },
    /// Create new skill
    SkillCreate {
        skill_name: String,
        description: String,
        body: String,
    },
}

/// LLM response parser
pub struct ResponseParser;

impl ResponseParser {
    /// Strip `<think ...>...</think reasoning>` blocks.
    /// Some models like MiniMAX output reasoning in these tags.
    pub fn strip_thinking(content: &str) -> String {
        let mut result = content.to_string();

        // Find and remove all <think...>...</think> blocks
        while let Some(start) = result.find("<think") {
            if let Some(tag_end) = result[start..].find('>') {
                let content_start = start + tag_end + 1;

                // Try MiniMAX official closing tag first
                if let Some(end) = result[content_start..].find("</think reasoning>") {
                    result = format!(
                        "{}{}",
                        &result[..start],
                        &result[content_start + end + "</think reasoning>".len()..]
                    );
                    continue;
                }

                // Try generic </think...> closing tag
                if let Some(end) = result[content_start..].find("</think") {
                    let remainder = &result[content_start + end..];
                    if let Some(close_pos) = remainder.find('>') {
                        result = format!(
                            "{}{}",
                            &result[..start],
                            &result[content_start + end + close_pos + 1..]
                        );
                        continue;
                    }
                }

                // No closing tag found — remove everything from start
                result = result[..start].to_string();
            }
            break;
        }

        result.trim().to_string()
    }

    /// Convert OpenAI Function Calling tool_calls array to ToolCallAction.
    /// Returns None if `tool_calls` is empty or None.
    pub fn parse_tool_calls(tool_calls: &[serde_json::Value]) -> Option<ToolCallAction> {
        let tc = tool_calls.first()?;

        let function = tc.get("function")?;
        let name = function.get("name")?.as_str()?;
        let arguments = function
            .get("arguments")
            .and_then(|a| a.as_str())
            .unwrap_or("{}");

        match name {
            "respond" => {
                let args: serde_json::Value = serde_json::from_str(arguments).ok()?;
                let silent = args.get("silent").and_then(|v| v.as_bool()).unwrap_or(false);
                if silent {
                    return Some(ToolCallAction::Silence);
                }
                let text = args
                    .get("text")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                if text.is_empty() {
                    return Some(ToolCallAction::Silence);
                }
                Some(ToolCallAction::Message { content: text })
            }
            "exec" => {
                let args: serde_json::Value = serde_json::from_str(arguments).ok()?;
                let command = args.get("command")?.as_str()?.to_string();
                if command.is_empty() {
                    return None;
                }
                let workdir = args.get("workdir").and_then(|v| v.as_str()).map(String::from);
                let timeout_secs = args.get("timeout").and_then(|v| v.as_u64());
                Some(ToolCallAction::Exec {
                    command,
                    workdir,
                    timeout_secs,
                })
            }
            "read_file" => {
                let args: serde_json::Value = serde_json::from_str(arguments).ok()?;
                let path = args.get("path")?.as_str()?.to_string();
                if path.is_empty() {
                    return None;
                }
                Some(ToolCallAction::ReadFile { path })
            }
            "create_skill" => {
                let args: serde_json::Value = serde_json::from_str(arguments).ok()?;
                let skill_name = args.get("skill_name")?.as_str()?.to_string();
                if skill_name.is_empty() {
                    return None;
                }
                let description = args.get("description").and_then(|v| v.as_str()).unwrap_or("").to_string();
                let body = args.get("body").and_then(|v| v.as_str()).unwrap_or("").to_string();
                Some(ToolCallAction::SkillCreate {
                    skill_name,
                    description,
                    body,
                })
            }
            _ => None,
        }
    }

    /// Strip leaked tool-call text that some models emit as plain text
    /// instead of proper Function Calling (e.g. "respond(silent=true)").
    pub fn strip_leaked_tool_calls(content: &str) -> String {
        let tool_names = ["respond", "exec", "read_file", "create_skill"];
        let lines: Vec<&str> = content
            .lines()
            .filter(|line| {
                let trimmed = line.trim();
                if trimmed.is_empty() {
                    return false; // remove blank lines too
                }
                for name in &tool_names {
                    if trimmed.starts_with(name) {
                        let rest = trimmed[name.len()..].trim_start();
                        if rest.starts_with('(') {
                            return false; // leaked tool call
                        }
                    }
                }
                true
            })
            .collect();
        lines.join("\n").trim().to_string()
    }

    /// Fallback text response when Function Calling is not available.
    /// Strips thinking blocks and leaked tool-call text.
    pub fn text_fallback(content: &str) -> ToolCallAction {
        let cleaned = Self::strip_thinking(content);
        let cleaned = Self::strip_leaked_tool_calls(&cleaned);
        if cleaned.is_empty() {
            ToolCallAction::Silence
        } else {
            ToolCallAction::Message { content: cleaned }
        }
    }
}

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

    // ── strip_thinking ────────────────────────────────

    #[test]
    fn test_strip_thinking_basic() {
        let input = "<think reasoning>Hello</think reasoning>World";
        assert_eq!(ResponseParser::strip_thinking(input), "World");
    }

    #[test]
    fn test_strip_thinking_multiline() {
        let input = "<think reasoning>\nLine 1\nLine 2\n</think reasoning>\nActual response";
        assert_eq!(ResponseParser::strip_thinking(input), "Actual response");
    }

    #[test]
    fn test_strip_thinking_no_tag() {
        let input = "Just a normal response";
        assert_eq!(
            ResponseParser::strip_thinking(input),
            "Just a normal response"
        );
    }

    #[test]
    fn test_strip_thinking_empty_after_strip() {
        let input = "<think reasoning>internal</think reasoning>";
        assert_eq!(ResponseParser::strip_thinking(input), "");
    }

    #[test]
    fn test_strip_thinking_variant_no_space() {
        let input = "<think reasoning>Hello\n</think reasoning>\n\nWorld";
        assert_eq!(ResponseParser::strip_thinking(input), "World");
    }

    #[test]
    fn test_strip_thinking_variant_with_space() {
        let input = "<think >Hello</think >World";
        assert_eq!(ResponseParser::strip_thinking(input), "World");
    }

    #[test]
    fn test_strip_thinking_variant_with_type() {
        let input = "<think type=\"deep\">Hello</think type=\"deep\">World";
        assert_eq!(ResponseParser::strip_thinking(input), "World");
    }

    #[test]
    fn test_strip_thinking_multiple_blocks() {
        let input = "Start <think>think1</think> middle <think>think2</think> end";
        assert_eq!(ResponseParser::strip_thinking(input), "Start  middle  end");
    }

    // ── parse_tool_calls (Function Calling) ──────────

    #[test]
    fn test_parse_tool_calls_respond() {
        // Build the arguments as a JSON string (as LLM would output)
        let arguments_str = r#"{"text": "Hello!"}"#;
        let tool_calls = vec![serde_json::json!({
            "id": "call_1",
            "type": "function",
            "function": {
                "name": "respond",
                "arguments": arguments_str
            }
        })];
        let action = ResponseParser::parse_tool_calls(&tool_calls).unwrap();
        assert_eq!(
            action,
            ToolCallAction::Message {
                content: "Hello!".to_string()
            }
        );
    }

    #[test]
    fn test_parse_tool_calls_silence() {
        let tool_calls = vec![serde_json::json!({
            "id": "call_1",
            "type": "function",
            "function": {
                "name": "respond",
                "arguments": "{\"silent\": true}"
            }
        })];
        let action = ResponseParser::parse_tool_calls(&tool_calls).unwrap();
        assert_eq!(action, ToolCallAction::Silence);
    }

    #[test]
    fn test_parse_tool_calls_exec() {
        let tool_calls = vec![serde_json::json!({
            "id": "call_exec_1",
            "type": "function",
            "function": {
                "name": "exec",
                "arguments": "{\"command\": \"rg 'fn main' /workspace --type rust -n\"}"
            }
        })];
        let action = ResponseParser::parse_tool_calls(&tool_calls).unwrap();
        match action {
            ToolCallAction::Exec { command, .. } => {
                assert_eq!(command, "rg 'fn main' /workspace --type rust -n");
            }
            _ => panic!("Expected Exec, got {:?}", action),
        }
    }

    #[test]
    fn test_parse_tool_calls_exec_with_workdir() {
        let tool_calls = vec![serde_json::json!({
            "id": "call_exec_2",
            "type": "function",
            "function": {
                "name": "exec",
                "arguments": "{\"command\": \"ls -la\", \"workdir\": \"/workspace/src\"}"
            }
        })];
        let action = ResponseParser::parse_tool_calls(&tool_calls).unwrap();
        match action {
            ToolCallAction::Exec {
                command, workdir, ..
            } => {
                assert_eq!(command, "ls -la");
                assert_eq!(workdir, Some("/workspace/src".to_string()));
            }
            _ => panic!("Expected Exec"),
        }
    }

    #[test]
    fn test_parse_tool_calls_exec_empty_command() {
        let tool_calls = vec![serde_json::json!({
            "id": "call_exec_3",
            "type": "function",
            "function": {
                "name": "exec",
                "arguments": "{\"command\": \"\"}"
            }
        })];
        let action = ResponseParser::parse_tool_calls(&tool_calls);
        assert!(action.is_none());
    }

    #[test]
    fn test_parse_tool_calls_read_file() {
        let tool_calls = vec![serde_json::json!({
            "id": "call_read_1",
            "type": "function",
            "function": {
                "name": "read_file",
                "arguments": "{\"path\": \"/workspace/skills/code_search/SKILL.md\"}"
            }
        })];
        let action = ResponseParser::parse_tool_calls(&tool_calls).unwrap();
        match action {
            ToolCallAction::ReadFile { path } => {
                assert_eq!(path, "/workspace/skills/code_search/SKILL.md");
            }
            _ => panic!("Expected ReadFile, got {:?}", action),
        }
    }

    #[test]
    fn test_parse_tool_calls_read_file_empty_path() {
        let tool_calls = vec![serde_json::json!({
            "id": "call_read_2",
            "type": "function",
            "function": {
                "name": "read_file",
                "arguments": "{\"path\": \"\"}"
            }
        })];
        let action = ResponseParser::parse_tool_calls(&tool_calls);
        assert!(action.is_none());
    }

    #[test]
    fn test_parse_tool_calls_skill_create() {
        let tool_calls = vec![serde_json::json!({
            "id": "call_3",
            "type": "function",
            "function": {
                "name": "create_skill",
                "arguments": "{\"skill_name\": \"checker\", \"description\": \"Check things\", \"body\": \"# Checker\\nBody\"}"
            }
        })];
        let action = ResponseParser::parse_tool_calls(&tool_calls).unwrap();
        match action {
            ToolCallAction::SkillCreate {
                skill_name,
                description,
                body,
            } => {
                assert_eq!(skill_name, "checker");
                assert_eq!(description, "Check things");
                assert!(body.contains("Checker"));
            }
            _ => panic!("Expected SkillCreate"),
        }
    }

    #[test]
    fn test_parse_tool_calls_empty() {
        let action = ResponseParser::parse_tool_calls(&[]);
        assert!(action.is_none());
    }

    #[test]
    fn test_parse_tool_calls_unknown_function() {
        let tool_calls = vec![serde_json::json!({
            "id": "call_x",
            "type": "function",
            "function": {
                "name": "unknown_func",
                "arguments": "{}"
            }
        })];
        let action = ResponseParser::parse_tool_calls(&tool_calls);
        assert!(action.is_none());
    }

    #[test]
    fn test_parse_tool_calls_malformed_json() {
        let tool_calls = vec![serde_json::json!({
            "id": "call_1",
            "type": "function",
            "function": {
                "name": "respond",
                "arguments": "not valid json"
            }
        })];
        let action = ResponseParser::parse_tool_calls(&tool_calls);
        assert!(action.is_none());
    }

    // ── text_fallback ───────────────────────────

    #[test]
    fn test_text_fallback_with_content() {
        let action = ResponseParser::text_fallback("Hello world!");
        assert_eq!(
            action,
            ToolCallAction::Message {
                content: "Hello world!".to_string()
            }
        );
    }

    #[test]
    fn test_text_fallback_empty() {
        let action = ResponseParser::text_fallback("");
        assert_eq!(action, ToolCallAction::Silence);
    }

    #[test]
    fn test_text_fallback_with_thinking() {
        let action = ResponseParser::text_fallback("<think>reasoning</think>Actual response");
        assert_eq!(
            action,
            ToolCallAction::Message {
                content: "Actual response".to_string()
            }
        );
    }

    #[test]
    fn test_text_fallback_whitespace_only() {
        let action = ResponseParser::text_fallback("   \n\t  ");
        assert_eq!(action, ToolCallAction::Silence);
    }

    // ── strip_leaked_tool_calls ──────────────

    #[test]
    fn test_strip_leaked_respond_silent() {
        let action = ResponseParser::text_fallback("respond(silent=true)");
        assert_eq!(action, ToolCallAction::Silence);
    }

    #[test]
    fn test_strip_leaked_respond_mixed() {
        let action = ResponseParser::text_fallback("Hello!\nrespond(silent=true)");
        assert_eq!(
            action,
            ToolCallAction::Message { content: "Hello!".to_string() }
        );
    }

    #[test]
    fn test_strip_leaked_exec() {
        let action = ResponseParser::text_fallback("exec(\"ls -la\")");
        assert_eq!(action, ToolCallAction::Silence);
    }

    #[test]
    fn test_strip_leaked_preserves_normal_text() {
        let action = ResponseParser::text_fallback("This is a normal response about executing code.");
        assert_eq!(
            action,
            ToolCallAction::Message { content: "This is a normal response about executing code.".to_string() }
        );
    }
}