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
//! Bash command execution built-in tool.
//!
//! Executes shell commands with timeout and output capture.

use crate::messages::ToolDefinition;
use crate::tools::actor::{ExecuteToolDirect, ToolActor, ToolActorResponse};
use crate::tools::{ToolConfig, ToolError, ToolExecutionFuture, ToolExecutorTrait};
use acton_reactive::prelude::*;
use serde::Deserialize;
use serde_json::{json, Value};
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
use tokio::time::timeout;

/// Bash command execution tool executor.
///
/// Executes shell commands and captures output.
#[derive(Debug, Clone)]
pub struct BashTool {
    /// Default timeout in seconds
    default_timeout: u64,
    /// Maximum allowed timeout in seconds
    max_timeout: u64,
}

/// Bash tool actor state.
///
/// This actor wraps the `BashTool` executor for per-agent tool spawning.
#[acton_actor]
pub struct BashToolActor;

impl Default for BashTool {
    fn default() -> Self {
        Self {
            default_timeout: 120,
            max_timeout: 600,
        }
    }
}

/// Arguments for the bash tool.
#[derive(Debug, Deserialize)]
struct BashArgs {
    /// Command to execute
    command: String,
    /// Timeout in seconds (default: 120, max: 600)
    #[serde(default)]
    timeout: Option<u64>,
    /// Working directory (default: current directory)
    #[serde(default)]
    cwd: Option<String>,
}

/// Maximum output size to capture (1MB).
const MAX_OUTPUT_SIZE: usize = 1024 * 1024;

impl BashTool {
    /// Creates a new bash tool with default settings.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a new bash tool with custom timeout settings.
    #[must_use]
    pub fn with_timeouts(default_timeout: u64, max_timeout: u64) -> Self {
        Self {
            default_timeout,
            max_timeout,
        }
    }

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

        ToolConfig::new(ToolDefinition {
            name: "bash".to_string(),
            description: "Use to execute a shell command and capture its output. Use for system operations, git commands, build tools, and anything else that requires a shell.".to_string(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "command": {
                        "type": "string",
                        "description": "The shell command to execute"
                    },
                    "timeout": {
                        "type": "integer",
                        "description": "Timeout in seconds (default: 120, max: 600)",
                        "minimum": 1,
                        "maximum": 600
                    },
                    "cwd": {
                        "type": "string",
                        "description": "Absolute path to working directory. Only specify if you need a different directory than the current one."
                    }
                },
                "required": ["command"]
            }),
        })
        .with_sandbox(true) // Mark as requiring sandbox by default
    }

    /// Truncates output if it exceeds the maximum size.
    fn truncate_output(output: &str) -> (String, bool) {
        if output.len() > MAX_OUTPUT_SIZE {
            let truncated = &output[..MAX_OUTPUT_SIZE];
            // Try to truncate at a line boundary
            let last_newline = truncated.rfind('\n').unwrap_or(MAX_OUTPUT_SIZE);
            (
                format!(
                    "{}\n\n... (output truncated, {} bytes total)",
                    &output[..last_newline],
                    output.len()
                ),
                true,
            )
        } else {
            (output.to_string(), false)
        }
    }
}

impl ToolExecutorTrait for BashTool {
    fn execute(&self, args: Value) -> ToolExecutionFuture {
        let default_timeout = self.default_timeout;
        let max_timeout = self.max_timeout;

        Box::pin(async move {
            let args: BashArgs = serde_json::from_value(args).map_err(|e| {
                ToolError::validation_failed("bash", format!("invalid arguments: {e}"))
            })?;

            // Validate empty command early
            if args.command.is_empty() {
                return Err(ToolError::validation_failed(
                    "bash",
                    "command cannot be empty",
                ));
            }

            // Validate and set timeout
            let timeout_secs = args.timeout.unwrap_or(default_timeout).min(max_timeout);

            // Validate working directory if provided
            if let Some(ref cwd) = args.cwd {
                let path = Path::new(cwd);
                if !path.is_absolute() {
                    return Err(ToolError::validation_failed(
                        "bash",
                        "cwd must be an absolute path",
                    ));
                }
                if !path.exists() {
                    return Err(ToolError::execution_failed(
                        "bash",
                        format!("working directory does not exist: {cwd}"),
                    ));
                }
                if !path.is_dir() {
                    return Err(ToolError::execution_failed(
                        "bash",
                        format!("cwd is not a directory: {cwd}"),
                    ));
                }
            }

            // Build the command
            let mut cmd = Command::new("bash");
            cmd.arg("-c")
                .arg(&args.command)
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .stdin(Stdio::null());

            // Set working directory if provided
            if let Some(ref cwd) = args.cwd {
                cmd.current_dir(cwd);
            }

            // Spawn the process
            let mut child = cmd.spawn().map_err(|e| {
                ToolError::execution_failed("bash", format!("failed to spawn process: {e}"))
            })?;

            // Wait for completion with timeout
            let timeout_duration = Duration::from_secs(timeout_secs);
            let result = timeout(timeout_duration, async {
                // Read stdout and stderr
                let mut stdout_buf = Vec::new();
                let mut stderr_buf = Vec::new();

                if let Some(mut stdout) = child.stdout.take() {
                    let _ = stdout.read_to_end(&mut stdout_buf).await;
                }

                if let Some(mut stderr) = child.stderr.take() {
                    let _ = stderr.read_to_end(&mut stderr_buf).await;
                }

                let status = child.wait().await?;

                Ok::<_, std::io::Error>((status, stdout_buf, stderr_buf))
            })
            .await;

            match result {
                Ok(Ok((status, stdout_buf, stderr_buf))) => {
                    let stdout = String::from_utf8_lossy(&stdout_buf);
                    let stderr = String::from_utf8_lossy(&stderr_buf);

                    let (stdout_str, stdout_truncated) = Self::truncate_output(&stdout);
                    let (stderr_str, stderr_truncated) = Self::truncate_output(&stderr);

                    let exit_code = status.code().unwrap_or(-1);

                    Ok(json!({
                        "exit_code": exit_code,
                        "stdout": stdout_str,
                        "stderr": stderr_str,
                        "success": status.success(),
                        "truncated": stdout_truncated || stderr_truncated
                    }))
                }
                Ok(Err(e)) => Err(ToolError::execution_failed(
                    "bash",
                    format!("process error: {e}"),
                )),
                Err(_) => {
                    // Timeout - try to kill the process
                    let _ = child.kill().await;
                    Err(ToolError::timeout(
                        "bash",
                        Duration::from_secs(timeout_secs),
                    ))
                }
            }
        })
    }

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

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

        // Basic safety check for obviously dangerous commands
        let dangerous_patterns = [
            "rm -rf /",
            ":(){ :|:& };:",
            "mkfs.",
            "dd if=/dev/zero of=/dev/",
        ];
        for pattern in &dangerous_patterns {
            if args.command.contains(pattern) {
                return Err(ToolError::validation_failed(
                    "bash",
                    format!("command contains dangerous pattern: {pattern}"),
                ));
            }
        }

        Ok(())
    }

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

    fn timeout(&self) -> Duration {
        Duration::from_secs(self.default_timeout)
    }
}

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

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

    async fn spawn(runtime: &mut ActorRuntime) -> ActorHandle {
        let mut builder = runtime.new_actor_with_name::<Self>("bash_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 = BashTool::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 tempfile::TempDir;

    #[tokio::test]
    async fn bash_simple_command() {
        let tool = BashTool::new();
        let result = tool
            .execute(json!({
                "command": "echo 'hello world'"
            }))
            .await
            .unwrap();

        assert!(result["success"].as_bool().unwrap());
        assert_eq!(result["exit_code"], 0);
        assert!(result["stdout"].as_str().unwrap().contains("hello world"));
    }

    #[tokio::test]
    async fn bash_with_stderr() {
        let tool = BashTool::new();
        let result = tool
            .execute(json!({
                "command": "echo 'error' >&2"
            }))
            .await
            .unwrap();

        assert!(result["success"].as_bool().unwrap());
        assert!(result["stderr"].as_str().unwrap().contains("error"));
    }

    #[tokio::test]
    async fn bash_exit_code() {
        let tool = BashTool::new();
        let result = tool
            .execute(json!({
                "command": "exit 42"
            }))
            .await
            .unwrap();

        assert!(!result["success"].as_bool().unwrap());
        assert_eq!(result["exit_code"], 42);
    }

    #[tokio::test]
    async fn bash_with_cwd() {
        let dir = TempDir::new().unwrap();

        let tool = BashTool::new();
        let result = tool
            .execute(json!({
                "command": "pwd",
                "cwd": dir.path().to_str().unwrap()
            }))
            .await
            .unwrap();

        assert!(result["success"].as_bool().unwrap());
        // The output should contain the temp directory path
        let stdout = result["stdout"].as_str().unwrap();
        assert!(stdout.contains(dir.path().file_name().unwrap().to_str().unwrap()));
    }

    #[tokio::test]
    async fn bash_timeout() {
        let tool = BashTool::with_timeouts(1, 5); // 1 second timeout
        let result = tool
            .execute(json!({
                "command": "sleep 10",
                "timeout": 1
            }))
            .await;

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

    #[tokio::test]
    async fn bash_invalid_cwd() {
        let tool = BashTool::new();
        let result = tool
            .execute(json!({
                "command": "echo test",
                "cwd": "/nonexistent/directory"
            }))
            .await;

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

    #[tokio::test]
    async fn bash_relative_cwd_rejected() {
        let tool = BashTool::new();
        let result = tool
            .execute(json!({
                "command": "echo test",
                "cwd": "relative/path"
            }))
            .await;

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

    #[tokio::test]
    async fn bash_empty_command_rejected() {
        let tool = BashTool::new();
        let result = tool
            .execute(json!({
                "command": ""
            }))
            .await;

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

    #[tokio::test]
    async fn bash_dangerous_command_rejected() {
        let tool = BashTool::new();
        let result = tool.validate_args(&json!({
            "command": "rm -rf /"
        }));

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

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

    #[test]
    fn truncate_output_small() {
        let (output, truncated) = BashTool::truncate_output("small output");
        assert_eq!(output, "small output");
        assert!(!truncated);
    }

    #[test]
    fn truncate_output_large() {
        let large_output = "x".repeat(MAX_OUTPUT_SIZE + 1000);
        let (output, truncated) = BashTool::truncate_output(&large_output);
        assert!(output.len() <= MAX_OUTPUT_SIZE + 100); // Some overhead for truncation message
        assert!(truncated);
        assert!(output.contains("truncated"));
    }

    #[test]
    fn config_has_correct_schema() {
        let config = BashTool::config();
        assert_eq!(config.definition.name, "bash");
        assert!(config.definition.description.contains("shell command"));
        assert!(config.sandboxed); // Should require sandbox

        let schema = &config.definition.input_schema;
        assert!(schema["properties"]["command"].is_object());
        assert!(schema["properties"]["timeout"].is_object());
        assert!(schema["properties"]["cwd"].is_object());
    }
}