albatross-cli 2.1.0

Open source, terminal-first AI coding agent with fully transparent multi-model routing. Local (Ollama, LM Studio, MLX, llama.cpp) or cloud, your keys, one TUI.
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
use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{json, Value};

use super::{diff::unified_diff, PathPolicy, Tool, ToolPreview};

pub struct FileEditTool {
    pub approve: bool,
    pub path_policy: PathPolicy,
}

#[derive(Deserialize)]
struct Args {
    path: String,
    edits: Vec<Edit>,
}

#[derive(Deserialize)]
struct Edit {
    old_text: String,
    new_text: String,
}

/// Locate the line span that changed between `original` and `updated`, as a
/// half-open `[start, end)` range of 0-based line indices into `updated`.
/// Returns `None` when nothing changed. Uses a common prefix/suffix scan, so a
/// small edit in a large file yields a small span.
fn changed_line_span(original: &str, updated: &str) -> Option<(usize, usize)> {
    let o: Vec<&str> = original.lines().collect();
    let u: Vec<&str> = updated.lines().collect();
    if o == u {
        return None;
    }
    let max_pre = o.len().min(u.len());
    let mut pre = 0;
    while pre < max_pre && o[pre] == u[pre] {
        pre += 1;
    }
    let max_suf = (o.len() - pre).min(u.len() - pre);
    let mut suf = 0;
    while suf < max_suf && o[o.len() - 1 - suf] == u[u.len() - 1 - suf] {
        suf += 1;
    }
    let start = pre;
    // Show at least one line so a pure deletion still anchors somewhere.
    let end = u.len().saturating_sub(suf).max(start + 1).min(u.len());
    Some((start, end))
}

/// Render a line-numbered snippet of `content` covering `[start, end)` plus a
/// few lines of context on each side. Capped so a huge edit can't flood the
/// model's context.
fn numbered_snippet(content: &str, start: usize, end: usize, context: usize) -> String {
    const MAX_LINES: usize = 30;
    let lines: Vec<&str> = content.lines().collect();
    let from = start.saturating_sub(context);
    let full_to = (end + context).min(lines.len());
    let truncated = full_to.saturating_sub(from) > MAX_LINES;
    let to = if truncated { from + MAX_LINES } else { full_to };
    let mut out = String::new();
    for (i, line) in lines.iter().enumerate().take(to).skip(from) {
        out.push_str(&format!("{:>5}  {}\n", i + 1, line));
    }
    if truncated {
        out.push_str("…[snippet truncated]\n");
    }
    out.truncate(out.trim_end().len());
    out
}

#[async_trait]
impl Tool for FileEditTool {
    fn name(&self) -> &'static str {
        "file_edit"
    }
    fn description(&self) -> &'static str {
        "Apply search-and-replace edits to a file. Each old_text must appear exactly once. Returns a unified diff plus the re-read applied state (verified + a line-numbered snippet) so you can confirm the change landed."
    }
    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "path": { "type": "string", "description": "Absolute or relative path to the file" },
                "edits": {
                    "type": "array",
                    "minItems": 1,
                    "items": {
                        "type": "object",
                        "properties": {
                            "old_text": { "type": "string", "description": "Exact text to find (must appear once)" },
                            "new_text": { "type": "string", "description": "Text to replace it with" }
                        },
                        "required": ["old_text", "new_text"]
                    }
                }
            },
            "required": ["path", "edits"]
        })
    }
    fn require_approval(&self, _args: &Value) -> bool {
        self.approve
            || _args
                .get("path")
                .and_then(Value::as_str)
                .map(|p| self.path_policy.require_prompt_for_path(p))
                .unwrap_or(false)
    }
    async fn preview(&self, args: &Value) -> Option<ToolPreview> {
        let args: Args = serde_json::from_value(args.clone()).ok()?;
        let resolved = self.path_policy.resolve(&args.path);
        let original = tokio::fs::read_to_string(&resolved.normalized).await.ok()?;
        let mut working = original.clone();
        for edit in &args.edits {
            if edit.old_text.is_empty() || working.matches(&edit.old_text).count() != 1 {
                return Some(ToolPreview {
                    summary: format!("Edit {}", resolved.normalized.display()),
                    diff: None,
                    risk: Some(
                        "preview unavailable until each old_text matches exactly once".into(),
                    ),
                });
            }
            working = working.replacen(&edit.old_text, &edit.new_text, 1);
        }
        let mut risk = None;
        if resolved.outside_workspace {
            risk = Some(format!(
                "outside workspace root {}",
                self.path_policy.root().display()
            ));
        }
        Some(ToolPreview {
            summary: format!(
                "Edit {} ({} edits)",
                resolved.normalized.display(),
                args.edits.len()
            ),
            diff: Some(unified_diff(
                &original,
                &working,
                &resolved.normalized.display().to_string(),
            )),
            risk,
        })
    }
    async fn execute(&self, args: Value) -> Value {
        let args: Args = match serde_json::from_value(args) {
            Ok(a) => a,
            Err(e) => return json!({ "error": format!("invalid args: {e}") }),
        };
        if let Some(error) = self.path_policy.deny_path(&args.path) {
            return json!({ "error": error });
        }
        let resolved = self.path_policy.resolve(&args.path);
        let path = resolved.normalized.display().to_string();
        let original = match tokio::fs::read_to_string(&resolved.normalized).await {
            Ok(s) => s,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                // Honour the Claude Code convention: a single edit with empty old_text on a
                // missing file means "create this file with new_text as its entire content".
                // This avoids the retry loop where models trained on Claude Code's Edit tool
                // send file_edit({old_text: "", new_text: <content>}) to create new files.
                if args.edits.len() == 1 && args.edits[0].old_text.is_empty() {
                    let content = &args.edits[0].new_text;
                    if let Some(parent) = resolved.normalized.parent() {
                        if !parent.as_os_str().is_empty() {
                            if let Err(e) = tokio::fs::create_dir_all(parent).await {
                                return json!({ "error": e.to_string() });
                            }
                        }
                    }
                    return match tokio::fs::write(&resolved.normalized, content.as_bytes()).await {
                        Ok(_) => json!({
                            "edited": true,
                            "path": path,
                            "diff": unified_diff("", content, &path),
                            "verified": true,
                            "applied_snippet": content,
                        }),
                        Err(e) => json!({ "error": e.to_string() }),
                    };
                }
                return json!({ "error": format!("File not found: {path}. Use file_write to create new files.") });
            }
            Err(e) => return json!({ "error": e.to_string() }),
        };
        let mut working = original.clone();
        for (idx, edit) in args.edits.iter().enumerate() {
            if edit.old_text.is_empty() {
                return json!({ "error": format!("Edit {}: old_text is empty. Use file_write to create new files.", idx + 1) });
            }
            let occurrences = working.matches(&edit.old_text).count();
            if occurrences == 0 {
                return json!({ "error": format!("Edit {}: old_text not found", idx + 1) });
            }
            if occurrences > 1 {
                return json!({
                    "error": format!(
                        "Edit {}: old_text appears {} times — make it unique",
                        idx + 1,
                        occurrences
                    )
                });
            }
            working = working.replacen(&edit.old_text, &edit.new_text, 1);
        }
        if let Err(e) = tokio::fs::write(&resolved.normalized, working.as_bytes()).await {
            return json!({ "error": e.to_string() });
        }
        // Re-read from disk so the model sees the actually-applied state, not an
        // assumption. `verified` is false if what landed on disk differs from
        // what we intended to write (e.g. a concurrent writer or odd encoding).
        let on_disk = tokio::fs::read_to_string(&resolved.normalized)
            .await
            .unwrap_or_else(|_| working.clone());
        let verified = on_disk == working;
        let applied_snippet = changed_line_span(&original, &on_disk)
            .map(|(start, end)| numbered_snippet(&on_disk, start, end, 3))
            .unwrap_or_default();
        json!({
            "edited": true,
            "path": path,
            "diff": unified_diff(&original, &working, &path),
            "verified": verified,
            "applied_snippet": applied_snippet,
        })
    }
}

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

    #[test]
    fn diff_identical_has_no_hunks() {
        let d = unified_diff("a\nb\nc", "a\nb\nc", "f.txt");
        assert_eq!(d, "--- f.txt\n+++ f.txt");
    }

    #[test]
    fn diff_single_replacement() {
        let d = unified_diff("a\nb\nc", "a\nB\nc", "f.txt");
        assert!(d.contains("-b"));
        assert!(d.contains("+B"));
        assert!(d.contains("@@ -2 +2 @@"));
    }

    #[test]
    fn diff_includes_added_line() {
        let d = unified_diff("a\nc", "a\nb\nc", "f.txt");
        assert!(d.contains("+b"));
        assert!(d.contains("@@ -2 +2 @@"));
    }

    #[test]
    fn diff_includes_removed_line() {
        let d = unified_diff("a\nb\nc", "a\nc", "f.txt");
        assert!(d.contains("-b"));
        assert!(d.contains("@@ -2 +2 @@"));
    }

    #[test]
    fn diff_header_uses_path() {
        let d = unified_diff("x", "y", "/abs/path/foo.rs");
        assert!(d.starts_with("--- /abs/path/foo.rs\n+++ /abs/path/foo.rs"));
    }

    #[test]
    fn changed_span_none_when_identical() {
        assert_eq!(changed_line_span("a\nb\nc", "a\nb\nc"), None);
    }

    #[test]
    fn changed_span_is_tight_around_single_edit() {
        // Only line index 2 changes in a 5-line file.
        let original = "a\nb\nc\nd\ne";
        let updated = "a\nb\nC\nd\ne";
        assert_eq!(changed_line_span(original, updated), Some((2, 3)));
    }

    #[test]
    fn numbered_snippet_uses_one_based_line_numbers_and_context() {
        let content = "a\nb\nc\nd\ne";
        // changed line index 2 (=line 3), context 1 → lines 2..=4
        let snip = numbered_snippet(content, 2, 3, 1);
        assert!(snip.contains("    2  b"));
        assert!(snip.contains("    3  c"));
        assert!(snip.contains("    4  d"));
        assert!(!snip.contains("    1  a"));
        assert!(!snip.contains("    5  e"));
    }

    #[tokio::test]
    async fn creates_new_file_when_old_text_empty_and_file_missing() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("sub/new.html");

        let result = FileEditTool {
            approve: false,
            path_policy: PathPolicy::default(),
        }
        .execute(json!({
            "path": path.to_str().unwrap(),
            "edits": [{ "old_text": "", "new_text": "<h1>hello</h1>" }]
        }))
        .await;

        assert!(result["edited"].as_bool().unwrap(), "{result}");
        assert_eq!(result["verified"].as_bool(), Some(true));
        let content = tokio::fs::read_to_string(&path).await.unwrap();
        assert_eq!(content, "<h1>hello</h1>");
    }

    #[tokio::test]
    async fn file_not_found_with_nonempty_old_text_returns_error() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("missing.txt");

        let result = FileEditTool {
            approve: false,
            path_policy: PathPolicy::default(),
        }
        .execute(json!({
            "path": path.to_str().unwrap(),
            "edits": [{ "old_text": "something", "new_text": "else" }]
        }))
        .await;

        let err = result["error"].as_str().unwrap();
        assert!(err.contains("File not found"), "{err}");
        assert!(err.contains("file_write"), "{err}");
    }

    #[tokio::test]
    async fn applies_unique_replacement() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.txt");
        tokio::fs::write(&path, "alpha\nbeta\ngamma").await.unwrap();

        let result = FileEditTool {
            approve: false,
            path_policy: PathPolicy::default(),
        }
        .execute(json!({
            "path": path.to_str().unwrap(),
            "edits": [{ "old_text": "beta", "new_text": "BETA" }]
        }))
        .await;

        assert!(result["edited"].as_bool().unwrap());
        // Re-read verification confirms the write landed and surfaces the
        // applied region back to the model.
        assert_eq!(result["verified"].as_bool(), Some(true));
        assert!(result["applied_snippet"].as_str().unwrap().contains("BETA"));
        let content = tokio::fs::read_to_string(&path).await.unwrap();
        assert_eq!(content, "alpha\nBETA\ngamma");
    }

    #[tokio::test]
    async fn rejects_non_unique_match() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.txt");
        tokio::fs::write(&path, "x\nx\nx").await.unwrap();

        let result = FileEditTool {
            approve: false,
            path_policy: PathPolicy::default(),
        }
        .execute(json!({
            "path": path.to_str().unwrap(),
            "edits": [{ "old_text": "x", "new_text": "y" }]
        }))
        .await;
        assert!(result["error"].as_str().unwrap().contains("3 times"));
    }

    #[tokio::test]
    async fn rejects_missing_match() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.txt");
        tokio::fs::write(&path, "alpha").await.unwrap();

        let result = FileEditTool {
            approve: false,
            path_policy: PathPolicy::default(),
        }
        .execute(json!({
            "path": path.to_str().unwrap(),
            "edits": [{ "old_text": "missing", "new_text": "x" }]
        }))
        .await;
        assert!(result["error"].as_str().unwrap().contains("not found"));
    }

    #[tokio::test]
    async fn applies_sequential_edits() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.txt");
        tokio::fs::write(&path, "one two three").await.unwrap();

        let result = FileEditTool {
            approve: false,
            path_policy: PathPolicy::default(),
        }
        .execute(json!({
            "path": path.to_str().unwrap(),
            "edits": [
                { "old_text": "one", "new_text": "ONE" },
                { "old_text": "three", "new_text": "THREE" }
            ]
        }))
        .await;

        assert!(result["edited"].as_bool().unwrap());
        let content = tokio::fs::read_to_string(&path).await.unwrap();
        assert_eq!(content, "ONE two THREE");
    }
}