agents-toolkit 0.0.30

Reusable tools and utilities for Rust deep 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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Built-in filesystem tools for agent file manipulation
//!
//! These tools provide a mock filesystem interface that agents can use to
//! read, write, and edit files stored in the agent state.

use agents_core::command::StateDiff;
use agents_core::tools::{Tool, ToolBox, ToolContext, ToolParameterSchema, ToolResult, ToolSchema};
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::Value;
use std::collections::{BTreeMap, HashMap};

/// List files tool - shows all files in the agent's filesystem
pub struct LsTool;

#[async_trait]
impl Tool for LsTool {
    fn schema(&self) -> ToolSchema {
        ToolSchema::no_params("ls", "List all files in the filesystem")
    }

    async fn execute(&self, _args: Value, ctx: ToolContext) -> anyhow::Result<ToolResult> {
        let files: Vec<String> = ctx.state.files.keys().cloned().collect();
        Ok(ToolResult::json(&ctx, serde_json::json!(files)))
    }
}

/// Read file tool - reads the contents of a file
pub struct ReadFileTool;

#[derive(Deserialize)]
struct ReadFileArgs {
    #[serde(rename = "file_path")]
    path: String,
    #[serde(default)]
    offset: usize,
    #[serde(default = "default_limit")]
    limit: usize,
}

const fn default_limit() -> usize {
    2000
}

#[async_trait]
impl Tool for ReadFileTool {
    fn schema(&self) -> ToolSchema {
        let mut properties = HashMap::new();
        properties.insert(
            "file_path".to_string(),
            ToolParameterSchema::string("Path to the file to read"),
        );
        properties.insert(
            "offset".to_string(),
            ToolParameterSchema::integer("Line number to start reading from (default: 0)"),
        );
        properties.insert(
            "limit".to_string(),
            ToolParameterSchema::integer("Maximum number of lines to read (default: 2000)"),
        );

        ToolSchema::new(
            "read_file",
            "Read the contents of a file with optional line offset and limit",
            ToolParameterSchema::object(
                "Read file parameters",
                properties,
                vec!["file_path".to_string()],
            ),
        )
    }

    async fn execute(&self, args: Value, ctx: ToolContext) -> anyhow::Result<ToolResult> {
        let args: ReadFileArgs = serde_json::from_value(args)?;

        let Some(contents) = ctx.state.files.get(&args.path) else {
            return Ok(ToolResult::text(
                &ctx,
                format!("Error: File '{}' not found", args.path),
            ));
        };

        if contents.trim().is_empty() {
            return Ok(ToolResult::text(
                &ctx,
                "System reminder: File exists but has empty contents",
            ));
        }

        let lines: Vec<&str> = contents.lines().collect();
        if args.offset >= lines.len() {
            return Ok(ToolResult::text(
                &ctx,
                format!(
                    "Error: Line offset {} exceeds file length ({} lines)",
                    args.offset,
                    lines.len()
                ),
            ));
        }

        let end = (args.offset + args.limit).min(lines.len());
        let mut formatted = String::new();
        for (idx, line) in lines[args.offset..end].iter().enumerate() {
            let line_number = args.offset + idx + 1;
            let mut content = line.to_string();
            if content.len() > args.limit {
                let mut truncate_at = args.limit;
                while !content.is_char_boundary(truncate_at) {
                    truncate_at -= 1;
                }
                content.truncate(truncate_at);
            }
            formatted.push_str(&format!("{:6}\t{}\n", line_number, content));
        }

        Ok(ToolResult::text(&ctx, formatted.trim_end().to_string()))
    }
}

/// Write file tool - creates or overwrites a file
pub struct WriteFileTool;

#[derive(Deserialize)]
struct WriteFileArgs {
    #[serde(rename = "file_path")]
    path: String,
    content: String,
}

#[async_trait]
impl Tool for WriteFileTool {
    fn schema(&self) -> ToolSchema {
        let mut properties = HashMap::new();
        properties.insert(
            "file_path".to_string(),
            ToolParameterSchema::string("Path to the file to write"),
        );
        properties.insert(
            "content".to_string(),
            ToolParameterSchema::string("Content to write to the file"),
        );

        ToolSchema::new(
            "write_file",
            "Write content to a file (creates new or overwrites existing)",
            ToolParameterSchema::object(
                "Write file parameters",
                properties,
                vec!["file_path".to_string(), "content".to_string()],
            ),
        )
    }

    async fn execute(&self, args: Value, ctx: ToolContext) -> anyhow::Result<ToolResult> {
        let args: WriteFileArgs = serde_json::from_value(args)?;

        // Update mutable state if available
        if let Some(state_handle) = &ctx.state_handle {
            let mut state = state_handle
                .write()
                .expect("filesystem write lock poisoned");
            state.files.insert(args.path.clone(), args.content.clone());
        }

        // Create state diff for persistence
        let mut diff = StateDiff::default();
        let mut files = BTreeMap::new();
        files.insert(args.path.clone(), args.content);
        diff.files = Some(files);

        let message = ctx.text_response(format!("Updated file {}", args.path));
        Ok(ToolResult::with_state(message, diff))
    }
}

/// Edit file tool - performs string replacement in a file
pub struct EditFileTool;

#[derive(Deserialize)]
struct EditFileArgs {
    #[serde(rename = "file_path")]
    path: String,
    #[serde(rename = "old_string")]
    old: String,
    #[serde(rename = "new_string")]
    new: String,
    #[serde(default)]
    replace_all: bool,
}

#[async_trait]
impl Tool for EditFileTool {
    fn schema(&self) -> ToolSchema {
        let mut properties = HashMap::new();
        properties.insert(
            "file_path".to_string(),
            ToolParameterSchema::string("Path to the file to edit"),
        );
        properties.insert(
            "old_string".to_string(),
            ToolParameterSchema::string("String to find and replace"),
        );
        properties.insert(
            "new_string".to_string(),
            ToolParameterSchema::string("Replacement string"),
        );
        properties.insert(
            "replace_all".to_string(),
            ToolParameterSchema::boolean(
                "Replace all occurrences (default: false, requires unique match)",
            ),
        );

        ToolSchema::new(
            "edit_file",
            "Edit a file by replacing old_string with new_string",
            ToolParameterSchema::object(
                "Edit file parameters",
                properties,
                vec![
                    "file_path".to_string(),
                    "old_string".to_string(),
                    "new_string".to_string(),
                ],
            ),
        )
    }

    async fn execute(&self, args: Value, ctx: ToolContext) -> anyhow::Result<ToolResult> {
        let args: EditFileArgs = serde_json::from_value(args)?;

        let Some(existing) = ctx.state.files.get(&args.path).cloned() else {
            return Ok(ToolResult::text(
                &ctx,
                format!("Error: File '{}' not found", args.path),
            ));
        };

        if !existing.contains(&args.old) {
            return Ok(ToolResult::text(
                &ctx,
                format!("Error: String not found in file: '{}'", args.old),
            ));
        }

        if !args.replace_all {
            let occurrences = existing.matches(&args.old).count();
            if occurrences > 1 {
                return Ok(ToolResult::text(
                    &ctx,
                    format!(
                        "Error: String '{}' appears {} times in file. Use replace_all=true to replace all instances, or provide a more specific string with surrounding context.",
                        args.old, occurrences
                    ),
                ));
            }
        }

        let updated = if args.replace_all {
            existing.replace(&args.old, &args.new)
        } else {
            existing.replacen(&args.old, &args.new, 1)
        };

        let replacement_count = if args.replace_all {
            existing.matches(&args.old).count()
        } else {
            1
        };

        // Update mutable state if available
        if let Some(state_handle) = &ctx.state_handle {
            let mut state = state_handle
                .write()
                .expect("filesystem write lock poisoned");
            state.files.insert(args.path.clone(), updated.clone());
        }

        // Create state diff
        let mut diff = StateDiff::default();
        let mut files = BTreeMap::new();
        files.insert(args.path.clone(), updated);
        diff.files = Some(files);

        let message = if args.replace_all {
            ctx.text_response(format!(
                "Successfully replaced {} instance(s) of the string in '{}'",
                replacement_count, args.path
            ))
        } else {
            ctx.text_response(format!("Successfully replaced string in '{}'", args.path))
        };

        Ok(ToolResult::with_state(message, diff))
    }
}

/// Create all filesystem tools and return them as a vec
pub fn create_filesystem_tools() -> Vec<ToolBox> {
    vec![
        std::sync::Arc::new(LsTool),
        std::sync::Arc::new(ReadFileTool),
        std::sync::Arc::new(WriteFileTool),
        std::sync::Arc::new(EditFileTool),
    ]
}

#[cfg(test)]
mod tests {
    use super::*;
    use agents_core::state::AgentStateSnapshot;
    use serde_json::json;
    use std::sync::{Arc, RwLock};

    #[tokio::test]
    async fn ls_tool_lists_files() {
        let mut state = AgentStateSnapshot::default();
        state
            .files
            .insert("test.txt".to_string(), "content".to_string());
        let ctx = ToolContext::new(Arc::new(state));

        let tool = LsTool;
        let result = tool.execute(json!({}), ctx).await.unwrap();

        match result {
            ToolResult::Message(msg) => {
                let files: Vec<String> =
                    serde_json::from_value(msg.content.as_json().unwrap().clone()).unwrap();
                assert_eq!(files, vec!["test.txt"]);
            }
            _ => panic!("Expected message result"),
        }
    }

    #[tokio::test]
    async fn read_file_tool_reads_content() {
        let mut state = AgentStateSnapshot::default();
        state.files.insert(
            "main.rs".to_string(),
            "fn main() {}\nlet x = 1;".to_string(),
        );
        let ctx = ToolContext::new(Arc::new(state));

        let tool = ReadFileTool;
        let result = tool
            .execute(
                json!({"file_path": "main.rs", "offset": 0, "limit": 10}),
                ctx,
            )
            .await
            .unwrap();

        match result {
            ToolResult::Message(msg) => {
                let text = msg.content.as_text().unwrap();
                assert!(text.contains("fn main"));
            }
            _ => panic!("Expected message result"),
        }
    }

    #[tokio::test]
    async fn write_file_tool_creates_file() {
        let state = Arc::new(AgentStateSnapshot::default());
        let state_handle = Arc::new(RwLock::new(AgentStateSnapshot::default()));
        let ctx = ToolContext::with_mutable_state(state, state_handle.clone());

        let tool = WriteFileTool;
        let result = tool
            .execute(
                json!({"file_path": "new.txt", "content": "hello world"}),
                ctx,
            )
            .await
            .unwrap();

        match result {
            ToolResult::WithStateUpdate {
                message,
                state_diff,
            } => {
                assert!(message
                    .content
                    .as_text()
                    .unwrap()
                    .contains("Updated file new.txt"));
                assert!(state_diff.files.unwrap().contains_key("new.txt"));

                // Verify state was updated
                let final_state = state_handle.read().unwrap();
                assert_eq!(final_state.files.get("new.txt").unwrap(), "hello world");
            }
            _ => panic!("Expected state update result"),
        }
    }

    #[tokio::test]
    async fn edit_file_tool_replaces_string() {
        let mut state = AgentStateSnapshot::default();
        state
            .files
            .insert("test.txt".to_string(), "hello world".to_string());
        let state = Arc::new(state);
        let state_handle = Arc::new(RwLock::new((*state).clone()));
        let ctx = ToolContext::with_mutable_state(state, state_handle.clone());

        let tool = EditFileTool;
        let result = tool
            .execute(
                json!({
                    "file_path": "test.txt",
                    "old_string": "world",
                    "new_string": "rust"
                }),
                ctx,
            )
            .await
            .unwrap();

        match result {
            ToolResult::WithStateUpdate { state_diff, .. } => {
                let files = state_diff.files.unwrap();
                assert_eq!(files.get("test.txt").unwrap(), "hello rust");
            }
            _ => panic!("Expected state update result"),
        }
    }
}