caliban-agent-core 0.4.0

Agent loop, tool dispatch, cancellation, retry, compaction, and hooks for the caliban agent harness — internal crate for the caliban binary; no API stability, pin exact versions
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
//! v2 pattern matcher: `*`, `?`, `**`, `~glob` anywhere-match for Bash,
//! dotted-key MCP arg accessors, and workspace-normalized paths for
//! file-edit tools.

use crate::hooks::ToolCtx;

/// Match `pattern` against `ctx` using the workspace root inferred from `git`.
/// See [`matches_with_workspace`] for the full pattern grammar.
pub fn matches(pattern: &str, ctx: &ToolCtx<'_>) -> bool {
    matches_with_workspace(pattern, ctx, &workspace_root())
}

/// Return the current workspace root by asking `git rev-parse --show-toplevel`.
/// Falls back to the current working directory if git is unavailable or fails.
pub fn workspace_root() -> std::path::PathBuf {
    // Best-effort: ask git for the toplevel; fall back to cwd.
    if let Ok(out) = std::process::Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .output()
        && out.status.success()
    {
        let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
        if !s.is_empty() {
            return std::path::PathBuf::from(s);
        }
    }
    std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."))
}

fn split_pattern(pattern: &str) -> (&str, Option<&str>) {
    pattern
        .split_once(':')
        .map_or((pattern, None), |(name, spec)| (name, Some(spec)))
}

fn is_file_edit_tool(name: &str) -> bool {
    matches!(
        name,
        "Read" | "Write" | "Edit" | "MultiEdit" | "NotebookEdit"
    )
}

fn glob_match(pat: &str, hay: &str) -> bool {
    // Uniform glob via `globset` with literal_separator=false so `*` and `**`
    // both behave intuitively for non-path inputs (URLs, commands).
    let g = globset::GlobBuilder::new(pat)
        .literal_separator(false)
        .build();
    match g {
        Ok(g) => g.compile_matcher().is_match(hay),
        Err(_) => false, // bad pattern => never match (loud at config time)
    }
}

fn glob_match_path(pat: &str, hay: &std::path::Path) -> bool {
    let g = globset::GlobBuilder::new(pat)
        .literal_separator(true) // for path globs, `*` doesn't cross `/`
        .build();
    match g {
        Ok(g) => g.compile_matcher().is_match(hay),
        Err(_) => false,
    }
}

/// Match `pattern` against `ctx`, treating `workspace` as the repo root for
/// path normalization. Exported for testing and `caliban perms test/explain`.
///
/// # Pattern grammar
///
/// - `Tool` — match any invocation of `Tool`.
/// - `Tool:<glob>` — glob the tool's first arg (`*`, `?`, `**`).
/// - `Bash:~<glob>` — match anywhere in the bash command (sliding-window).
/// - `Tool:key=<glob>` / `Tool:k1.k2=<glob>` — dotted-key accessor; comma-separated pairs are AND-combined.
/// - `*` — catch-all.
///
/// For file-edit tools (`Read`, `Write`, `Edit`, `MultiEdit`, `NotebookEdit`) the file path
/// is workspace-normalized and relative patterns implicitly anchor with `**/`.
pub fn matches_with_workspace(
    pattern: &str,
    ctx: &ToolCtx<'_>,
    workspace: &std::path::Path,
) -> bool {
    let (tool_pat, arg_pat) = split_pattern(pattern);
    if tool_pat != "*" && !glob_match(tool_pat, ctx.tool_name) {
        return false;
    }
    let Some(spec) = arg_pat else {
        return true;
    };

    // ~glob: match anywhere in the Bash command line.
    if let Some(rest) = spec.strip_prefix('~') {
        if ctx.tool_name != "Bash" {
            return false;
        }
        let cmd = ctx
            .input
            .get("command")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        return contains_glob(rest, cmd);
    }

    // dotted-key=value pairs: AND-combined.
    if spec.contains('=') {
        return spec.split(',').all(|kv| kv_match(kv, ctx.input));
    }

    // Path globs for file-edit tools — workspace-normalize both sides.
    if is_file_edit_tool(ctx.tool_name) {
        // File-edit tools deserialize as `{"path": "..."}`; the canonical
        // accessor lives in `caliban_common` so all permission codepaths
        // agree on the key (previously this site looked up "file_path",
        // which silently produced an empty target and made every
        // `Tool:<glob>` rule a no-op for MultiEdit/NotebookEdit).
        let raw = first_arg(ctx).unwrap_or_default();
        // `workspace_normalize` lexically resolves `.`/`..` so a traversal in
        // the input can't slip past the anchored glob below (#216).
        let target = workspace_normalize(&raw, workspace);
        let spec_path = std::path::Path::new(spec);
        if spec_path.is_absolute() {
            // Absolute pattern: match directly against the normalized target.
            return glob_match_path(spec, &target);
        }
        // Relative (workspace-scoped) pattern. The normalized target must stay
        // *inside* the workspace — a `..` escape (e.g. `../../etc/passwd`) that
        // resolves outside it must never match a workspace-scoped rule (#216,
        // gap in #177). #177 only blocked a same-named subtree elsewhere; it
        // didn't resolve `..`, so `<ws>/../../etc/passwd` still matched a
        // `<ws>/**`-anchored glob.
        if !target.starts_with(workspace) {
            return false;
        }
        // Strip a leading `./`, then anchor to the workspace root so the
        // pattern stays inside the repo. `<ws>/**/<stripped>` lets `src/**`
        // match at any depth within the workspace. Escape the workspace prefix
        // so a literal path containing glob metacharacters isn't reinterpreted.
        let stripped = spec.strip_prefix("./").unwrap_or(spec);
        let ws = globset::escape(&workspace.to_string_lossy());
        let glob_pat = format!("{ws}/**/{stripped}");
        return glob_match_path(&glob_pat, &target);
    }

    // Default: glob over the first-arg string of known tools.
    let first = first_arg(ctx).unwrap_or_default();
    glob_match(spec, &first)
}

/// Thin wrapper around the canonical [`caliban_common::glob_match::first_arg`]
/// so the matcher and the rest of caliban agree on the JSON key used to
/// extract a tool's first arg (e.g. `path` for file-edit tools).
fn first_arg(ctx: &ToolCtx<'_>) -> Option<String> {
    caliban_common::glob_match::first_arg(ctx.tool_name, ctx.input)
}

fn contains_glob(pat: &str, hay: &str) -> bool {
    // Sliding-window glob match. Cheap because hay is short (a shell line).
    for i in 0..=hay.len() {
        for j in i..=hay.len() {
            if !hay.is_char_boundary(i) || !hay.is_char_boundary(j) {
                continue;
            }
            if glob_match(pat, &hay[i..j]) {
                return true;
            }
        }
    }
    false
}

fn kv_match(kv: &str, input: &serde_json::Value) -> bool {
    let Some((key, glob)) = kv.split_once('=') else {
        return false;
    };
    let mut cursor = input;
    for part in key.split('.') {
        match cursor.get(part) {
            Some(next) => cursor = next,
            None => return glob_match(glob, ""), // missing key → empty
        }
    }
    let val = cursor.as_str().unwrap_or("");
    glob_match(glob, val)
}

fn workspace_normalize(p: &str, workspace: &std::path::Path) -> std::path::PathBuf {
    let path = std::path::Path::new(p);
    let joined = if path.is_absolute() {
        path.to_path_buf()
    } else {
        let stripped: &std::path::Path = path.strip_prefix("./").unwrap_or(path);
        workspace.join(stripped)
    };
    lexical_normalize(&joined)
}

/// Resolve `.` and `..` components purely lexically (no filesystem access, so
/// it works for paths that don't exist and never follows symlinks). A leading
/// `..` that can't be popped is preserved so the result still lies outside any
/// absolute prefix — that's what lets the caller detect a workspace escape
/// (#216).
fn lexical_normalize(p: &std::path::Path) -> std::path::PathBuf {
    use std::path::Component;
    let mut out = std::path::PathBuf::new();
    for comp in p.components() {
        match comp {
            Component::CurDir => {}
            Component::ParentDir => match out.components().next_back() {
                // Pop a preceding normal component …
                Some(Component::Normal(_)) => {
                    out.pop();
                }
                // … otherwise keep the `..` (root / leading `..` / `..` chain)
                // so the result still lies outside the prefix we joined onto —
                // that's what lets the caller detect a workspace escape (#216).
                _ => out.push(".."),
            },
            other => out.push(other.as_os_str()),
        }
    }
    out
}

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

    fn ctx<'a>(name: &'a str, input: &'a serde_json::Value) -> ToolCtx<'a> {
        ToolCtx {
            session_id: "test-session",
            turn_index: 0,
            tool_use_id: "t",
            tool_name: name,
            input,
            is_read_only: false,
        }
    }

    #[test]
    fn globstar_path_matches_nested_rs_file() {
        // File-edit tools deserialize their JSON input as `{"path": "..."}`
        // — see caliban-tools-builtin/src/fs/{edit,multi_edit,...}.rs. The
        // matcher must look up the same key.
        let ws = std::path::Path::new("/repo");
        let i = json!({"path": "/repo/crates/x/src/y.rs"});
        assert!(
            matches_with_workspace("Edit:src/**/*.rs", &ctx("Edit", &i), ws),
            "globstar should match nested .rs under the workspace src tree"
        );
    }

    #[test]
    fn relative_pattern_does_not_escape_workspace() {
        // Security (#177): a relative file-edit pattern must scope to the
        // workspace. It must NOT match a same-named subtree elsewhere on the
        // filesystem.
        let ws = std::path::Path::new("/repo");
        let outside = json!({"path": "/etc/src/evil.rs"});
        assert!(
            !matches_with_workspace("Edit:src/**/*.rs", &ctx("Edit", &outside), ws),
            "relative pattern must be workspace-scoped, must not match /etc/src/..."
        );
        let home = json!({"path": "/home/attacker/src/evil.rs"});
        assert!(
            !matches_with_workspace("Edit:src/**/*.rs", &ctx("Edit", &home), ws),
            "relative pattern must not match /home/attacker/src/..."
        );
        // Still matches inside the workspace, at any depth.
        let inside = json!({"path": "/repo/crates/x/src/y.rs"});
        assert!(
            matches_with_workspace("Edit:src/**/*.rs", &ctx("Edit", &inside), ws),
            "relative pattern must still match src/** anywhere under the workspace"
        );
    }

    #[test]
    fn dotdot_traversal_does_not_escape_workspace() {
        // Security (#216, gap in #177): a `..` traversal in the input path must
        // not let a workspace-scoped Allow match a file outside the workspace.
        let ws = std::path::Path::new("/repo");
        let escape = json!({"path": "../../../../etc/passwd"});
        assert!(
            !matches_with_workspace("Edit:**", &ctx("Edit", &escape), ws),
            "workspace-scoped Edit:** must not match a ../ traversal outside the workspace"
        );
        // An absolute-but-traversing input normalizes and is rejected too.
        let escape_abs = json!({"path": "/repo/../../etc/passwd"});
        assert!(
            !matches_with_workspace("Edit:**", &ctx("Edit", &escape_abs), ws),
            "a path that lexically escapes the workspace must not match a workspace-scoped rule"
        );
        // Sanity: an in-workspace relative path still matches.
        let inside = json!({"path": "src/main.rs"});
        assert!(
            matches_with_workspace("Edit:**", &ctx("Edit", &inside), ws),
            "in-workspace relative path still matches Edit:**"
        );
        // And `..` that stays inside the workspace is fine.
        let inside_dotdot = json!({"path": "crates/x/../y/z.rs"});
        assert!(
            matches_with_workspace("Edit:**", &ctx("Edit", &inside_dotdot), ws),
            "a `..` that resolves to a path still inside the workspace matches"
        );
    }

    #[test]
    fn path_normalization_handles_relative_pattern() {
        let ws = std::path::Path::new("/repo");
        let i = json!({"path": "/repo/foo.rs"});
        assert!(matches_with_workspace(
            "Edit:./foo.rs",
            &ctx("Edit", &i),
            ws
        ));
        assert!(matches_with_workspace("Edit:foo.rs", &ctx("Edit", &i), ws));
    }

    #[test]
    fn multi_edit_path_matches_workspace_glob() {
        // Regression: prior to the path-key fix, MultiEdit rules never
        // matched any input because the matcher looked up "file_path"
        // while the tool's input shape is `{"path": "...", "edits": [...]}`.
        let ws = std::path::Path::new("/repo");
        let i = json!({"path": "/repo/src/foo.rs", "edits": []});
        assert!(
            matches_with_workspace("MultiEdit:src/**/*.rs", &ctx("MultiEdit", &i), ws),
            "MultiEdit rule must match against the tool's `path` field"
        );
    }

    #[test]
    fn notebook_edit_path_matches_workspace_glob() {
        // Same regression as MultiEdit — NotebookEdit also uses `path`.
        let ws = std::path::Path::new("/repo");
        let i = json!({"path": "/repo/nb.ipynb", "cell_id": "x", "new_source": ""});
        assert!(matches_with_workspace(
            "NotebookEdit:**/*.ipynb",
            &ctx("NotebookEdit", &i),
            ws
        ));
    }

    #[test]
    fn bash_anywhere_catches_sudo() {
        let i = json!({"command": "sudo rm -rf /"});
        assert!(matches_with_workspace(
            "Bash:~rm *",
            &ctx("Bash", &i),
            std::path::Path::new("/")
        ));
    }

    #[test]
    fn bash_anywhere_only_for_bash() {
        let i = json!({"path": "rm"});
        // ~glob on Read is not allowed; should return false (NOT match).
        assert!(!matches_with_workspace(
            "Read:~rm",
            &ctx("Read", &i),
            std::path::Path::new("/")
        ));
    }

    #[test]
    fn mcp_dotted_key_matches() {
        let i = json!({"repo": "anthropic/caliban", "title": "feat"});
        assert!(matches_with_workspace(
            "mcp__github__create_issue:repo=anthropic/*",
            &ctx("mcp__github__create_issue", &i),
            std::path::Path::new("/")
        ));
    }

    #[test]
    fn mcp_multi_kv_all_must_match() {
        let i = json!({"repo": "anthropic/caliban", "title": "feat"});
        assert!(matches_with_workspace(
            "mcp__github__create_issue:repo=anthropic/*,title=feat*",
            &ctx("mcp__github__create_issue", &i),
            std::path::Path::new("/")
        ));
        assert!(!matches_with_workspace(
            "mcp__github__create_issue:repo=anthropic/*,title=docs*",
            &ctx("mcp__github__create_issue", &i),
            std::path::Path::new("/")
        ));
    }

    #[test]
    fn first_arg_fallback_preserved() {
        let i = json!({"command": "git push"});
        assert!(matches_with_workspace(
            "Bash:git *",
            &ctx("Bash", &i),
            std::path::Path::new("/")
        ));
        assert!(!matches_with_workspace(
            "Bash:git *",
            &ctx("Bash", &json!({"command": "gitk"})),
            std::path::Path::new("/")
        ));
    }

    #[test]
    fn star_matches_unknown_mcp_tool() {
        let i = json!({});
        assert!(matches_with_workspace(
            "*",
            &ctx("mcp__weird__tool", &i),
            std::path::Path::new("/")
        ));
    }
}