agent-file-tools 0.22.1

Agent File Tools — tree-sitter powered code analysis for AI 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
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
use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};

use tree_sitter::{Node, Parser};

use crate::context::AppContext;

use super::{arity, PermissionAsk, PermissionKind};

const FILE_COMMANDS: &[&str] = &[
    "rm", "cp", "mv", "mkdir", "touch", "chmod", "chown", "cat", "cd", "source", ".",
];
const CWD_COMMANDS: &[&str] = &["cd", "pushd", "popd"];

#[derive(Debug, Clone)]
struct Part {
    text: String,
}

pub fn scan(command: &str, ctx: &AppContext) -> Vec<PermissionAsk> {
    #[cfg(windows)]
    {
        let _ = (command, ctx);
        return Vec::new();
    }

    #[cfg(not(windows))]
    {
        let config = ctx.config();
        if !config.bash_permissions {
            return Vec::new();
        }
        let Some(project_root) = config.project_root.clone() else {
            return Vec::new();
        };
        drop(config);

        scan_with_cwd(command, ctx, &project_root)
    }
}

pub fn scan_with_cwd(command: &str, ctx: &AppContext, cwd: &Path) -> Vec<PermissionAsk> {
    let Some(project_root) = ctx.config().project_root.clone() else {
        return Vec::new();
    };
    let project_root = resolve_existing(&project_root);
    let cwd = resolve_existing(cwd);

    let mut parser = Parser::new();
    if parser
        .set_language(&tree_sitter_bash::LANGUAGE.into())
        .is_err()
    {
        // Fail closed: if we can't even load the bash grammar we cannot
        // verify the command is safe, so require explicit permission via
        // a wildcard ask rather than silently letting the command run.
        // This was previously `return Vec::new()` which created a hard
        // bypass of the user's bash permission rules whenever grammar
        // loading failed.
        return vec![parse_failed_ask()];
    }

    let Some(tree) = parser.parse(command, None) else {
        return vec![parse_failed_ask()];
    };

    let root = tree.root_node();
    if root.has_error() {
        return vec![parse_failed_ask()];
    }
    let mut command_nodes = Vec::new();
    collect_commands(root, &mut command_nodes);

    // Fail-closed: tree-sitter parsed successfully but found NO `command`
    // nodes, yet the input has visible content. This happens for shapes
    // that have side effects without invoking a command word, e.g.:
    //   - pure redirects:  `> /tmp/x` (truncate file)
    //   - variable-only:   `FOO=bar`  (set shell variable)
    //   - empty subshell:  `()`
    // Without this fall-back the `bash.rs` guard
    // `if !permission_asks.is_empty()` skips the permission check
    // entirely and the user's `bash: { "*": deny }` rule is bypassed.
    //
    // Pure `cd` does NOT trigger this branch because tree-sitter still
    // produces a `command` node for it; the cd handling above just
    // chooses not to push an ask for that node, which matches OpenCode
    // and is intentional (cd has no externally visible effect beyond
    // updating scan_cwd, already handled).
    if command_nodes.is_empty() && !command.trim().is_empty() {
        return vec![parse_failed_ask()];
    }

    let mut asks = Vec::new();
    let mut seen = HashSet::new();
    let mut scan_cwd = cwd.clone();
    for node in command_nodes {
        let parts = command_parts(command, node);
        if parts.is_empty() {
            continue;
        }

        let tokens: Vec<String> = parts.iter().map(|part| part.text.clone()).collect();
        let head = tokens[0].as_str();

        if head == "cd" {
            if let Some(arg) = path_args(&parts).next() {
                if let Some(path) = arg_path(arg, &scan_cwd) {
                    scan_cwd = path;
                }
            }
            continue;
        }

        if FILE_COMMANDS.contains(&head) {
            for arg in path_args(&parts) {
                let Some(path) = arg_path(arg, &scan_cwd) else {
                    continue;
                };
                push_external_path(&mut asks, &mut seen, &project_root, &path);
            }
        }

        collect_redirection_targets(command, node, &scan_cwd, |target| match target {
            RedirectTarget::Path(path) => {
                push_external_path(&mut asks, &mut seen, &project_root, &path);
            }
            RedirectTarget::Dynamic => push_external_wildcard(&mut asks, &mut seen),
        });

        // Mirror OpenCode's `packages/opencode/src/tool/bash.ts`: only
        // skip `cd`/`pushd`/`popd` (they have no externally visible effect
        // beyond updating scan_cwd, already handled above). Every other
        // command — including `echo` — must produce a bash ask so the
        // user's permission rules (`bash: { "*": deny, ... }`) actually
        // apply. Previous code excluded `echo` here, which let any
        // command starting with `echo` bypass deny rules.
        if !CWD_COMMANDS.contains(&head) {
            push_bash_ask(&mut asks, &mut seen, source(command, node), &tokens);
            if head == "xargs" {
                push_xargs_ask(&mut asks, &mut seen, &tokens);
            }
        }
    }

    asks
}

fn parse_failed_ask() -> PermissionAsk {
    PermissionAsk {
        kind: PermissionKind::Bash,
        patterns: vec!["*".to_string()],
        always: Vec::new(),
    }
}

fn collect_commands<'tree>(node: Node<'tree>, out: &mut Vec<Node<'tree>>) {
    if node.kind() == "command" {
        out.push(node);
    }

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_commands(child, out);
    }
}

fn command_parts(source: &str, node: Node<'_>) -> Vec<Part> {
    let mut out = Vec::new();

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "command_elements" {
            let mut element_cursor = child.walk();
            for item in child.children(&mut element_cursor) {
                if item.kind() == "command_argument_sep" || item.kind() == "redirection" {
                    continue;
                }
                out.push(Part {
                    text: node_text(source, item).to_string(),
                });
            }
            continue;
        }

        if matches!(
            child.kind(),
            "command_name"
                | "command_name_expr"
                | "word"
                | "string"
                | "raw_string"
                | "concatenation"
        ) {
            out.push(Part {
                text: node_text(source, child).to_string(),
            });
        }
    }

    out
}

fn source(command: &str, node: Node<'_>) -> String {
    let node = node
        .parent()
        .filter(|parent| parent.kind() == "redirected_statement")
        .unwrap_or(node);
    node_text(command, node).trim().to_string()
}

fn node_text<'source>(source: &'source str, node: Node<'_>) -> &'source str {
    node.utf8_text(source.as_bytes()).unwrap_or("")
}

enum RedirectTarget {
    Path(PathBuf),
    Dynamic,
}

fn collect_redirection_targets(
    source: &str,
    command: Node<'_>,
    cwd: &Path,
    mut on_target: impl FnMut(RedirectTarget),
) {
    // In tree-sitter-bash, redirects on `echo hi > /tmp/out` are siblings of
    // the `command` node, wrapped inside `redirected_statement`. Walking
    // `command.children` would miss them. Walk from the parent
    // (`redirected_statement`) when present, otherwise fall back to walking
    // `command` itself in case a future grammar version inlines redirections
    // under `command`.
    let walk_root = match command.parent() {
        Some(parent) if parent.kind() == "redirected_statement" => parent,
        _ => command,
    };
    let mut cursor = walk_root.walk();
    for child in walk_root.children(&mut cursor) {
        // Skip the inner `command` node itself — its children are arguments,
        // not redirections, and re-walking them is just wasted work.
        if child.id() == command.id() {
            continue;
        }
        collect_redirection_targets_from_node(source, child, cwd, &mut on_target);
    }
}

fn collect_redirection_targets_from_node(
    source: &str,
    node: Node<'_>,
    cwd: &Path,
    on_target: &mut impl FnMut(RedirectTarget),
) {
    // tree-sitter-bash 0.25.x emits `file_redirect` and `heredoc_redirect`
    // (and `redirection` in some shapes). All three carry a redirect target
    // as a child `word`/`file`/`raw_string`/`string`/`concatenation`/
    // `simple_expansion`/`expansion`/`command_substitution`.
    if matches!(
        node.kind(),
        "file_redirect" | "heredoc_redirect" | "herestring_redirect" | "redirection"
    ) {
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if is_dynamic_node(child) {
                on_target(RedirectTarget::Dynamic);
                continue;
            }
            if matches!(
                child.kind(),
                "word" | "file" | "raw_string" | "string" | "concatenation"
            ) {
                let text = node_text(source, child);
                if dynamic(text) {
                    on_target(RedirectTarget::Dynamic);
                } else if let Some(path) = arg_path(text, cwd) {
                    on_target(RedirectTarget::Path(path));
                }
            }
        }
        return;
    }

    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        collect_redirection_targets_from_node(source, child, cwd, on_target);
    }
}

fn is_dynamic_node(node: Node<'_>) -> bool {
    matches!(
        node.kind(),
        "expansion" | "command_substitution" | "simple_expansion"
    )
}

fn path_args(parts: &[Part]) -> impl Iterator<Item = &str> {
    let head = parts.first().map(|part| part.text.as_str()).unwrap_or("");
    parts.iter().skip(1).filter_map(move |part| {
        if part.text.starts_with('-') || (head == "chmod" && part.text.starts_with('+')) {
            None
        } else {
            Some(part.text.as_str())
        }
    })
}

fn arg_path(arg: &str, cwd: &Path) -> Option<PathBuf> {
    let text = home(&unquote(arg));
    let text = glob_prefix(&text)?;
    if dynamic(text) {
        return None;
    }

    let path = PathBuf::from(text);
    let resolved = if path.is_absolute() {
        path
    } else {
        cwd.join(path)
    };
    Some(resolve_existing(&resolved))
}

fn unquote(text: &str) -> String {
    if text.len() < 2 {
        return text.to_string();
    }
    let bytes = text.as_bytes();
    let first = bytes[0];
    let last = bytes[bytes.len() - 1];
    if (first == b'\'' || first == b'"') && first == last {
        text[1..text.len() - 1].to_string()
    } else {
        text.to_string()
    }
}

fn home(text: &str) -> String {
    if text == "~" {
        return std::env::var("HOME").unwrap_or_else(|_| text.to_string());
    }
    if let Some(rest) = text.strip_prefix("~/") {
        if let Ok(home) = std::env::var("HOME") {
            return Path::new(&home).join(rest).to_string_lossy().into_owned();
        }
    }
    text.replace("$HOME", &std::env::var("HOME").unwrap_or_default())
        .replace("${HOME}", &std::env::var("HOME").unwrap_or_default())
        .replace(
            "$PWD",
            &std::env::current_dir()
                .unwrap_or_default()
                .to_string_lossy(),
        )
        .replace(
            "${PWD}",
            &std::env::current_dir()
                .unwrap_or_default()
                .to_string_lossy(),
        )
}

fn glob_prefix(text: &str) -> Option<&str> {
    match text.find(['?', '*', '[']) {
        Some(0) => None,
        Some(index) => Some(&text[..index]),
        None => Some(text),
    }
}

fn dynamic(text: &str) -> bool {
    text.starts_with('(')
        || text.contains("$(")
        || text.contains("${")
        || text.contains('`')
        || text.contains('$')
}

fn resolve_existing(path: &Path) -> PathBuf {
    std::fs::canonicalize(path).unwrap_or_else(|_| normalize_path(path))
}

fn normalize_path(path: &Path) -> PathBuf {
    let mut result = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                if !result.pop() {
                    result.push(component.as_os_str());
                }
            }
            other => result.push(other.as_os_str()),
        }
    }
    result
}

fn permission_dir(path: &Path) -> PathBuf {
    if path.is_dir() {
        path.to_path_buf()
    } else {
        path.parent().unwrap_or(path).to_path_buf()
    }
}

fn display_path(path: &Path) -> String {
    path.to_string_lossy().into_owned()
}

fn push_bash_ask(
    asks: &mut Vec<PermissionAsk>,
    seen: &mut HashSet<String>,
    pattern: String,
    tokens: &[String],
) {
    let stable = arity::prefix(tokens).join(" ");
    if stable.is_empty() {
        return;
    }
    push_ask(
        asks,
        seen,
        PermissionAsk {
            kind: PermissionKind::Bash,
            patterns: vec![pattern],
            always: vec![format!("{stable} *")],
        },
    );
}

fn push_xargs_ask(asks: &mut Vec<PermissionAsk>, seen: &mut HashSet<String>, tokens: &[String]) {
    let mut index = 1;
    while index < tokens.len() && tokens[index].starts_with('-') {
        index += 1;
    }
    if index >= tokens.len() {
        return;
    }
    push_bash_ask(asks, seen, tokens[index..].join(" "), &tokens[index..]);
}

fn push_external_path(
    asks: &mut Vec<PermissionAsk>,
    seen: &mut HashSet<String>,
    project_root: &Path,
    path: &Path,
) {
    if path.starts_with(project_root) {
        return;
    }
    let dir = permission_dir(path);
    let pattern = format!("{}/*", display_path(&dir));
    push_ask(
        asks,
        seen,
        PermissionAsk {
            kind: PermissionKind::ExternalDirectory,
            patterns: vec![pattern.clone()],
            always: vec![pattern],
        },
    );
}

fn push_external_wildcard(asks: &mut Vec<PermissionAsk>, seen: &mut HashSet<String>) {
    push_ask(
        asks,
        seen,
        PermissionAsk {
            kind: PermissionKind::ExternalDirectory,
            patterns: vec!["*".to_string()],
            always: vec!["*".to_string()],
        },
    );
}

fn push_ask(asks: &mut Vec<PermissionAsk>, seen: &mut HashSet<String>, ask: PermissionAsk) {
    let key = format!("{:?}:{:?}:{:?}", ask.kind, ask.patterns, ask.always);
    if seen.insert(key) {
        asks.push(ask);
    }
}