yapi-core 0.4.1

Coding agent core: sessions, compaction, settings, resources, built-in tools, system prompt, packages, extension runner and MCP. An internal library of yapi, with no stable API.
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
//! Built-in tools on a scratch directory.
#![allow(
    clippy::unwrap_used,
    reason = "test helpers; a panic is a test failure"
)]

use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use serde_json::{Value, json};
use tokio_util::sync::CancellationToken;
use yapi_agent::UpdateSink;
use yapi_core::tools::{ToolEnv, builtin};
use yapi_types::event::ToolResult;

struct Scratch(PathBuf);

impl Scratch {
    fn new(name: &str) -> Scratch {
        let dir = std::env::temp_dir().join(format!("yapi-tools-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        Scratch(dir)
    }
}

impl Drop for Scratch {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

fn env(cwd: &Path) -> ToolEnv {
    ToolEnv {
        cwd: cwd.to_path_buf(),
        runtime: Arc::default(),
        bin_dir: cwd.join("bin"),
    }
}

fn sink() -> (UpdateSink, Arc<Mutex<Vec<ToolResult>>>) {
    let updates = Arc::new(Mutex::new(Vec::new()));
    let store = updates.clone();
    (
        Arc::new(move |update| store.lock().unwrap().push(update)),
        updates,
    )
}

async fn call(cwd: &Path, name: &str, args: Value) -> Result<ToolResult, String> {
    let tool = builtin(name, &env(cwd)).unwrap().tool;
    let (updates, _) = sink();
    tool.execute("id".into(), args, CancellationToken::new(), updates)
        .await
}

fn text(result: &ToolResult) -> String {
    yapi_types::message::blocks_text(&result.content, "\n")
}

#[tokio::test]
async fn read_pages_through_files() {
    let dir = Scratch::new("read");
    let lines: Vec<String> = (1..=5).map(|n| format!("line {n}")).collect();
    std::fs::write(dir.0.join("a.txt"), lines.join("\n")).unwrap();

    let result = call(
        &dir.0,
        "read",
        json!({"path": "a.txt", "offset": 2, "limit": 2}),
    )
    .await
    .unwrap();
    assert_eq!(
        text(&result),
        "line 2\nline 3\n\n[2 more lines in file. Use offset=4 to continue.]"
    );
    let err = call(&dir.0, "read", json!({"path": "a.txt", "offset": 9}))
        .await
        .unwrap_err();
    assert_eq!(err, "Offset 9 is beyond end of file (5 lines total)");
    let err = call(&dir.0, "read", json!({"path": "missing.txt"}))
        .await
        .unwrap_err();
    assert!(err.starts_with("ENOENT: no such file or directory, access '"));

    let long: Vec<String> = (1..=2500).map(|n| n.to_string()).collect();
    std::fs::write(dir.0.join("long.txt"), long.join("\n")).unwrap();
    let result = call(&dir.0, "read", json!({"path": "@long.txt"}))
        .await
        .unwrap();
    assert!(
        text(&result).ends_with("\n\n[Showing lines 1-2000 of 2500. Use offset=2001 to continue.]")
    );
    assert_eq!(
        result.details.unwrap()["truncation"]["truncatedBy"],
        "lines"
    );
}

#[tokio::test]
async fn read_resizes_images() {
    use image::{DynamicImage, ImageOutputFormat, RgbaImage};
    let dir = Scratch::new("read-images");
    let write = |name: &str, width: u32, format: ImageOutputFormat| {
        let image = DynamicImage::ImageRgba8(RgbaImage::new(width, 4));
        image
            .write_to(
                &mut std::fs::File::create(dir.0.join(name)).unwrap(),
                format,
            )
            .unwrap();
    };
    write("small.bmp", 3, ImageOutputFormat::Bmp);
    write("wide.png", 2100, ImageOutputFormat::Png);
    let bmp = std::fs::read(dir.0.join("small.bmp")).unwrap();
    std::fs::write(dir.0.join("broken.bmp"), &bmp[..bmp.len() - 8]).unwrap();

    let read = |path: &'static str| {
        let dir = dir.0.clone();
        async move {
            let result = call(&dir, "read", json!({ "path": path })).await.unwrap();
            let images: Vec<String> = result
                .content
                .iter()
                .filter_map(|block| match block {
                    yapi_types::message::ContentBlock::Image(image) => {
                        Some(image.mime_type.clone())
                    }
                    _ => None,
                })
                .collect();
            (text(&result), images)
        }
    };
    assert_eq!(
        read("small.bmp").await,
        (
            "Read image file [image/png]\n[Image converted from image/bmp to image/png.]".into(),
            vec!["image/png".into()]
        )
    );
    assert_eq!(
        read("wide.png").await,
        (
            "Read image file [image/png]\n[Image: original 2100x4, displayed at 2000x4. Multiply coordinates by 1.05 to map to original image.]".into(),
            vec!["image/png".into()]
        )
    );
    assert_eq!(
        read("broken.bmp").await,
        (
            "Read image file [image/bmp]\n[Image omitted: could not be converted to a supported inline image format.]".into(),
            vec![]
        )
    );
}

#[tokio::test]
async fn bom_and_crlf_preserved() {
    let dir = Scratch::new("edit");
    let result = call(
        &dir.0,
        "write",
        json!({"path": "sub/f.txt", "content": "\u{feff}one\r\ntwo\r\n"}),
    )
    .await
    .unwrap();
    assert_eq!(text(&result), "Successfully wrote to sub/f.txt");

    let result = call(
        &dir.0,
        "edit",
        json!({"path": "sub/f.txt", "edits": [{"oldText": "two\n", "newText": "2\n"}]}),
    )
    .await
    .unwrap();
    assert_eq!(
        text(&result),
        "Successfully replaced 1 block(s) in sub/f.txt."
    );
    assert_eq!(
        std::fs::read_to_string(dir.0.join("sub/f.txt")).unwrap(),
        "\u{feff}one\r\n2\r\n"
    );
    let details = result.details.unwrap();
    assert_eq!(details["diff"], " 1 one\n-2 two\n+2 2");
    assert_eq!(details["firstChangedLine"], 2);

    let err = call(
        &dir.0,
        "edit",
        json!({"path": "nope.txt", "edits": [{"oldText": "a", "newText": "b"}]}),
    )
    .await
    .unwrap_err();
    assert_eq!(err, "Could not edit file: nope.txt. Error code: ENOENT.");

    // Node's messages for a directory: `read` names no path, `open` does.
    std::fs::create_dir(dir.0.join("adir")).unwrap();
    let err = call(&dir.0, "write", json!({"path": "adir", "content": "x"}))
        .await
        .unwrap_err();
    assert_eq!(
        err,
        format!(
            "EISDIR: illegal operation on a directory, open '{}'",
            dir.0.join("adir").display()
        )
    );

    // A `tool_call` handler can drop a validated argument, and the file is left alone.
    for (name, args, field) in [
        ("write", json!({"path": "sub/f.txt"}), "content"),
        ("write", json!({"content": "x"}), "path"),
        (
            "edit",
            json!({"path": "sub/f.txt", "edits": [{"oldText": "one"}]}),
            "newText",
        ),
    ] {
        let err = call(&dir.0, name, args).await.unwrap_err();
        assert_eq!(
            err,
            format!("The \"{field}\" argument must be of type string.")
        );
    }
    assert_eq!(
        std::fs::read_to_string(dir.0.join("sub/f.txt")).unwrap(),
        "\u{feff}one\r\n2\r\n"
    );
}

#[tokio::test]
async fn edit_accepts_legacy_arguments() {
    let dir = env(Path::new("/"));
    let tool = builtin("edit", &dir).unwrap().tool;
    let args = json!({"path": "f", "oldText": "a", "newText": "b"});
    let prepared = tool.prepare_arguments(args.as_object().unwrap().clone());
    assert_eq!(
        Value::Object(prepared),
        json!({"path": "f", "edits": [{"oldText": "a", "newText": "b"}]})
    );
}

#[tokio::test]
async fn bash_output_exit_codes() {
    let dir = Scratch::new("bash");
    let result = call(&dir.0, "bash", json!({"command": "echo hi; echo err >&2"}))
        .await
        .unwrap();
    // stdout and stderr are separate pipes, so their lines may arrive in either order.
    let mut lines: Vec<String> = text(&result).lines().map(str::to_owned).collect();
    lines.sort();
    assert_eq!(lines, ["err", "hi"]);
    assert_eq!(result.structured_content.as_ref().unwrap()["exit_code"], 0);

    let result = call(&dir.0, "bash", json!({"command": "exit 3"}))
        .await
        .unwrap();
    assert_eq!(text(&result), "(no output)\n\nCommand exited with code 3");
    assert_eq!(result.is_error, Some(true));

    let err = call(
        &dir.0,
        "bash",
        json!({"command": "echo start; sleep 5", "timeout": 0.2}),
    )
    .await
    .unwrap_err();
    assert_eq!(err, "start\n\n\nCommand timed out after 0.2 seconds");
}

#[cfg(unix)]
#[tokio::test]
async fn bash_shell_settings() {
    let dir = Scratch::new("bash-shell");
    let runtime = yapi_core::tools::Runtime {
        shell_path: Some("/bin/sh".into()),
        shell_command_prefix: Some("FOO=bar".into()),
        ..Default::default()
    };
    let env = ToolEnv {
        runtime: Arc::new(std::sync::RwLock::new(runtime)),
        ..env(&dir.0)
    };
    let tool = builtin("bash", &env).unwrap().tool;
    let (updates, _) = sink();
    let result = tool
        .execute(
            "id".into(),
            json!({"command": "echo $FOO; echo $0"}),
            CancellationToken::new(),
            updates,
        )
        .await
        .unwrap();
    assert_eq!(text(&result), "bar\n/bin/sh\n");
    // `~` in `shellPath` names the home directory.
    let home = yapi_core::tools::path::home_dir();
    let (shell, _) = yapi_core::tools::bash::shell_with(Some("~")).unwrap();
    assert_eq!(Path::new(&shell), home);
}

#[tokio::test]
async fn bash_abort_and_updates() {
    let dir = Scratch::new("abort");
    let tool = builtin("bash", &env(&dir.0)).unwrap().tool;
    let (updates, seen) = sink();
    let cancel = CancellationToken::new();
    let trigger = cancel.clone();
    tokio::spawn(async move {
        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
        trigger.cancel();
    });
    let err = tool
        .execute(
            "id".into(),
            json!({"command": "echo partial; sleep 30 & echo $! > pid; wait"}),
            cancel,
            updates,
        )
        .await
        .unwrap_err();
    assert_eq!(err, "partial\n\n\nCommand aborted");
    {
        let seen = seen.lock().unwrap();
        assert!(seen.len() >= 2, "expected an initial and an output update");
        assert_eq!(text(&seen[1]), "partial\n");
    }
    // The abort kills the shell's whole process group, background jobs included.
    #[cfg(unix)]
    {
        let pid = std::fs::read_to_string(dir.0.join("pid")).unwrap();
        let alive = || {
            std::process::Command::new("kill")
                .args(["-0", pid.trim()])
                .stderr(std::process::Stdio::null())
                .status()
                .unwrap()
                .success()
        };
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        while alive() {
            assert!(
                std::time::Instant::now() < deadline,
                "background job outlived the abort"
            );
            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        }
    }
}

#[tokio::test]
async fn read_huge_offset_limit() {
    let dir = Scratch::new("read-huge");
    std::fs::write(dir.0.join("a.txt"), "1\n2\n3").unwrap();
    let result = call(
        &dir.0,
        "read",
        json!({"path": "a.txt", "offset": 2, "limit": 1e20}),
    )
    .await
    .unwrap();
    assert_eq!(text(&result), "2\n3");
    let err = call(&dir.0, "read", json!({"path": "a.txt", "offset": 1e20}))
        .await
        .unwrap_err();
    assert_eq!(
        err,
        "Offset 100000000000000000000 is beyond end of file (3 lines total)"
    );
}

#[tokio::test]
async fn grep_huge_context() {
    let dir = Scratch::new("grep-context");
    std::fs::write(dir.0.join("a.txt"), "one\ntwo\nthree").unwrap();
    let result = call(&dir.0, "grep", json!({"pattern": "two", "context": 1e20}))
        .await
        .unwrap();
    assert_eq!(text(&result), "a.txt-1- one\na.txt:2: two\na.txt-3- three");
}

#[tokio::test]
async fn edit_refuses_non_utf8() {
    let dir = Scratch::new("edit-latin1");
    let original = b"caf\xe9\nx = 1\n";
    std::fs::write(dir.0.join("f.txt"), original).unwrap();
    let err = call(
        &dir.0,
        "edit",
        json!({"path": "f.txt", "edits": [{"oldText": "x = 1", "newText": "x = 2"}]}),
    )
    .await
    .unwrap_err();
    assert_eq!(err, "Could not edit file: f.txt. File is not valid UTF-8.");
    assert_eq!(std::fs::read(dir.0.join("f.txt")).unwrap(), original);
}

#[tokio::test]
async fn edit_keeps_line_endings() {
    let dir = Scratch::new("edit-endings");
    let file = dir.0.join("f.txt");
    for (before, old, new, after) in [
        ("a\nb\r\nc\r\n", "a", "A", "A\nb\r\nc\r\n"),
        ("s = \"x\ry\"\nz\n", "z", "Z", "s = \"x\ry\"\nZ\n"),
        // A fuzzy match: curly quotes and trailing spaces in the file.
        (
            "\u{feff}say \u{201C}hi\u{201D}  \r\nkeep \r\n",
            "say \"hi\"",
            "say \"bye\"",
            "\u{feff}say \"bye\"\r\nkeep \r\n",
        ),
    ] {
        std::fs::write(&file, before).unwrap();
        call(
            &dir.0,
            "edit",
            json!({"path": "f.txt", "edits": [{"oldText": old, "newText": new}]}),
        )
        .await
        .unwrap();
        assert_eq!(std::fs::read_to_string(&file).unwrap(), after, "{before:?}");
    }
}

#[tokio::test(flavor = "multi_thread")]
async fn parallel_edits() {
    let dir = Scratch::new("edit-parallel");
    let file = dir.0.join("f.txt");
    let edit = |old: &str, new: &str| {
        call(
            &dir.0,
            "edit",
            json!({"path": "f.txt", "edits": [{"oldText": old, "newText": new}]}),
        )
    };
    for round in 0..20 {
        std::fs::write(&file, "top\nbottom\n").unwrap();
        let (top, bottom) = tokio::join!(edit("top", "TOP"), edit("bottom", "BOTTOM"));
        top.unwrap();
        bottom.unwrap();
        let content = std::fs::read_to_string(&file).unwrap();
        assert_eq!(content, "TOP\nBOTTOM\n", "round {round}");
    }
}

#[tokio::test]
async fn bash_long_output() {
    let dir = Scratch::new("bash-long");
    let result = call(&dir.0, "bash", json!({"command": "seq 1 300000"}))
        .await
        .unwrap();
    let path = result.details.as_ref().unwrap()["fullOutputPath"]
        .as_str()
        .unwrap()
        .to_owned();
    assert!(text(&result).ends_with(&format!(
        "\n[Showing lines 298001-300000 of 300000. Full output: {path}]"
    )));
    let structured = result.structured_content.as_ref().unwrap();
    assert_eq!(structured["truncated"], true);
    assert_eq!(structured["full_output_path"], path);
    let full = structured["output"].as_str().unwrap();
    // `seq 1 300000` prints 1,988,895 bytes, of which the first and last 512 KiB stay.
    let omitted = 1_988_895 - 1024 * 1024;
    assert!(full.starts_with("1\n2\n3\n"));
    assert!(full.contains(&format!("\n\n[... {omitted} bytes omitted ...]\n\n")));
    assert!(full.ends_with("\n299999\n300000\n"));
    std::fs::remove_file(path).unwrap();
}

#[tokio::test]
async fn bash_timeout_while_flooding() {
    let dir = Scratch::new("bash-flood");
    let run = call(&dir.0, "bash", json!({"command": "yes", "timeout": 0.5}));
    let err = tokio::time::timeout(std::time::Duration::from_secs(3), run)
        .await
        .expect("the timeout ends a flooding command")
        .unwrap_err();
    assert!(err.ends_with("\n\nCommand timed out after 0.5 seconds"));
    let log = err.split("Full output: ").nth(1).unwrap();
    std::fs::remove_file(log.split(']').next().unwrap()).unwrap();
}