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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! Grep content search built-in tool.
//!
//! Searches file contents with regex support.

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 regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::path::Path;
use walkdir::WalkDir;

/// Grep content search tool executor.
///
/// Searches file contents using regex patterns.
#[derive(Debug, Default, Clone)]
pub struct GrepTool;

/// Grep tool actor state.
///
/// This actor wraps the `GrepTool` executor for per-agent tool spawning.
#[acton_actor]
pub struct GrepToolActor;

/// Arguments for the grep tool.
#[derive(Debug, Deserialize)]
struct GrepArgs {
    /// Regex pattern to search for
    pattern: String,
    /// File or directory to search in (default: current directory)
    #[serde(default)]
    path: Option<String>,
    /// File glob pattern to filter files (e.g., "*.rs")
    #[serde(default)]
    glob: Option<String>,
    /// Number of context lines before and after each match
    #[serde(default)]
    context_lines: Option<usize>,
    /// Case insensitive search
    #[serde(default)]
    ignore_case: Option<bool>,
}

/// A single match result.
#[derive(Debug, Serialize)]
struct GrepMatch {
    /// File path
    file: String,
    /// Line number (1-indexed)
    line: usize,
    /// Matched line content
    content: String,
    /// Context lines before the match
    #[serde(skip_serializing_if = "Vec::is_empty")]
    before: Vec<String>,
    /// Context lines after the match
    #[serde(skip_serializing_if = "Vec::is_empty")]
    after: Vec<String>,
}

/// Maximum number of matches to return.
const MAX_MATCHES: usize = 500;

/// Maximum file size to search (10MB).
const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024;

impl GrepTool {
    /// Creates a new grep 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: "grep".to_string(),
            description: "Search file contents using regex patterns. Returns matching lines with optional context.".to_string(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "pattern": {
                        "type": "string",
                        "description": "Regex pattern to search for"
                    },
                    "path": {
                        "type": "string",
                        "description": "File or directory to search in (default: current directory)"
                    },
                    "glob": {
                        "type": "string",
                        "description": "File pattern to filter files (e.g., '*.rs', '*.{ts,tsx}')"
                    },
                    "context_lines": {
                        "type": "integer",
                        "description": "Number of context lines before and after each match",
                        "minimum": 0,
                        "maximum": 10
                    },
                    "ignore_case": {
                        "type": "boolean",
                        "description": "Case insensitive search (default: false)"
                    }
                },
                "required": ["pattern"]
            }),
        })
    }

    /// Checks if a filename matches a glob-like pattern.
    fn matches_glob(filename: &str, pattern: &str) -> bool {
        // Simple glob matching for common patterns
        if let Some(ext) = pattern.strip_prefix("*.") {
            filename.ends_with(&format!(".{ext}"))
        } else if pattern.contains('*') {
            // Convert simple glob to regex
            let regex_pattern = pattern
                .replace('.', "\\.")
                .replace('*', ".*")
                .replace('?', ".");
            Regex::new(&format!("^{regex_pattern}$"))
                .map(|re| re.is_match(filename))
                .unwrap_or(false)
        } else {
            filename == pattern
        }
    }

    /// Searches a single file for matches.
    fn search_file(
        path: &Path,
        regex: &Regex,
        context_lines: usize,
    ) -> Result<Vec<GrepMatch>, ToolError> {
        let content = std::fs::read_to_string(path).map_err(|e| {
            ToolError::execution_failed("grep", format!("failed to read {}: {e}", path.display()))
        })?;

        let lines: Vec<&str> = content.lines().collect();
        let mut matches = Vec::new();

        for (idx, line) in lines.iter().enumerate() {
            if regex.is_match(line) {
                let before: Vec<String> = if context_lines > 0 && idx > 0 {
                    let start = idx.saturating_sub(context_lines);
                    lines[start..idx].iter().map(|s| (*s).to_string()).collect()
                } else {
                    Vec::new()
                };

                let after: Vec<String> = if context_lines > 0 {
                    let end = (idx + 1 + context_lines).min(lines.len());
                    lines[idx + 1..end]
                        .iter()
                        .map(|s| (*s).to_string())
                        .collect()
                } else {
                    Vec::new()
                };

                matches.push(GrepMatch {
                    file: path.to_string_lossy().to_string(),
                    line: idx + 1,
                    content: (*line).to_string(),
                    before,
                    after,
                });
            }
        }

        Ok(matches)
    }
}

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

            // Build regex
            let pattern = if args.ignore_case.unwrap_or(false) {
                format!("(?i){}", args.pattern)
            } else {
                args.pattern.clone()
            };

            let regex = Regex::new(&pattern).map_err(|e| {
                ToolError::validation_failed("grep", format!("invalid regex pattern: {e}"))
            })?;

            // Determine and validate search path
            let validator = PathValidator::new();
            let search_path = match &args.path {
                Some(p) => {
                    let path = Path::new(p);
                    if !path.is_absolute() {
                        return Err(ToolError::validation_failed(
                            "grep",
                            "path must be absolute",
                        ));
                    }
                    // Validate the search path using PathValidator for security
                    validator
                        .validate(path)
                        .map_err(|e| ToolError::validation_failed("grep", e.to_string()))?
                }
                None => std::env::current_dir().map_err(|e| {
                    ToolError::execution_failed(
                        "grep",
                        format!("failed to get current directory: {e}"),
                    )
                })?,
            };

            let context_lines = args.context_lines.unwrap_or(0).min(10);
            let glob_pattern = args.glob.as_deref();

            let mut all_matches = Vec::new();
            let mut files_searched = 0;
            let mut truncated = false;

            // Search single file or directory
            if search_path.is_file() {
                if let Ok(matches) = Self::search_file(&search_path, &regex, context_lines) {
                    all_matches.extend(matches);
                    files_searched = 1;
                }
            } else {
                // Walk directory
                for entry in WalkDir::new(&search_path)
                    .follow_links(false)
                    .into_iter()
                    .filter_map(Result::ok)
                {
                    if all_matches.len() >= MAX_MATCHES {
                        truncated = true;
                        break;
                    }

                    let path = entry.path();

                    // Skip directories
                    if !path.is_file() {
                        continue;
                    }

                    // Skip hidden files and directories
                    if entry
                        .file_name()
                        .to_str()
                        .map(|s| s.starts_with('.'))
                        .unwrap_or(false)
                    {
                        continue;
                    }

                    // Apply glob filter
                    if let Some(glob) = glob_pattern {
                        let filename = entry.file_name().to_string_lossy();
                        if !Self::matches_glob(&filename, glob) {
                            continue;
                        }
                    }

                    // Skip large files
                    if let Ok(metadata) = entry.metadata() {
                        if metadata.len() > MAX_FILE_SIZE {
                            continue;
                        }
                    }

                    // Skip binary files (quick heuristic)
                    if let Ok(content) = std::fs::read(path) {
                        let sample_size = content.len().min(8192);
                        let null_count = content[..sample_size].iter().filter(|&&b| b == 0).count();
                        if null_count > sample_size / 10 {
                            continue;
                        }
                    }

                    if let Ok(matches) = Self::search_file(path, &regex, context_lines) {
                        let remaining = MAX_MATCHES - all_matches.len();
                        if matches.len() > remaining {
                            all_matches.extend(matches.into_iter().take(remaining));
                            truncated = true;
                            break;
                        }
                        all_matches.extend(matches);
                    }
                    files_searched += 1;
                }
            }

            Ok(json!({
                "matches": all_matches,
                "count": all_matches.len(),
                "files_searched": files_searched,
                "truncated": truncated,
                "pattern": args.pattern
            }))
        })
    }

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

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

        // Validate regex
        let pattern = if args.ignore_case.unwrap_or(false) {
            format!("(?i){}", args.pattern)
        } else {
            args.pattern
        };

        Regex::new(&pattern).map_err(|e| {
            ToolError::validation_failed("grep", format!("invalid regex pattern: {e}"))
        })?;

        Ok(())
    }
}

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

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

    async fn spawn(runtime: &mut ActorRuntime) -> ActorHandle {
        let mut builder = runtime.new_actor_with_name::<Self>("grep_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 = GrepTool::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 grep_finds_matches() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("test.txt"),
            "hello world\nfoo bar\nhello again",
        )
        .unwrap();

        let tool = GrepTool::new();
        let result = tool
            .execute(json!({
                "pattern": "hello",
                "path": dir.path().to_str().unwrap()
            }))
            .await
            .unwrap();

        assert_eq!(result["count"], 2);

        let matches = result["matches"].as_array().unwrap();
        assert!(matches[0]["content"].as_str().unwrap().contains("hello"));
        assert!(matches[1]["content"].as_str().unwrap().contains("hello"));
    }

    #[tokio::test]
    async fn grep_with_context() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("test.txt"),
            "line 1\nline 2\nmatch here\nline 4\nline 5",
        )
        .unwrap();

        let tool = GrepTool::new();
        let result = tool
            .execute(json!({
                "pattern": "match",
                "path": dir.path().to_str().unwrap(),
                "context_lines": 2
            }))
            .await
            .unwrap();

        assert_eq!(result["count"], 1);

        let matches = result["matches"].as_array().unwrap();
        let m = &matches[0];

        assert_eq!(m["line"], 3);
        assert_eq!(m["before"].as_array().unwrap().len(), 2);
        assert_eq!(m["after"].as_array().unwrap().len(), 2);
    }

    #[tokio::test]
    async fn grep_case_insensitive() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("test.txt"),
            "Hello World\nHELLO WORLD\nhello world",
        )
        .unwrap();

        let tool = GrepTool::new();
        let result = tool
            .execute(json!({
                "pattern": "hello",
                "path": dir.path().to_str().unwrap(),
                "ignore_case": true
            }))
            .await
            .unwrap();

        assert_eq!(result["count"], 3);
    }

    #[tokio::test]
    async fn grep_with_glob_filter() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("test.rs"), "fn main() {}").unwrap();
        fs::write(dir.path().join("test.txt"), "fn main() {}").unwrap();

        let tool = GrepTool::new();
        let result = tool
            .execute(json!({
                "pattern": "fn main",
                "path": dir.path().to_str().unwrap(),
                "glob": "*.rs"
            }))
            .await
            .unwrap();

        assert_eq!(result["count"], 1);

        let matches = result["matches"].as_array().unwrap();
        assert!(matches[0]["file"].as_str().unwrap().ends_with(".rs"));
    }

    #[tokio::test]
    async fn grep_regex_pattern() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("test.txt"), "foo123\nbar456\nbaz789").unwrap();

        let tool = GrepTool::new();
        let result = tool
            .execute(json!({
                "pattern": "\\d{3}$",
                "path": dir.path().to_str().unwrap()
            }))
            .await
            .unwrap();

        assert_eq!(result["count"], 3);
    }

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

        let tool = GrepTool::new();
        let result = tool
            .execute(json!({
                "pattern": "xyz",
                "path": dir.path().to_str().unwrap()
            }))
            .await
            .unwrap();

        assert_eq!(result["count"], 0);
        assert!(!result["truncated"].as_bool().unwrap());
    }

    #[tokio::test]
    async fn grep_invalid_regex() {
        let tool = GrepTool::new();
        let result = tool
            .execute(json!({
                "pattern": "[invalid"
            }))
            .await;

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

    #[tokio::test]
    async fn grep_relative_path_rejected() {
        let tool = GrepTool::new();
        let result = tool
            .execute(json!({
                "pattern": "test",
                "path": "relative/path"
            }))
            .await;

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

    #[tokio::test]
    async fn grep_path_not_found() {
        let tool = GrepTool::new();
        let result = tool
            .execute(json!({
                "pattern": "test",
                "path": "/nonexistent/path"
            }))
            .await;

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

    #[test]
    fn matches_glob_extension() {
        assert!(GrepTool::matches_glob("file.rs", "*.rs"));
        assert!(!GrepTool::matches_glob("file.txt", "*.rs"));
    }

    #[test]
    fn matches_glob_exact() {
        assert!(GrepTool::matches_glob("Cargo.toml", "Cargo.toml"));
        assert!(!GrepTool::matches_glob("other.toml", "Cargo.toml"));
    }

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

        let schema = &config.definition.input_schema;
        assert!(schema["properties"]["pattern"].is_object());
        assert!(schema["properties"]["path"].is_object());
        assert!(schema["properties"]["glob"].is_object());
        assert!(schema["properties"]["context_lines"].is_object());
        assert!(schema["properties"]["ignore_case"].is_object());
    }
}