agent-code-lib 0.16.1

Agent engine library: LLM providers, tools, query loop, memory
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//! Bash tool: execute shell commands.
//!
//! Runs commands via the system shell. Features:
//! - Timeout with configurable duration (default 2min, max 10min)
//! - Background execution for long-running commands
//! - Sandbox mode: blocks writes outside the project directory
//! - Destructive command warnings
//! - Output truncation for large results
//! - Cancellation via CancellationToken

use async_trait::async_trait;
use serde_json::json;
use std::path::PathBuf;
use std::process::Stdio;
use std::time::Duration;
use tokio::io::AsyncReadExt;
use tokio::process::Command;

use super::{Tool, ToolContext, ToolResult};
use crate::error::ToolError;

/// Maximum output size before truncation (256KB).
const MAX_OUTPUT_BYTES: usize = 256 * 1024;

/// Commands that are potentially destructive and warrant a warning.
const DESTRUCTIVE_PATTERNS: &[&str] = &[
    // Filesystem destruction.
    "rm -rf",
    "rm -r /",
    "rm -fr",
    "rmdir",
    "shred",
    // Git destructive operations.
    "git reset --hard",
    "git clean -f",
    "git clean -d",
    "git push --force",
    "git push -f",
    "git checkout -- .",
    "git checkout -f",
    "git restore .",
    "git branch -D",
    "git branch --delete --force",
    "git stash drop",
    "git stash clear",
    "git rebase --abort",
    // Database operations.
    "DROP TABLE",
    "DROP DATABASE",
    "DROP SCHEMA",
    "DELETE FROM",
    "TRUNCATE",
    // System operations.
    "shutdown",
    "reboot",
    "halt",
    "poweroff",
    "init 0",
    "init 6",
    "mkfs",
    "dd if=",
    "dd of=/dev",
    "> /dev/sd",
    "wipefs",
    // Permission escalation.
    "chmod -R 777",
    "chmod 777",
    "chown -R",
    // Process/system danger.
    "kill -9",
    "killall",
    "pkill -9",
    // Fork bomb.
    ":(){ :|:& };:",
    // NPM/package destruction.
    "npm publish",
    "cargo publish",
    // Docker cleanup.
    "docker system prune -a",
    "docker volume prune",
    // Kubernetes.
    "kubectl delete namespace",
    "kubectl delete --all",
    // Infrastructure.
    "terraform destroy",
    "pulumi destroy",
];

/// Paths that should never be written to.
const BLOCKED_WRITE_PATHS: &[&str] = &[
    "/etc/", "/usr/", "/bin/", "/sbin/", "/boot/", "/sys/", "/proc/",
];

pub struct BashTool;

#[async_trait]
impl Tool for BashTool {
    fn name(&self) -> &'static str {
        "Bash"
    }

    fn description(&self) -> &'static str {
        "Executes a shell command and returns its output."
    }

    fn input_schema(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "required": ["command"],
            "properties": {
                "command": {
                    "type": "string",
                    "description": "The command to execute"
                },
                "timeout": {
                    "type": "integer",
                    "description": "Timeout in milliseconds (max 600000)"
                },
                "description": {
                    "type": "string",
                    "description": "Description of what this command does"
                },
                "run_in_background": {
                    "type": "boolean",
                    "description": "Run the command in the background and return immediately"
                },
                "dangerouslyDisableSandbox": {
                    "type": "boolean",
                    "description": "Disable safety checks for this command. Use only when explicitly asked."
                }
            }
        })
    }

    fn is_read_only(&self) -> bool {
        false
    }

    fn is_concurrency_safe(&self) -> bool {
        false
    }

    fn get_path(&self, _input: &serde_json::Value) -> Option<PathBuf> {
        None
    }

    fn validate_input(&self, input: &serde_json::Value) -> Result<(), String> {
        let command = input.get("command").and_then(|v| v.as_str()).unwrap_or("");

        // Skip all safety checks if dangerouslyDisableSandbox is set.
        if input
            .get("dangerouslyDisableSandbox")
            .and_then(|v| v.as_bool())
            .unwrap_or(false)
        {
            return Ok(());
        }

        // Check for destructive commands.
        let cmd_lower = command.to_lowercase();
        for pattern in DESTRUCTIVE_PATTERNS {
            if cmd_lower.contains(&pattern.to_lowercase()) {
                return Err(format!(
                    "Potentially destructive command detected: contains '{pattern}'. \
                     This command could cause data loss or system damage. \
                     If you're sure, ask the user for confirmation first."
                ));
            }
        }

        // Check for piped destructive patterns.
        // Split on pipes and check each segment's base command.
        for segment in command.split('|') {
            let trimmed = segment.trim();
            let base_cmd = trimmed.split_whitespace().next().unwrap_or("");
            if matches!(
                base_cmd,
                "rm" | "shred" | "dd" | "mkfs" | "wipefs" | "shutdown" | "reboot" | "halt"
            ) {
                return Err(format!(
                    "Potentially destructive command in pipe: '{base_cmd}'. \
                     Ask the user for confirmation first."
                ));
            }
        }

        // Check for chained destructive commands (&&, ;).
        for segment in cmd_lower.split("&&").flat_map(|s| s.split(';')) {
            let trimmed = segment.trim();
            for pattern in DESTRUCTIVE_PATTERNS {
                if trimmed.contains(&pattern.to_lowercase()) {
                    return Err(format!(
                        "Potentially destructive command in chain: contains '{pattern}'. \
                         Ask the user for confirmation first."
                    ));
                }
            }
        }

        // Advanced security checks (inspired by TS bashSecurity.ts).
        check_shell_injection(command)?;

        // Block writes to system paths.
        for path in BLOCKED_WRITE_PATHS {
            if cmd_lower.contains(&format!(">{path}"))
                || cmd_lower.contains(&format!("tee {path}"))
                || cmd_lower.contains(&"mv ".to_string()) && cmd_lower.contains(path)
            {
                return Err(format!(
                    "Cannot write to system path '{path}'. \
                     Operations on system directories are not allowed."
                ));
            }
        }

        // Tree-sitter AST analysis (catches obfuscation that regex misses).
        if let Some(parsed) = super::bash_parse::parse_bash(command) {
            let violations = super::bash_parse::check_parsed_security(&parsed);
            if let Some(first) = violations.first() {
                return Err(format!("AST security check: {first}"));
            }
        }

        Ok(())
    }

    async fn call(
        &self,
        input: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<ToolResult, ToolError> {
        let command = input
            .get("command")
            .and_then(|v| v.as_str())
            .ok_or_else(|| ToolError::InvalidInput("'command' is required".into()))?;

        let timeout_ms = input
            .get("timeout")
            .and_then(|v| v.as_u64())
            .unwrap_or(120_000)
            .min(600_000);

        let run_in_background = input
            .get("run_in_background")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        // Background execution: spawn and return immediately.
        if run_in_background {
            return run_background(command, &ctx.cwd, ctx.task_manager.as_ref()).await;
        }

        // Build the base bash command.
        let mut base = Command::new("bash");
        base.arg("-c")
            .arg(command)
            .current_dir(&ctx.cwd)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        // Honor a tool-call-level `dangerouslyDisableSandbox: true` by
        // skipping the sandbox wrapper. This path is blocked entirely
        // when the session has `security.disable_bypass_permissions = true`.
        let disable_sandbox_requested = input
            .get("dangerouslyDisableSandbox")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let mut cmd = if let Some(ref sandbox) = ctx.sandbox {
            if disable_sandbox_requested && sandbox.allow_bypass() {
                tracing::warn!(
                    "bash call set dangerouslyDisableSandbox; wrapping skipped for this call"
                );
                base
            } else {
                if disable_sandbox_requested && !sandbox.allow_bypass() {
                    tracing::warn!(
                        "dangerouslyDisableSandbox ignored: security.disable_bypass_permissions is set"
                    );
                }
                sandbox.wrap(base)
            }
        } else {
            base
        };

        let mut child = cmd
            .spawn()
            .map_err(|e| ToolError::ExecutionFailed(format!("Failed to spawn: {e}")))?;

        let timeout = Duration::from_millis(timeout_ms);

        let mut stdout_handle = child.stdout.take().unwrap();
        let mut stderr_handle = child.stderr.take().unwrap();

        let mut stdout_buf = Vec::new();
        let mut stderr_buf = Vec::new();

        let result = tokio::select! {
            r = async {
                let (so, se) = tokio::join!(
                    async { stdout_handle.read_to_end(&mut stdout_buf).await },
                    async { stderr_handle.read_to_end(&mut stderr_buf).await },
                );
                so?;
                se?;
                child.wait().await
            } => {
                match r {
                    Ok(status) => {
                        let exit_code = status.code().unwrap_or(-1);
                        let content = format_output(&stdout_buf, &stderr_buf, exit_code);

                        Ok(ToolResult {
                            content,
                            is_error: exit_code != 0,
                        })
                    }
                    Err(e) => Err(ToolError::ExecutionFailed(e.to_string())),
                }
            }
            _ = tokio::time::sleep(timeout) => {
                let _ = child.kill().await;
                Err(ToolError::Timeout(timeout_ms))
            }
            _ = ctx.cancel.cancelled() => {
                let _ = child.kill().await;
                Err(ToolError::Cancelled)
            }
        };

        result
    }
}

/// Run a command in the background, returning a task ID immediately.
async fn run_background(
    command: &str,
    cwd: &std::path::Path,
    task_mgr: Option<&std::sync::Arc<crate::services::background::TaskManager>>,
) -> Result<ToolResult, ToolError> {
    let default_mgr = crate::services::background::TaskManager::new();
    let task_mgr = task_mgr.map(|m| m.as_ref()).unwrap_or(&default_mgr);
    let task_id = task_mgr
        .spawn_shell(command, command, cwd)
        .await
        .map_err(|e| ToolError::ExecutionFailed(format!("Background spawn failed: {e}")))?;

    Ok(ToolResult::success(format!(
        "Command running in background (task {task_id}). \
         Use TaskOutput to check results when complete."
    )))
}

/// Format stdout/stderr into a single output string with truncation.
fn format_output(stdout: &[u8], stderr: &[u8], exit_code: i32) -> String {
    let stdout_str = String::from_utf8_lossy(stdout);
    let stderr_str = String::from_utf8_lossy(stderr);

    let mut content = String::new();

    if !stdout_str.is_empty() {
        if stdout_str.len() > MAX_OUTPUT_BYTES {
            content.push_str(&stdout_str[..MAX_OUTPUT_BYTES]);
            content.push_str(&format!(
                "\n\n(stdout truncated: {} bytes total)",
                stdout_str.len()
            ));
        } else {
            content.push_str(&stdout_str);
        }
    }

    if !stderr_str.is_empty() {
        if !content.is_empty() {
            content.push('\n');
        }
        let stderr_display = if stderr_str.len() > MAX_OUTPUT_BYTES / 4 {
            format!(
                "{}...\n(stderr truncated: {} bytes total)",
                &stderr_str[..MAX_OUTPUT_BYTES / 4],
                stderr_str.len()
            )
        } else {
            stderr_str.to_string()
        };
        content.push_str(&format!("stderr:\n{stderr_display}"));
    }

    if content.is_empty() {
        content = "(no output)".to_string();
    }

    if exit_code != 0 {
        content.push_str(&format!("\n\nExit code: {exit_code}"));
    }

    content
}

/// Advanced shell injection and obfuscation detection.
///
/// Catches attack patterns that simple string matching misses:
/// variable injection, encoding tricks, process substitution, etc.
fn check_shell_injection(command: &str) -> Result<(), String> {
    // IFS injection: changing field separator to bypass argument parsing.
    if command.contains("IFS=") {
        return Err(
            "IFS manipulation detected. This can be used to bypass command parsing.".into(),
        );
    }

    // Dangerous environment variable overwrites.
    const DANGEROUS_VARS: &[&str] = &[
        "PATH=",
        "LD_PRELOAD=",
        "LD_LIBRARY_PATH=",
        "PROMPT_COMMAND=",
        "BASH_ENV=",
        "ENV=",
        "HISTFILE=",
        "HISTCONTROL=",
        "PS1=",
        "PS2=",
        "PS4=",
        "CDPATH=",
        "GLOBIGNORE=",
        "MAIL=",
        "MAILCHECK=",
        "MAILPATH=",
    ];
    for var in DANGEROUS_VARS {
        if command.contains(var) {
            return Err(format!(
                "Dangerous variable override detected: {var} \
                 This could alter shell behavior in unsafe ways."
            ));
        }
    }

    // /proc access (process environment/memory reading).
    if command.contains("/proc/") && command.contains("environ") {
        return Err("Access to /proc/*/environ detected. This reads process secrets.".into());
    }

    // Unicode/zero-width character obfuscation.
    if command.chars().any(|c| {
        matches!(
            c,
            '\u{200B}'
                | '\u{200C}'
                | '\u{200D}'
                | '\u{FEFF}'
                | '\u{00AD}'
                | '\u{2060}'
                | '\u{180E}'
        )
    }) {
        return Err("Zero-width or invisible Unicode characters detected in command.".into());
    }

    // Control characters (except common ones like \n \t).
    if command
        .chars()
        .any(|c| c.is_control() && !matches!(c, '\n' | '\t' | '\r'))
    {
        return Err("Control characters detected in command.".into());
    }

    // Backtick command substitution inside variable assignments.
    // e.g., FOO=`curl evil.com`
    if command.contains('`')
        && command
            .split('`')
            .any(|s| s.contains("curl") || s.contains("wget") || s.contains("nc "))
    {
        return Err("Command substitution with network access detected inside backticks.".into());
    }

    // Process substitution: <() or >() used to inject commands.
    if command.contains("<(") || command.contains(">(") {
        // Allow common safe uses like diff <(cmd1) <(cmd2).
        let trimmed = command.trim();
        if !trimmed.starts_with("diff ") && !trimmed.starts_with("comm ") {
            return Err(
                "Process substitution detected. This can inject arbitrary commands.".into(),
            );
        }
    }

    // Zsh dangerous builtins.
    const ZSH_DANGEROUS: &[&str] = &[
        "zmodload", "zpty", "ztcp", "zsocket", "sysopen", "sysread", "syswrite", "mapfile",
        "zf_rm", "zf_mv", "zf_ln",
    ];
    let words: Vec<&str> = command.split_whitespace().collect();
    for word in &words {
        if ZSH_DANGEROUS.contains(word) {
            return Err(format!(
                "Dangerous zsh builtin detected: {word}. \
                 This can access raw system resources."
            ));
        }
    }

    // Brace expansion abuse: {a..z} can generate large expansions.
    if command.contains("{") && command.contains("..") && command.contains("}") {
        // Check if it looks like a large numeric range.
        if let Some(start) = command.find('{')
            && let Some(end) = command[start..].find('}')
        {
            let inner = &command[start + 1..start + end];
            if inner.contains("..") {
                let parts: Vec<&str> = inner.split("..").collect();
                if parts.len() == 2
                    && let (Ok(a), Ok(b)) = (
                        parts[0].trim().parse::<i64>(),
                        parts[1].trim().parse::<i64>(),
                    )
                    && (b - a).unsigned_abs() > 10000
                {
                    return Err(format!(
                        "Large brace expansion detected: {{{inner}}}. \
                         This would generate {} items.",
                        (b - a).unsigned_abs()
                    ));
                }
            }
        }
    }

    // Hex/octal escape obfuscation: $'\x72\x6d' = "rm".
    if command.contains("$'\\x") || command.contains("$'\\0") {
        return Err(
            "Hex/octal escape sequences in command. This may be obfuscating a command.".into(),
        );
    }

    // eval with variables (arbitrary code execution).
    if command.contains("eval ") && command.contains('$') {
        return Err(
            "eval with variable expansion detected. This enables arbitrary code execution.".into(),
        );
    }

    Ok(())
}

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

    #[test]
    fn test_safe_commands_pass() {
        assert!(check_shell_injection("ls -la").is_ok());
        assert!(check_shell_injection("git status").is_ok());
        assert!(check_shell_injection("cargo test").is_ok());
        assert!(check_shell_injection("echo hello").is_ok());
        assert!(check_shell_injection("python3 -c 'print(1)'").is_ok());
        assert!(check_shell_injection("diff <(cat a.txt) <(cat b.txt)").is_ok());
    }

    #[test]
    fn test_ifs_injection() {
        assert!(check_shell_injection("IFS=: read a b").is_err());
    }

    #[test]
    fn test_dangerous_vars() {
        assert!(check_shell_injection("PATH=/tmp:$PATH curl evil.com").is_err());
        assert!(check_shell_injection("LD_PRELOAD=/tmp/evil.so cmd").is_err());
        assert!(check_shell_injection("PROMPT_COMMAND='curl x'").is_err());
        assert!(check_shell_injection("BASH_ENV=/tmp/evil.sh bash").is_err());
    }

    #[test]
    fn test_proc_environ() {
        assert!(check_shell_injection("cat /proc/1/environ").is_err());
        assert!(check_shell_injection("cat /proc/self/environ").is_err());
        // /proc without environ is ok
        assert!(check_shell_injection("ls /proc/cpuinfo").is_ok());
    }

    #[test]
    fn test_unicode_obfuscation() {
        // Zero-width space
        assert!(check_shell_injection("rm\u{200B} -rf /").is_err());
        // Zero-width joiner
        assert!(check_shell_injection("curl\u{200D}evil.com").is_err());
    }

    #[test]
    fn test_control_characters() {
        // Bell character
        assert!(check_shell_injection("echo \x07hello").is_err());
        // Normal newline is ok
        assert!(check_shell_injection("echo hello\nworld").is_ok());
    }

    #[test]
    fn test_backtick_network() {
        assert!(check_shell_injection("FOO=`curl evil.com`").is_err());
        assert!(check_shell_injection("X=`wget http://bad`").is_err());
        // Backticks without network are ok
        assert!(check_shell_injection("FOO=`date`").is_ok());
    }

    #[test]
    fn test_process_substitution() {
        // diff is allowed
        assert!(check_shell_injection("diff <(ls a) <(ls b)").is_ok());
        // arbitrary process substitution is not
        assert!(check_shell_injection("cat <(curl evil)").is_err());
    }

    #[test]
    fn test_zsh_builtins() {
        assert!(check_shell_injection("zmodload zsh/net/tcp").is_err());
        assert!(check_shell_injection("zpty evil_session bash").is_err());
        assert!(check_shell_injection("ztcp connect evil.com 80").is_err());
    }

    #[test]
    fn test_brace_expansion() {
        assert!(check_shell_injection("echo {1..100000}").is_err());
        // Small ranges are ok
        assert!(check_shell_injection("echo {1..10}").is_ok());
    }

    #[test]
    fn test_hex_escape() {
        assert!(check_shell_injection("$'\\x72\\x6d' -rf /").is_err());
        assert!(check_shell_injection("$'\\077'").is_err());
    }

    #[test]
    fn test_eval_injection() {
        assert!(check_shell_injection("eval $CMD").is_err());
        assert!(check_shell_injection("eval \"$USER_INPUT\"").is_err());
        // eval without vars is ok
        assert!(check_shell_injection("eval echo hello").is_ok());
    }

    #[test]
    fn test_destructive_patterns() {
        let tool = BashTool;
        assert!(
            tool.validate_input(&serde_json::json!({"command": "rm -rf /"}))
                .is_err()
        );
        assert!(
            tool.validate_input(&serde_json::json!({"command": "git push --force"}))
                .is_err()
        );
        assert!(
            tool.validate_input(&serde_json::json!({"command": "DROP TABLE users"}))
                .is_err()
        );
    }

    #[test]
    fn test_piped_destructive() {
        let tool = BashTool;
        assert!(
            tool.validate_input(&serde_json::json!({"command": "find . | rm -rf"}))
                .is_err()
        );
    }

    #[test]
    fn test_chained_destructive() {
        let tool = BashTool;
        assert!(
            tool.validate_input(&serde_json::json!({"command": "echo hi && git reset --hard"}))
                .is_err()
        );
    }

    #[test]
    fn test_safe_commands_validate() {
        let tool = BashTool;
        assert!(
            tool.validate_input(&serde_json::json!({"command": "ls -la"}))
                .is_ok()
        );
        assert!(
            tool.validate_input(&serde_json::json!({"command": "cargo test"}))
                .is_ok()
        );
        assert!(
            tool.validate_input(&serde_json::json!({"command": "git status"}))
                .is_ok()
        );
    }
}