acton-ai 0.26.0

An agentic AI framework where each agent is an actor
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
//! Edit file built-in tool.
//!
//! Makes targeted string replacements in files.

use crate::messages::ToolDefinition;
use crate::tools::actor::{ExecuteToolDirect, ToolActor, ToolActorResponse};
use crate::tools::security::PathValidator;
use crate::tools::{ToolConfig, ToolError, ToolExecutionFuture, ToolExecutorTrait};
use acton_reactive::prelude::*;
use serde::Deserialize;
use serde_json::{json, Value};
use std::path::Path;

/// Edit file tool executor.
///
/// Makes targeted string replacements in files.
#[derive(Debug, Default, Clone)]
pub struct EditFileTool;

/// Edit file tool actor state.
///
/// This actor wraps the `EditFileTool` executor for per-agent tool spawning.
#[acton_actor]
pub struct EditFileToolActor;

/// Arguments for the edit_file tool.
#[derive(Debug, Deserialize)]
struct EditFileArgs {
    /// Absolute path to the file to edit
    path: String,
    /// Exact string to find and replace
    old_string: String,
    /// Replacement string
    new_string: String,
    /// Replace all occurrences (default: false)
    #[serde(default)]
    replace_all: bool,
}

impl EditFileTool {
    /// Creates a new edit file tool.
    #[must_use]
    pub fn new() -> Self {
        Self
    }

    /// Returns the tool configuration for registration.
    #[must_use]
    pub fn config() -> ToolConfig {
        use crate::messages::ToolDefinition;

        ToolConfig::new(ToolDefinition {
            name: "edit_file".to_string(),
            description: "Make targeted string replacements in a file. The old_string must be found exactly once unless replace_all is true.".to_string(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Absolute path to the file to edit"
                    },
                    "old_string": {
                        "type": "string",
                        "description": "Exact string to find and replace"
                    },
                    "new_string": {
                        "type": "string",
                        "description": "Replacement string"
                    },
                    "replace_all": {
                        "type": "boolean",
                        "description": "Replace all occurrences (default: false, which requires exactly one match)"
                    }
                },
                "required": ["path", "old_string", "new_string"]
            }),
        })
        .with_sandbox(true) // File edits require sandbox for security
    }

    /// Generates a simple diff-style output.
    fn generate_diff(old_content: &str, new_content: &str, path: &str) -> String {
        let mut diff = String::new();
        diff.push_str(&format!("--- {path}\n"));
        diff.push_str(&format!("+++ {path}\n"));

        let old_lines: Vec<&str> = old_content.lines().collect();
        let new_lines: Vec<&str> = new_content.lines().collect();

        // Simple line-by-line diff
        let mut old_idx = 0;
        let mut new_idx = 0;

        while old_idx < old_lines.len() || new_idx < new_lines.len() {
            let old_line = old_lines.get(old_idx);
            let new_line = new_lines.get(new_idx);

            match (old_line, new_line) {
                (Some(o), Some(n)) if o == n => {
                    diff.push_str(&format!(" {o}\n"));
                    old_idx += 1;
                    new_idx += 1;
                }
                (Some(o), Some(n)) => {
                    diff.push_str(&format!("-{o}\n"));
                    diff.push_str(&format!("+{n}\n"));
                    old_idx += 1;
                    new_idx += 1;
                }
                (Some(o), None) => {
                    diff.push_str(&format!("-{o}\n"));
                    old_idx += 1;
                }
                (None, Some(n)) => {
                    diff.push_str(&format!("+{n}\n"));
                    new_idx += 1;
                }
                (None, None) => break,
            }
        }

        diff
    }
}

impl ToolExecutorTrait for EditFileTool {
    fn execute(&self, args: Value) -> ToolExecutionFuture {
        Box::pin(async move {
            let args: EditFileArgs = serde_json::from_value(args).map_err(|e| {
                ToolError::validation_failed("edit_file", format!("invalid arguments: {e}"))
            })?;

            let path = Path::new(&args.path);

            // Validate path is absolute
            if !path.is_absolute() {
                return Err(ToolError::validation_failed(
                    "edit_file",
                    "path must be absolute",
                ));
            }

            // Validate path using PathValidator for security
            let validator = PathValidator::new();
            let canonical_path = validator
                .validate_file(path)
                .map_err(|e| ToolError::validation_failed("edit_file", e.to_string()))?;

            // Validate that old_string != new_string
            if args.old_string == args.new_string {
                return Err(ToolError::validation_failed(
                    "edit_file",
                    "old_string and new_string must be different",
                ));
            }

            // Read the file
            let content = tokio::fs::read_to_string(&canonical_path)
                .await
                .map_err(|e| {
                    ToolError::execution_failed("edit_file", format!("failed to read file: {e}"))
                })?;

            // Count occurrences
            let match_count = content.matches(&args.old_string).count();

            if match_count == 0 {
                return Err(ToolError::execution_failed(
                    "edit_file",
                    "old_string not found in file; verify the exact content to replace",
                ));
            }

            if !args.replace_all && match_count > 1 {
                return Err(ToolError::execution_failed(
                    "edit_file",
                    format!(
                        "old_string found {match_count} times; use replace_all: true to replace all, or provide more context to make it unique"
                    ),
                ));
            }

            // Perform replacement
            let new_content = if args.replace_all {
                content.replace(&args.old_string, &args.new_string)
            } else {
                content.replacen(&args.old_string, &args.new_string, 1)
            };

            // Generate diff
            let diff = Self::generate_diff(&content, &new_content, &args.path);

            // Write the file
            tokio::fs::write(&canonical_path, &new_content)
                .await
                .map_err(|e| {
                    ToolError::execution_failed("edit_file", format!("failed to write file: {e}"))
                })?;

            Ok(json!({
                "success": true,
                "path": args.path,
                "replacements": match_count,
                "diff": diff
            }))
        })
    }

    fn validate_args(&self, args: &Value) -> Result<(), ToolError> {
        let args: EditFileArgs = serde_json::from_value(args.clone()).map_err(|e| {
            ToolError::validation_failed("edit_file", format!("invalid arguments: {e}"))
        })?;

        if args.path.is_empty() {
            return Err(ToolError::validation_failed(
                "edit_file",
                "path cannot be empty",
            ));
        }

        if args.old_string.is_empty() {
            return Err(ToolError::validation_failed(
                "edit_file",
                "old_string cannot be empty",
            ));
        }

        Ok(())
    }

    fn requires_sandbox(&self) -> bool {
        true
    }
}

impl ToolActor for EditFileToolActor {
    fn name() -> &'static str {
        "edit_file"
    }

    fn definition() -> ToolDefinition {
        EditFileTool::config().definition
    }

    async fn spawn(runtime: &mut ActorRuntime) -> ActorHandle {
        let mut builder = runtime.new_actor_with_name::<Self>("edit_file_tool".to_string());

        builder.act_on::<ExecuteToolDirect>(|actor, envelope| {
            let msg = envelope.message();
            let correlation_id = msg.correlation_id.clone();
            let tool_call_id = msg.tool_call_id.clone();
            let args = msg.args.clone();
            let broker = actor.broker().clone();

            Reply::pending(async move {
                let tool = EditFileTool::new();
                let result = tool.execute(args).await;

                let response = match result {
                    Ok(value) => {
                        let result_str = serde_json::to_string(&value)
                            .unwrap_or_else(|e| format!("{{\"error\": \"{}\"}}", e));
                        ToolActorResponse::success(correlation_id, tool_call_id, result_str)
                    }
                    Err(e) => ToolActorResponse::error(correlation_id, tool_call_id, e.to_string()),
                };

                broker.broadcast(response).await;
            })
        });

        builder.start().await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[tokio::test]
    async fn edit_file_single_replacement() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("test.txt");
        fs::write(&path, "hello world").unwrap();

        let tool = EditFileTool::new();
        let result = tool
            .execute(json!({
                "path": path.to_str().unwrap(),
                "old_string": "world",
                "new_string": "rust"
            }))
            .await
            .unwrap();

        assert!(result["success"].as_bool().unwrap());
        assert_eq!(result["replacements"], 1);

        let content = fs::read_to_string(&path).unwrap();
        assert_eq!(content, "hello rust");
    }

    #[tokio::test]
    async fn edit_file_replace_all() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("test.txt");
        fs::write(&path, "foo foo foo").unwrap();

        let tool = EditFileTool::new();
        let result = tool
            .execute(json!({
                "path": path.to_str().unwrap(),
                "old_string": "foo",
                "new_string": "bar",
                "replace_all": true
            }))
            .await
            .unwrap();

        assert!(result["success"].as_bool().unwrap());
        assert_eq!(result["replacements"], 3);

        let content = fs::read_to_string(&path).unwrap();
        assert_eq!(content, "bar bar bar");
    }

    #[tokio::test]
    async fn edit_file_multiline_replacement() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("test.txt");
        fs::write(&path, "line1\nold content\nline3").unwrap();

        let tool = EditFileTool::new();
        let result = tool
            .execute(json!({
                "path": path.to_str().unwrap(),
                "old_string": "old content",
                "new_string": "new content\nwith multiple lines"
            }))
            .await
            .unwrap();

        assert!(result["success"].as_bool().unwrap());

        let content = fs::read_to_string(&path).unwrap();
        assert_eq!(content, "line1\nnew content\nwith multiple lines\nline3");
    }

    #[tokio::test]
    async fn edit_file_ambiguous_without_replace_all() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("test.txt");
        fs::write(&path, "foo foo foo").unwrap();

        let tool = EditFileTool::new();
        let result = tool
            .execute(json!({
                "path": path.to_str().unwrap(),
                "old_string": "foo",
                "new_string": "bar"
            }))
            .await;

        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("3 times"));
        assert!(err.contains("replace_all"));
    }

    #[tokio::test]
    async fn edit_file_not_found_in_content() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("test.txt");
        fs::write(&path, "hello world").unwrap();

        let tool = EditFileTool::new();
        let result = tool
            .execute(json!({
                "path": path.to_str().unwrap(),
                "old_string": "xyz",
                "new_string": "abc"
            }))
            .await;

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[tokio::test]
    async fn edit_file_same_string_rejected() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("test.txt");
        fs::write(&path, "hello world").unwrap();

        let tool = EditFileTool::new();
        let result = tool
            .execute(json!({
                "path": path.to_str().unwrap(),
                "old_string": "hello",
                "new_string": "hello"
            }))
            .await;

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("different"));
    }

    #[tokio::test]
    async fn edit_file_not_exists() {
        let tool = EditFileTool::new();
        let result = tool
            .execute(json!({
                "path": "/nonexistent/file.txt",
                "old_string": "old",
                "new_string": "new"
            }))
            .await;

        assert!(result.is_err());
        // PathValidator returns "cannot resolve path" for non-existent files
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("cannot resolve path"));
    }

    #[tokio::test]
    async fn edit_file_relative_path_rejected() {
        let tool = EditFileTool::new();
        let result = tool
            .execute(json!({
                "path": "relative/path.txt",
                "old_string": "old",
                "new_string": "new"
            }))
            .await;

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("absolute"));
    }

    #[tokio::test]
    async fn edit_file_generates_diff() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("test.txt");
        fs::write(&path, "line1\nold\nline3").unwrap();

        let tool = EditFileTool::new();
        let result = tool
            .execute(json!({
                "path": path.to_str().unwrap(),
                "old_string": "old",
                "new_string": "new"
            }))
            .await
            .unwrap();

        let diff = result["diff"].as_str().unwrap();
        assert!(diff.contains("-old"));
        assert!(diff.contains("+new"));
    }

    #[test]
    fn config_has_correct_schema() {
        let config = EditFileTool::config();
        assert_eq!(config.definition.name, "edit_file");
        assert!(config.definition.description.contains("replacement"));

        let schema = &config.definition.input_schema;
        assert!(schema["properties"]["path"].is_object());
        assert!(schema["properties"]["old_string"].is_object());
        assert!(schema["properties"]["new_string"].is_object());
        assert!(schema["properties"]["replace_all"].is_object());
    }

    #[test]
    fn edit_file_requires_sandbox() {
        let tool = EditFileTool::new();
        assert!(tool.requires_sandbox());
    }

    #[test]
    fn edit_file_config_is_sandboxed() {
        let config = EditFileTool::config();
        assert!(config.sandboxed, "edit_file tool should require sandbox");
    }
}