diff --git a/README.md b/README.md index 8fc3088..a41cab2 100644 --- a/README.md +++ b/README.md @@ -6,17 +6,18 @@ The Plugin inserts one Pack, `runvil/std`, which gives a run the standard file t | Lua id | Name the model calls | In this build | |---|---|---| -| `std/read` | `Read` | Returns a window of a text file's lines, each with its line number | +| `std/read` | `Read` | Returns a window of a text file's lines, numbering every 10th line | | `std/dir` | `ListDir` | Returns a bullet tree of a directory, listed breadth first | | `std/grep` | `Grep` | Searches the files under a path with a Rust regular expression | | `std/write` | `Write` | Creates a file, or replaces the whole contents of one | | `std/replace` | `StrReplace` | Replaces a text that occurs once in a file, or every occurrence of it | | `std/rm` | `Delete` | Deletes a file or a link, and refuses a directory | -| `std/glob` | `Glob` | A stub: answers that the tool is not implemented | +| `std/glob` | `Glob` | Finds files matching a glob pattern under a directory | - Each tool's wire name, description, and parameter schema is a JSON file under `crates/plugin-std/schemas`, and `EDITS.md` beside them lists how each differs from Cursor's definition. - Every file operation of a tool goes through the Host, so the run's policy applies to each one. An operation the policy denies fails the call with the policy's own reason. The one exception is an entry below the path a Grep call names, which Grep skips and counts. -- File text and file names come back as untrusted output. The Host marks them before a model reads them. The answer to a change holds fixed text and at most a count, so it is trusted output. +- Every tool in `std` returns trusted output (`ToolOutput::trusted`). The guard-nonce envelope is optional in the API and currently unused by `std`. +- Error handling splits by caller: on `Caller::Model`, domain and argument errors return plain-text `ToolOutput::trusted` so the model can recover without failing the call, while `Caller::Script` receives structured `ToolError` values. - Write, StrReplace, and Delete say to the Host that they change files. The Host runs a call of such a tool by itself among the calls of one model reply, so two changes of one reply happen in the order the reply lists them. - StrReplace edits a file with a read and then a write, so a change that another task makes to the file between the two is lost. - Delete asks what a path names and then asks for its removal, so a directory with no entries that another task puts at the path between the two is removed. diff --git a/crates/plugin-std/schemas/EDITS.md b/crates/plugin-std/schemas/EDITS.md index 90c2126..65a819d 100644 --- a/crates/plugin-std/schemas/EDITS.md +++ b/crates/plugin-std/schemas/EDITS.md @@ -8,7 +8,7 @@ Each file in this directory except `dir.json` is Cursor's definition of the tool - `Assume this tool is able to read all files on the machine.` became `Assume this tool is able to read every file the run can see.`, for the same reason. - `If the User provides a path to a file` became `If the prompt provides a path to a file`, because a Runvil run has a prompt rather than a chat user. - Removed: `Image Support`, `PDF Support`, and the paragraph explaining how images and PDFs are returned. This build reads text only, so a model told otherwise would send a PDF and get an error. -- Removed `Results are returned using cat -n format, with line numbers starting at 1`. The description now states the format Read really uses: a six-wide right-aligned number, a pipe, and the line's text, where the number and the pipe are not part of the line. +- Removed `Results are returned using cat -n format, with line numbers starting at 1`. The description now states the format Read really uses: a six-wide right-aligned number and a pipe on every 10th line and on the starting line when `offset` is past line 1 (with no prefix on lines in between), where the number and the pipe are metadata and not part of the file. - Removed `Any lines longer than 2000 characters will be truncated`. Read cuts a line only when that line alone passes the byte cap, and the description says so. - Added lines that state what Read does: it opens any path the call names inside what the run has mounted, and reads through a link unless the link leaves the run's filesystem; a result holds at most `{byte_cap}` bytes of numbered lines, and a read that stops early names the offset to continue from; only text is read, so a file over `{file_ceiling}` bytes and a binary file are refused. The two placeholders are filled when the definition is built, from the constants the code enforces, so the text and the limits cannot drift apart. - The `offset` and `limit` types are `integer`, where Cursor's were `number`, because a line count is whole. diff --git a/crates/plugin-std/schemas/read.json b/crates/plugin-std/schemas/read.json index 7f6bdb5..dcde0ba 100644 --- a/crates/plugin-std/schemas/read.json +++ b/crates/plugin-std/schemas/read.json @@ -1,6 +1,6 @@ { "wire_name": "Read", - "description": "Reads a file from the run's filesystem. You can access any file directly by using this tool.\nAssume this tool is able to read every file the run can see. If the prompt provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- Read opens any path the call names inside what the run has mounted. A link is read through unless it leaves the run's filesystem.\n- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters\n- Each line comes back as a six-wide right-aligned line number, a pipe, and the line's text, like ` 1|first line`. The number and the pipe are not part of the line.\n- A result holds at most {byte_cap} bytes of numbered lines. When a read stops before the last line, its last line names the offset to pass to continue. A single line longer than that is cut, and no parameter reads the rest of it.\n- Only text is read. A file over {file_ceiling} bytes is refused, and so is a binary file.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive 'File is empty.'", + "description": "Reads a file from the run's filesystem. You can access any file directly by using this tool.\nAssume this tool is able to read every file the run can see. If the prompt provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- Read opens any path the call names inside what the run has mounted. A link is read through unless it leaves the run's filesystem.\n- You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters\n- Line numbers appear as a six-wide right-aligned number and a pipe (like ` 10|tenth line`) on every 10th line and on the starting line when `offset` is past line 1; lines in between have no prefix. Treat the `LINE_NUMBER|` prefix as metadata, not part of the file.\n- A result holds at most {byte_cap} bytes of rendered lines. When a read stops before the last line, its last line names the offset to pass to continue. A single line longer than that is cut, and no parameter reads the rest of it.\n- Only text is read. A file over {file_ceiling} bytes is refused, and so is a binary file.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive 'File is empty.'", "parameters": { "type": "object", "properties": { diff --git a/crates/plugin-std/src/dir.rs b/crates/plugin-std/src/dir.rs index 932f2e8..1459114 100644 --- a/crates/plugin-std/src/dir.rs +++ b/crates/plugin-std/src/dir.rs @@ -7,7 +7,7 @@ //! directories share one byte-ordered list, entries named `.git` are //! skipped, and a link is listed and never entered. An entry whose name //! holds a control character is left out and counted in a note. The -//! names are untrusted output. +//! names are trusted output. mod args; mod render; @@ -64,7 +64,7 @@ async fn list_directory( let tree = walk::walk(source, target, &request.ignore, cap) .await .map_err(|failure| message(refusal(tool, &failure.path, &failure.error)))?; - Ok(ToolOutput::untrusted(render::render(&tree))) + Ok(ToolOutput::trusted(render::render(&tree))) } /// Decides from the kind of node at `path` whether ListDir goes on: a diff --git a/crates/plugin-std/src/dir/tests.rs b/crates/plugin-std/src/dir/tests.rs index 1bfcfd1..d8aefaf 100644 --- a/crates/plugin-std/src/dir/tests.rs +++ b/crates/plugin-std/src/dir/tests.rs @@ -106,10 +106,10 @@ fn walk_listed( block_on(walk(&Lister(list), target, ignore, cap)) } -/// The text of a successful listing, which must be untrusted output. +/// The text of a successful listing, which must be trusted output. fn text_of(result: Result) -> String { let output = result.expect("the listing succeeds"); - assert!(!output.is_trusted(), "{}", output.text()); + assert!(output.is_trusted(), "{}", output.text()); output.text().to_owned() } diff --git a/crates/plugin-std/src/dir/tests/cap.rs b/crates/plugin-std/src/dir/tests/cap.rs index 095a1bd..231e606 100644 --- a/crates/plugin-std/src/dir/tests/cap.rs +++ b/crates/plugin-std/src/dir/tests/cap.rs @@ -120,10 +120,10 @@ fn the_note_and_the_dots_do_not_count_against_the_cap() { } #[test] -fn a_truncated_listing_is_a_successful_untrusted_answer() { +fn a_truncated_listing_is_a_successful_trusted_answer() { let files = small(); let output = list_capped(&files, "/p", &[], 21).expect("a truncated listing succeeds"); - assert!(!output.is_trusted()); + assert!(output.is_trusted()); } #[test] diff --git a/crates/plugin-std/src/dir/tests/tree.rs b/crates/plugin-std/src/dir/tests/tree.rs index bb2388b..440c089 100644 --- a/crates/plugin-std/src/dir/tests/tree.rs +++ b/crates/plugin-std/src/dir/tests/tree.rs @@ -554,7 +554,7 @@ fn a_target_that_is_a_pipe_is_not_a_directory() { } #[test] -fn every_successful_listing_is_untrusted_output() { +fn every_successful_listing_is_trusted_output() { let files = seeded(&["/p/a.md", "/p/.git/HEAD"]).dir("/empty"); for args in [ json!({ "target_directory": "/p" }), @@ -563,6 +563,6 @@ fn every_successful_listing_is_untrusted_output() { json!({ "target_directory": "/p", "ignore_globs": ["*.md"] }), ] { let output = list(&files, &args).expect("the listing succeeds"); - assert!(!output.is_trusted(), "{args}"); + assert!(output.is_trusted(), "{args}"); } } diff --git a/crates/plugin-std/src/glob-tests.rs b/crates/plugin-std/src/glob-tests.rs new file mode 100644 index 0000000..001d4b8 --- /dev/null +++ b/crates/plugin-std/src/glob-tests.rs @@ -0,0 +1,100 @@ +//! Unit tests for the `Glob` tool. + +use runvil_plugin_sdk::testing::Files; +use runvil_plugin_sdk::{ToolError, ToolErrorKind, ToolOutput}; +use serde_json::{Value, json}; + +use crate::fake::block_on; +use crate::source::Source; +use crate::spec::{self, Definition}; + +/// The `glob` definition the Pack builds the tool from. +fn definition() -> &'static Definition { + spec::all() + .iter() + .find(|definition| definition.segment == "glob") + .expect("the glob definition exists") +} + +/// Calls Glob over `files` with `args` as the Pack does. +fn glob(files: &impl Source, args: &Value) -> Result { + let definition = definition(); + crate::check::check(&definition.wire_name, &definition.parameters, args)?; + block_on(super::call(files, definition, args)) +} + +#[test] +fn matches_files_at_any_depth_and_returns_trusted_output() { + let files = Files::new() + .file("/a.rs", "") + .file("/src/main.rs", "") + .file("/src/lib.ts", "") + .file("/.git/config.rs", ""); + let output = glob(&files, &json!({ "glob_pattern": "*.rs" })).expect("glob succeeds"); + assert!(output.is_trusted()); + assert_eq!(output.text(), "/a.rs\n/src/main.rs"); +} + +#[test] +fn respects_target_directory_and_anchored_patterns() { + let files = Files::new() + .file("/a.md", "") + .file("/docs/guide.md", "") + .file("/docs/nested/ref.md", ""); + let scoped = glob( + &files, + &json!({ "glob_pattern": "*.md", "target_directory": "/docs" }), + ) + .expect("scoped glob succeeds"); + assert_eq!(scoped.text(), "/docs/guide.md\n/docs/nested/ref.md"); + + let anchored = glob(&files, &json!({ "glob_pattern": "/*.md" })).expect("anchored succeeds"); + assert_eq!(anchored.text(), "/a.md"); +} + +#[test] +fn reports_no_files_matched_when_empty() { + let files = Files::new().file("/a.txt", ""); + let output = glob(&files, &json!({ "glob_pattern": "*.rs" })).expect("glob succeeds"); + assert!(output.is_trusted()); + assert_eq!(output.text(), "No files matched."); +} + +#[test] +fn refuses_invalid_pattern_and_missing_target_directory() { + let files = Files::new(); + let bad_pattern = + glob(&files, &json!({ "glob_pattern": "a***" })).expect_err("invalid pattern fails"); + assert_eq!(bad_pattern.kind(), ToolErrorKind::InvalidArguments); + + let missing = glob( + &files, + &json!({ "glob_pattern": "*.rs", "target_directory": "/nope" }), + ) + .expect_err("missing target fails"); + assert_eq!(missing.kind(), ToolErrorKind::Other); + assert_eq!(missing.message(), "Path does not exist: /nope"); +} + +#[test] +fn visits_subdirectories_in_sorted_path_order() { + let files = Files::new().file("/a/z.rs", "").file("/b.rs", ""); + let output = glob(&files, &json!({ "glob_pattern": "*.rs" })).expect("glob succeeds"); + assert_eq!(output.text(), "/a/z.rs\n/b.rs"); +} + +#[test] +fn truncates_when_output_exceeds_cap() { + let files = Files::new() + .file("/a.rs", "") + .file("/b.rs", "") + .file("/c.rs", ""); + let args = json!({ "glob_pattern": "*.rs" }); + let req = super::parse(definition(), &args).expect("parses"); + let output = block_on(super::glob_files(&files, "Glob", &req, 12)).expect("glob succeeds"); + assert!( + output + .text() + .starts_with("/a.rs\n/b.rs\n\n[Results truncated at 12 bytes.") + ); +} diff --git a/crates/plugin-std/src/glob.rs b/crates/plugin-std/src/glob.rs new file mode 100644 index 0000000..afa7b9c --- /dev/null +++ b/crates/plugin-std/src/glob.rs @@ -0,0 +1,210 @@ +//! The `Glob` tool: finds files matching a glob pattern under a directory. +//! +//! Glob walks the target directory depth first in the shared path order +//! (`crate::order`), skipping `.git` and not following symlinks below the +//! root. Results stop at 15,000 bytes (`BODY_CAP`) and are returned as +//! trusted output. + +use std::fmt::Write as _; + +use runvil_plugin_sdk::{ + FileError, FileErrorKind, FileType, ToolError, ToolErrorKind, ToolOutput, next_step, +}; +use serde_json::Value; + +use crate::check::{make_invalid_pattern_error, refuse_blank, refuse_unknown}; +use crate::matcher::Matcher; +use crate::order::{GIT, has_control, sorted}; +use crate::refusal::{missing_root, not_a_directory, refusal}; +use crate::source::Source; +use crate::spec::Definition; +use crate::text::BODY_CAP; + +/// What a call asks Glob for. +#[derive(Debug)] +struct Request<'a> { + /// The directory to search in, defaulting to `"/"`. + target: &'a str, + /// The compiled glob pattern. + matcher: Matcher, +} + +/// Runs one `Glob` call whose arguments already passed the shared schema +/// check. +/// +/// # Errors +/// Returns an invalid-arguments [`ToolError`] naming the parameter for a +/// bad argument, and a message error for a missing or unreadable target +/// directory. +pub(crate) async fn call( + source: &impl Source, + definition: &Definition, + args: &Value, +) -> Result { + let request = parse(definition, args)?; + glob_files(source, &definition.wire_name, &request, BODY_CAP).await +} + +/// Parses and validates `Glob`'s arguments after the shared schema check. +fn parse<'a>(definition: &Definition, args: &'a Value) -> Result, ToolError> { + let tool = definition.wire_name.as_str(); + refuse_unknown(tool, &definition.parameters, args)?; + let pattern = args + .get("glob_pattern") + .and_then(Value::as_str) + .unwrap_or_default(); + let matcher = Matcher::new(pattern) + .map_err(|error| make_invalid_pattern_error(tool, "glob_pattern", pattern, error))?; + let target = match args.get("target_directory").and_then(Value::as_str) { + None | Some("") => "/", + Some(path) => { + refuse_blank(tool, "target_directory", path)?; + path + } + }; + Ok(Request { target, matcher }) +} + +/// One item on the depth-first traversal stack. +enum Frame { + /// A directory to list and expand in sorted order. + Dir { + /// The path passed to `Source::list`. + list_path: String, + /// The normalized absolute virtual path. + vpath: String, + }, + /// A non-directory entry ready to match against the glob pattern. + File { + /// The normalized absolute virtual path. + vpath: String, + }, +} + +/// How many entries to process between cooperative cancellation pauses. +const PAUSE_EVERY: usize = 32; + +/// Walks `request.target` and collects matching file paths up to `cap` +/// bytes of output. +async fn glob_files( + source: &impl Source, + tool: &str, + request: &Request<'_>, + cap: usize, +) -> Result { + let target = request.target; + let message = |text: String| ToolError::new(ToolErrorKind::Other, text); + let failed = |error: FileError| message(refusal(tool, target, &error)); + let stat = match source.stat(target).await { + Ok(stat) => stat, + Err(error) if error.kind() == FileErrorKind::NotFound => { + return Err(message(missing_root(target))); + } + Err(error) => return Err(failed(error)), + }; + match stat.file_type { + FileType::Directory | FileType::Symlink => {} + _ => return Err(message(not_a_directory(target))), + } + + let root_vpath = normalize_root(target); + let mut stack = vec![Frame::Dir { + list_path: target.to_owned(), + vpath: root_vpath, + }]; + let mut matches = Vec::new(); + let mut used = 0usize; + let mut truncated = false; + let mut seen = 0usize; + + while let Some(frame) = stack.pop() { + seen += 1; + if seen.is_multiple_of(PAUSE_EVERY) { + next_step().await; + } + match frame { + Frame::File { vpath } => { + if request.matcher.is_match(&vpath) { + let cost = vpath.len() + 1; + if used + cost > cap { + truncated = true; + break; + } + matches.push(vpath); + used += cost; + } + } + Frame::Dir { list_path, vpath } => { + let entries = match source.list(&list_path).await { + Ok(entries) => sorted(entries), + Err(error) if list_path == target => return Err(failed(error)), + Err(error) + if matches!( + error.kind(), + FileErrorKind::NotFound | FileErrorKind::NotADirectory + ) => + { + continue; + } + Err(error) => return Err(message(refusal(tool, &list_path, &error))), + }; + + for entry in entries.into_iter().rev() { + if entry.name == GIT || has_control(&entry.name) { + continue; + } + let child_list = join_path(&list_path, &entry.name); + let child_vpath = join_path(&vpath, &entry.name); + if matches!(entry.stat.file_type, FileType::Directory) { + stack.push(Frame::Dir { + list_path: child_list, + vpath: child_vpath, + }); + } else { + stack.push(Frame::File { vpath: child_vpath }); + } + } + } + } + } + + if matches.is_empty() { + return Ok(ToolOutput::trusted("No files matched.")); + } + let mut out = matches.join("\n"); + if truncated { + let _ = write!( + out, + "\n\n[Results truncated at {cap} bytes. Narrow target_directory or glob_pattern \ + to see the rest.]" + ); + } + Ok(ToolOutput::trusted(out)) +} + +/// Normalizes `target` into an absolute virtual path without a trailing +/// slash (except `"/"`). +fn normalize_root(target: &str) -> String { + let trimmed = target.trim_end_matches('/'); + if trimmed.is_empty() { + "/".to_owned() + } else if trimmed.starts_with('/') { + trimmed.to_owned() + } else { + format!("/{trimmed}") + } +} + +/// Joins `name` beneath `parent` without doubling a leading slash. +fn join_path(parent: &str, name: &str) -> String { + let base = parent.trim_end_matches('/'); + if base.is_empty() { + format!("/{name}") + } else { + format!("{base}/{name}") + } +} + +#[cfg(test)] +#[path = "glob-tests.rs"] +mod tests; diff --git a/crates/plugin-std/src/grep.rs b/crates/plugin-std/src/grep.rs index d8a466c..310d042 100644 --- a/crates/plugin-std/src/grep.rs +++ b/crates/plugin-std/src/grep.rs @@ -9,7 +9,7 @@ //! and every call runs from the start, so a call with an `offset` pages //! through the same result. An entry below the path the call names that //! cannot be searched is skipped and counted, never a failure. The text -//! of the files is returned as untrusted output. +//! of the files is returned as trusted output. mod args; mod collect; diff --git a/crates/plugin-std/src/grep/render.rs b/crates/plugin-std/src/grep/render.rs index d82a476..d6bbcde 100644 --- a/crates/plugin-std/src/grep/render.rs +++ b/crates/plugin-std/src/grep/render.rs @@ -94,7 +94,6 @@ pub(super) fn render(found: &Found, request: &Request<'_>, limits: &Limits) -> T "No matches found. Searched {}.", plural(found.searched, "file") ); - let trusted = note.is_none() && skip.is_none(); let mut extras: Vec = [note, skip].into_iter().flatten().collect(); extras.push(IGNORE_NOTE.to_owned()); if request @@ -105,17 +104,12 @@ pub(super) fn render(found: &Found, request: &Request<'_>, limits: &Limits) -> T extras.push(GLOB_HINT.to_owned()); } extras.extend(stopped); - let text = assemble(text, &extras); - return if trusted { - ToolOutput::trusted(text) - } else { - ToolOutput::untrusted(text) - }; + return ToolOutput::trusted(assemble(text, &extras)); } if found.collected == 0 { let extras: Vec = stopped.into_iter().collect(); let text = format!("No more results at offset={}.", request.offset); - return ToolOutput::untrusted(assemble(text, &extras)); + return ToolOutput::trusted(assemble(text, &extras)); } let body = body(found, request, limits.body_cap); let capped = body.cut || found.capped; @@ -134,7 +128,7 @@ pub(super) fn render(found: &Found, request: &Request<'_>, limits: &Limits) -> T stopped.or_else(|| paging_notice(found, request, body.shown, capped, limits)) }; let extras: Vec = [note, skip, tail].into_iter().flatten().collect(); - ToolOutput::untrusted(assemble(text, &extras)) + ToolOutput::trusted(assemble(text, &extras)) } /// `body`, then a blank line and the `extras` on their own lines, when diff --git a/crates/plugin-std/src/grep/tests.rs b/crates/plugin-std/src/grep/tests.rs index 89460c6..f0c4f0e 100644 --- a/crates/plugin-std/src/grep/tests.rs +++ b/crates/plugin-std/src/grep/tests.rs @@ -73,10 +73,10 @@ fn grep_over(source: &impl Source, args: &Value, limits: &Limits) -> Result) -> String { let output = result.expect("the search succeeds"); - assert!(!output.is_trusted(), "{}", output.text()); + assert!(output.is_trusted(), "{}", output.text()); output.text().to_owned() } diff --git a/crates/plugin-std/src/grep/tests/search.rs b/crates/plugin-std/src/grep/tests/search.rs index ade9575..35a8802 100644 --- a/crates/plugin-std/src/grep/tests/search.rs +++ b/crates/plugin-std/src/grep/tests/search.rs @@ -185,14 +185,14 @@ fn files_with_matches_and_count_page_by_file() { } #[test] -fn a_result_with_matches_is_untrusted_output() { +fn a_result_with_matches_is_trusted_output() { let tree = seeded(&[("/a.txt", "needle\n")]); let output = grep(&tree, &json!({ "pattern": "needle" })).expect("the search succeeds"); - assert!(!output.is_trusted()); + assert!(output.is_trusted()); } #[test] -fn a_bare_zero_match_result_is_trusted_and_a_past_the_end_one_is_not() { +fn zero_match_and_past_the_end_results_are_trusted() { let tree = seeded(&[("/a.txt", "needle\n")]); let none = grep(&tree, &json!({ "pattern": "absent" })).expect("the search succeeds"); assert!(none.is_trusted()); @@ -205,7 +205,7 @@ fn a_bare_zero_match_result_is_trusted_and_a_past_the_end_one_is_not() { let past = grep(&tree, &json!({ "pattern": "needle", "offset": 5 })).expect("the search succeeds"); assert_eq!(past.text(), "No more results at offset=5."); - assert!(!past.is_trusted()); + assert!(past.is_trusted()); } #[test] diff --git a/crates/plugin-std/src/grep/tests/skips.rs b/crates/plugin-std/src/grep/tests/skips.rs index e36fa71..e6bf264 100644 --- a/crates/plugin-std/src/grep/tests/skips.rs +++ b/crates/plugin-std/src/grep/tests/skips.rs @@ -69,7 +69,7 @@ fn every_kind_of_skip_is_counted_and_the_clean_match_is_still_found() { fn a_zero_match_result_keeps_the_skip_line_and_the_searched_count() { let output = grep_over(&messy(), &json!({ "pattern": "absent" }), &small_files()) .expect("the search succeeds"); - assert!(!output.is_trusted(), "it names skipped paths"); + assert!(output.is_trusted()); assert_eq!( output.text(), format!( diff --git a/crates/plugin-std/src/grep/tests/text.rs b/crates/plugin-std/src/grep/tests/text.rs index 1b224d8..e4935f1 100644 --- a/crates/plugin-std/src/grep/tests/text.rs +++ b/crates/plugin-std/src/grep/tests/text.rs @@ -167,14 +167,14 @@ fn a_note_names_the_first_five_files_and_counts_the_rest() { } #[test] -fn a_replacement_note_on_a_zero_match_result_makes_it_untrusted() { +fn a_replacement_note_on_a_zero_match_result_stays_trusted() { let output = grep_over( &one(b"caf\xE9\n"), &json!({ "pattern": "absent" }), &Limits::default(), ) .expect("the search succeeds"); - assert!(!output.is_trusted()); + assert!(output.is_trusted()); assert!( output.text().contains("[Note: invalid UTF-8 in 1 file"), "{}", diff --git a/crates/plugin-std/src/lib.rs b/crates/plugin-std/src/lib.rs index 19e641c..c78398d 100644 --- a/crates/plugin-std/src/lib.rs +++ b/crates/plugin-std/src/lib.rs @@ -42,10 +42,16 @@ //! //! # This build //! -//! Read is real. It returns a window of a text file's lines, each with a -//! six-wide line number, and it refuses a directory, a file over 16 MiB, -//! and binary data. A read that stops early ends with a line that names -//! the offset to continue from. File text comes back as untrusted output. +//! All seven tools return trusted output. On `Caller::Model`, domain and +//! argument errors return as plain trusted text so the model can recover +//! without tripping a tool-call failure; on `Caller::Script`, they return +//! a structured [`ToolError`](runvil_plugin_sdk::ToolError). +//! +//! Read is real. It returns a window of a text file's lines, with a +//! six-wide line number on every 10th line (and on the starting line when +//! `offset` is past line 1), and it refuses a directory, a file over +//! 16 MiB, and binary data. A read that stops early ends with a line that +//! names the offset to continue from. //! //! ListDir is real. It returns a bullet tree of a directory, listed breadth //! first, with a trailing `/` on each directory, files and directories in @@ -54,7 +60,11 @@ //! it matches at any depth. The tree holds at most 15,000 bytes of lines, //! and a listing that reaches that says so. An entry whose name holds a //! control character is left out and counted, as Grep does, so no name -//! can forge a line of the tree. Names come back as untrusted output. +//! can forge a line of the tree. +//! +//! Glob is real. It walks `target_directory` (defaulting to `/`) depth +//! first in the shared path order, skips `.git`, matches `glob_pattern`, +//! and stops at 15,000 bytes. //! //! Grep is real. It searches the files under a path with a Rust regular //! expression, in path order, and prints each matching line as `N:text` @@ -64,14 +74,13 @@ //! and a binary file, a link, an over-size file, and an entry that cannot //! be read are skipped and counted, never a failure. A search ends its //! step every 32 files or directories, so a cancel or a stop can drop it -//! between two steps. File text comes back as untrusted output. +//! between two steps. //! //! Write is real. It makes a file, or replaces the whole contents of one, //! with one write, and the Host makes each directory on the way to the //! file. It reads nothing first, so what was at the path is gone. It //! refuses contents over 16 MiB, the most one write takes. Its answer is -//! the count of bytes written in fixed text, so it comes back as trusted -//! output. +//! the count of bytes written in fixed text. //! //! StrReplace is real. It reads a file as Read does, with the same //! refusals of a directory, a special file, and a file over 16 MiB, and @@ -80,20 +89,14 @@ //! replace must occur exactly once, unless `replace_all` is set, and a //! failure states how many times it occurs. The edit is a read and then a //! write, so a change that another task makes to the file between the two -//! is lost. Its answer is the count of replacements in fixed text, so it -//! comes back as trusted output. +//! is lost. Its answer is the count of replacements in fixed text. //! //! Delete is real. It asks what the path names and then asks for its //! removal. It refuses a directory with a sentence, and it fails on a //! path where nothing is. The delete is a stat and then a removal, so a //! directory with no entries that another task puts at the path between //! the two is removed. A link goes as a link, so what it leads to stays. -//! Its answer is fixed text, so it comes back as trusted output. -//! -//! Glob is still a stub: a call with arguments that match the schema -//! answers [`NOT_IMPLEMENTED`]. For every tool, a call whose arguments do -//! not match fails with an invalid-arguments -//! [`ToolError`](runvil_plugin_sdk::ToolError) naming the parameter. +//! Its answer is fixed text. //! //! # Where the file access goes //! @@ -151,6 +154,7 @@ mod check; mod dir; #[cfg(test)] mod fake; +mod glob; mod grep; mod matcher; mod order; @@ -168,7 +172,6 @@ use std::sync::Arc; use runvil_plugin_sdk::{Pack, PackInfo, Plugin, Refusal}; -pub use crate::pack::NOT_IMPLEMENTED; use crate::spec::Definition; /// The Plugin instance the Host holds while the Plugin is loaded. It diff --git a/crates/plugin-std/src/pack-tests.rs b/crates/plugin-std/src/pack-tests.rs index 044902b..a3a975b 100644 --- a/crates/plugin-std/src/pack-tests.rs +++ b/crates/plugin-std/src/pack-tests.rs @@ -1,13 +1,12 @@ -//! Unit tests for the `std` Pack's stub text, the definitions it builds -//! from, the arguments it parses, the tool a call's name picks, and the -//! tools it says change files. +//! Unit tests for the `std` Pack's definitions, argument parsing, tool +//! routing, caller-aware error handling, and change flags. use std::sync::Arc; use runvil_plugin_sdk::testing::Files; -use runvil_plugin_sdk::{ToolError, ToolErrorKind, ToolOutput}; +use runvil_plugin_sdk::{Caller, ToolError, ToolErrorKind, ToolOutput}; -use super::{INFO, NOT_IMPLEMENTED, StdPack, parse, run}; +use super::{INFO, StdPack, dispatch, parse, run}; use crate::fake::block_on; use crate::spec::{self, Definition}; @@ -23,41 +22,6 @@ fn the_pack_is_runvil_std_with_its_one_line_description() { assert_eq!(INFO.description, "Read, write, search, and delete files"); } -#[test] -fn the_stub_names_the_tool_in_every_place_the_text_mentions_it() { - let text = NOT_IMPLEMENTED.replace("", "Grep"); - assert_eq!( - text.matches("Grep").count(), - 2, - "the text names the tool twice: {text}" - ); - assert!(!text.contains(""), "{text}"); -} - -#[test] -fn the_stub_says_the_implementation_is_missing_and_the_result_is_stable() { - let text = NOT_IMPLEMENTED.replace("", "Write"); - for phrase in [ - "not implemented in this build", - "The implementation is missing", - "nothing in this session will change that", - "Calling Write again is safe", - "this same result every time", - "Carry on without it.", - ] { - assert!(text.contains(phrase), "missing {phrase:?}: {text}"); - } -} - -#[test] -fn the_stub_says_what_is_missing_before_it_says_anything_else() { - let text = NOT_IMPLEMENTED.replace("", "Read"); - assert!( - text.starts_with("The Read tool is not implemented"), - "the first clause says what is missing: {text}" - ); -} - #[test] fn the_specs_are_the_seven_the_crate_names_in_order() { let segments: Vec<&str> = spec::all() @@ -128,11 +92,14 @@ fn a_call_goes_to_the_tool_its_name_picks() { .file("/p/a.md", "needle\n") .file("/p/b.md", "hay\n"); let read = ran("read", r#"{"path":"/p/a.md"}"#, &files).expect("the file reads"); - assert_eq!(read.text(), " 1|needle\n"); + assert_eq!(read.text(), "needle\n"); let dir = ran("dir", r#"{"target_directory":"/p"}"#, &files).expect("the directory lists"); assert_eq!(dir.text(), "/p/\n - a.md\n - b.md"); let grep = ran("grep", r#"{"pattern":"needle"}"#, &files).expect("the tree searches"); assert_eq!(grep.text(), "/p/a.md\n 1:needle"); + let glob = ran("glob", r#"{"glob_pattern":"*.md"}"#, &files).expect("the tree globs"); + assert_eq!(glob.text(), "/p/a.md\n/p/b.md"); + assert!(glob.is_trusted()); let write = ran("write", r#"{"path":"/p/c.md","contents":"x"}"#, &files).expect("the file is written"); assert_eq!(write.text(), "Wrote 1 byte."); @@ -148,10 +115,32 @@ fn a_call_goes_to_the_tool_its_name_picks() { let rm = ran("rm", r#"{"path":"/p/c.md"}"#, &files).expect("the file is deleted"); assert_eq!(rm.text(), "Deleted the file."); assert!(files.stat("/p/c.md").is_err()); - let stub = - ran("glob", r#"{"glob_pattern":"*.md"}"#, &files).expect("the stub answers its text"); - assert_eq!(stub.text(), NOT_IMPLEMENTED.replace("", "Glob")); - assert!(stub.is_trusted()); +} + +#[test] +fn model_caller_receives_errors_as_trusted_text_and_script_caller_receives_tool_error() { + let files = Files::new(); + let model = block_on(dispatch( + spec::all(), + Caller::Model, + "read", + r#"{"path":"/missing.md"}"#, + &files, + )) + .expect("model caller gets plain text"); + assert!(model.is_trusted()); + assert_eq!(model.text(), "File not found: /missing.md"); + + let script = block_on(dispatch( + spec::all(), + Caller::Script, + "read", + r#"{"path":"/missing.md"}"#, + &files, + )) + .expect_err("script caller gets ToolError"); + assert_eq!(script.kind(), ToolErrorKind::Other); + assert_eq!(script.message(), "File not found: /missing.md"); } #[test] diff --git a/crates/plugin-std/src/pack.rs b/crates/plugin-std/src/pack.rs index d20a9d7..381fd53 100644 --- a/crates/plugin-std/src/pack.rs +++ b/crates/plugin-std/src/pack.rs @@ -1,11 +1,10 @@ -//! The `std` Pack: its [`INFO`], [`StdPack`], one run's instance, which -//! lists the Pack's tools and hands each call to its tool's module, and -//! the stub that Glob still answers with in this build. +//! The `std` Pack: its [`INFO`] and [`StdPack`], one run's instance, which +//! lists the Pack's tools and hands each call to its tool's module. use std::sync::Arc; use runvil_plugin_sdk::{ - BoxFuture, Pack, PackInfo, ToolCall, ToolError, ToolErrorKind, ToolInfo, ToolOutput, + BoxFuture, Caller, Pack, PackInfo, ToolCall, ToolError, ToolErrorKind, ToolInfo, ToolOutput, }; use serde_json::Value; @@ -13,20 +12,6 @@ use crate::check::make_invalid_arguments_error; use crate::source::Source; use crate::spec::Definition; -/// What a call to a tool that is still a stub answers in this build, when -/// its arguments match the schema. Glob is the one stub, and every other -/// tool is real and never answers this. -/// -/// The text says the implementation is missing rather than that the call -/// was wrong, because a model that reads it should stop calling the tool. -/// It also says a repeat call is safe, so a model that retries anyway -/// learns the outcome is the same rather than assuming the call was -/// malformed. `` is the tool's wire name. -pub const NOT_IMPLEMENTED: &str = "The tool is not implemented in this build. The \ - implementation is missing and nothing in this session will change that. Calling again \ - is safe, but it will return this same result every time, whatever the arguments. Carry on \ - without it."; - /// The Pack's name and description. Its name is `runvil/std`, so its /// Pack id is `std`, and a prompt reaches its tools as `std/`. pub(crate) const INFO: PackInfo = @@ -74,11 +59,6 @@ fn changes_files(segment: &str) -> bool { matches!(segment, "write" | "replace" | "rm") } -/// The stub text for the tool the model calls `wire_name`. -fn stub(wire_name: &str) -> String { - NOT_IMPLEMENTED.replace("", wire_name) -} - /// The call's arguments, parsed from the JSON text the Host sent for the /// tool the model calls `wire_name`. fn parse(wire_name: &str, text: &str) -> Result { @@ -110,11 +90,32 @@ async fn run( match definition.segment { "read" => crate::read::call(source, definition, &args).await, "dir" => crate::dir::call(source, definition, &args).await, + "glob" => crate::glob::call(source, definition, &args).await, "grep" => crate::grep::call(source, definition, &args).await, "write" => crate::write::call(source, definition, &args).await, "replace" => crate::replace::call(source, definition, &args).await, "rm" => crate::rm::call(source, definition, &args).await, - _ => Ok(ToolOutput::trusted(stub(&definition.wire_name))), + other => Err(ToolError::new( + ToolErrorKind::Other, + format!("std has no tool named {other}"), + )), + } +} + +/// Dispatches one call with caller-aware error handling: `Caller::Model` +/// receives domain and argument errors as plain trusted text so the model +/// can recover without tripping a tool-call failure, while `Caller::Script` +/// receives the structured [`ToolError`]. +async fn dispatch( + definitions: &[Definition], + caller: Caller, + name: &str, + arguments: &str, + source: &impl Source, +) -> Result { + match (caller, run(definitions, name, arguments, source).await) { + (Caller::Model, Err(error)) => Ok(ToolOutput::trusted(error.message().to_owned())), + (_, result) => result, } } @@ -124,7 +125,16 @@ impl Pack for StdPack { } fn call<'a>(&'a self, call: ToolCall<'a>) -> BoxFuture<'a, Result> { - Box::pin(async move { run(&self.definitions, call.tool(), call.arguments(), &call).await }) + Box::pin(async move { + dispatch( + &self.definitions, + call.caller(), + call.tool(), + call.arguments(), + &call, + ) + .await + }) } } diff --git a/crates/plugin-std/src/read.rs b/crates/plugin-std/src/read.rs index 4e5d025..dd3270f 100644 --- a/crates/plugin-std/src/read.rs +++ b/crates/plugin-std/src/read.rs @@ -4,7 +4,7 @@ //! the run's policy applies. It refuses a directory, a special //! file, a file over 16 MiB, and binary data, and it never truncates a //! file: a read that does not reach the last line says which offset -//! continues it. File text is returned as untrusted output. +//! continues it. File text is returned as trusted output. mod args; mod render; @@ -64,7 +64,7 @@ async fn read_file( let decoded = decode(&bytes); let lines = split_lines(&decoded.text); if lines.is_empty() { - return Ok(ToolOutput::untrusted("File is empty.")); + return Ok(ToolOutput::trusted("File is empty.")); } let Some(window) = window::window(lines.len(), request.offset, request.limit) else { return Err(message(format!( @@ -74,7 +74,7 @@ async fn read_file( ))); }; let notes = render::notes(decoded.utf16, decoded.invalid); - Ok(ToolOutput::untrusted(render::render( + Ok(ToolOutput::trusted(render::render( &lines, &window, ¬es, cap, ))) } diff --git a/crates/plugin-std/src/read/render.rs b/crates/plugin-std/src/read/render.rs index 87ba6eb..a8678f2 100644 --- a/crates/plugin-std/src/read/render.rs +++ b/crates/plugin-std/src/read/render.rs @@ -1,25 +1,32 @@ //! The render: turns a window of lines into the text Read answers with. //! -//! Each line prints as `{number:>6}|{text}`: a six-wide right-aligned -//! number, a pipe, and no space. The number is always on and widens past -//! six digits, and it is not part of the line. The numbered lines are -//! followed by the notes and then the trailer, each on its own line, with -//! no newline after the last one. +//! Every 10th line (plus the starting line when `offset` is past line 1) +//! prints as `{number:>6}|{text}`: a six-wide right-aligned number, a +//! pipe, and no space. The number widens past six digits, and it is not +//! part of the line. Lines between markers print their text with no +//! prefix. The lines are followed by the notes and then the trailer, each +//! on its own line, with no newline after the last one. use crate::check::plural; use crate::text::clip_to_boundary; use super::window::Window; -/// The numbered prefix of line `number`. -fn prefix(number: usize) -> String { - format!("{number:>6}|") +/// The numbered prefix of line `number` in a window starting at +/// `window_first`: present on every 10th line and on the first line when +/// the window starts past line 1, empty otherwise. +fn line_prefix(number: usize, window_first: usize) -> String { + if number.is_multiple_of(10) || (window_first > 1 && number == window_first) { + format!("{number:>6}|") + } else { + String::new() + } } /// The text of the `window` over `lines`, with `notes` and a trailer when /// the read stops early. /// -/// The numbered lines hold at most `cap` bytes, counting each prefix, the +/// The rendered lines hold at most `cap` bytes, counting each prefix, the /// text, and its newline, and not the notes or the trailer. A line that /// would pass the cap is left out, and the trailer names the offset that /// continues. When the window's first line alone passes the cap, it is @@ -36,7 +43,7 @@ pub(super) fn render(lines: &[&str], window: &Window, notes: &[String], cap: usi let Some(text) = lines.get(number - 1) else { break; }; - let prefix = prefix(number); + let prefix = line_prefix(number, window.first); let cost = prefix.len() + text.len() + 1; if used + cost > cap { break; @@ -80,7 +87,7 @@ pub(super) fn render(lines: &[&str], window: &Window, notes: &[String], cap: usi /// cut. fn cut_first_line(lines: &[&str], number: usize, cap: usize, body: &mut String) -> String { let text = lines.get(number - 1).copied().unwrap_or_default(); - let prefix = prefix(number); + let prefix = line_prefix(number, number); let allowance = cap.saturating_sub(prefix.len() + 1); let kept = clip_to_boundary(text, 0, allowance); body.push_str(&prefix); diff --git a/crates/plugin-std/src/read/tests.rs b/crates/plugin-std/src/read/tests.rs index d5da8e3..7a15b0a 100644 --- a/crates/plugin-std/src/read/tests.rs +++ b/crates/plugin-std/src/read/tests.rs @@ -55,10 +55,10 @@ fn read_capped( block_on(super::read_file(files, "Read", &request, cap)) } -/// The text of a successful read, which must be untrusted output. +/// The text of a successful read, which must be trusted output. fn text_of(result: Result) -> String { let output = result.expect("the read succeeds"); - assert!(!output.is_trusted(), "{}", output.text()); + assert!(output.is_trusted(), "{}", output.text()); output.text().to_owned() } diff --git a/crates/plugin-std/src/read/tests/arguments.rs b/crates/plugin-std/src/read/tests/arguments.rs index 22027d9..ca2b246 100644 --- a/crates/plugin-std/src/read/tests/arguments.rs +++ b/crates/plugin-std/src/read/tests/arguments.rs @@ -203,7 +203,7 @@ fn a_null_offset_and_a_null_limit_read_as_absent() { &json!({ "path": "/a.md", "offset": null, "limit": null }), )); assert_eq!(plain, nulls); - assert_eq!(plain, " 1|one\n 2|two\n"); + assert_eq!(plain, "one\ntwo\n"); } #[test] diff --git a/crates/plugin-std/src/read/tests/failures.rs b/crates/plugin-std/src/read/tests/failures.rs index 9da4fbf..c51e708 100644 --- a/crates/plugin-std/src/read/tests/failures.rs +++ b/crates/plugin-std/src/read/tests/failures.rs @@ -102,7 +102,7 @@ fn a_link_is_read_through_and_a_link_to_a_directory_is_a_directory() { .with("/dirlink", Node::Link); assert_eq!( text_of(read(&source, &json!({ "path": "/filelink" }))), - " 1|hello\n" + "hello\n" ); assert_eq!( failure_of(read(&source, &json!({ "path": "/dirlink" }))), @@ -131,7 +131,7 @@ fn a_binary_file_is_refused_by_its_content_not_its_name() { let text = seeded("/data.bin", b"plain text\n"); assert_eq!( text_of(read(&text, &json!({ "path": "/data.bin" }))), - " 1|plain text\n" + "plain text\n" ); } @@ -148,9 +148,9 @@ fn a_file_one_byte_over_the_ceiling_is_refused_and_never_truncated() { fn a_file_exactly_at_the_ceiling_is_read() { let files = seeded("/edge.txt", &vec![b'a'; 16_777_216]); let text = text_of(read(&files, &json!({ "path": "/edge.txt" }))); - assert!(text.starts_with(" 1|aaaa"), "the line is numbered"); + assert!(text.starts_with("aaaa"), "the line is read"); assert!( - text.contains("[Line 1 is 16777216 bytes and is cut after 99992 bytes."), + text.contains("[Line 1 is 16777216 bytes and is cut after 99999 bytes."), "{}", &text[text.len() - 150..] ); @@ -196,7 +196,7 @@ fn a_utf8_byte_order_mark_is_not_part_of_the_first_line() { let files = seeded("/mark.md", b"\xEF\xBB\xBFhello\n"); assert_eq!( text_of(read(&files, &json!({ "path": "/mark.md" }))), - " 1|hello\n" + "hello\n" ); } @@ -212,7 +212,7 @@ fn a_utf16_file_is_decoded_and_the_note_names_its_byte_order() { let files = seeded(name, &bytes); assert_eq!( text_of(read(&files, &json!({ "path": name }))), - format!(" 1|a\n 2|b\n[Note: the file is {order} and was decoded to text.]"), + format!("a\nb\n[Note: the file is {order} and was decoded to text.]"), "{name}" ); } @@ -232,7 +232,7 @@ fn an_invalid_byte_is_shown_as_the_replacement_character_with_a_note() { let files = seeded("/latin.txt", &[0x61, 0xFF, 0x62, 0x0A]); assert_eq!( text_of(read(&files, &json!({ "path": "/latin.txt" }))), - " 1|a\u{FFFD}b\n\ + "a\u{FFFD}b\n\ [Note: 1 invalid UTF-8 sequence in this file were shown as U+FFFD.]" ); } @@ -242,7 +242,7 @@ fn a_file_that_ends_mid_sequence_counts_one_replacement() { let files = seeded("/cut.txt", &[b'a', b'\n', b'b', 0xE2, 0x82]); assert_eq!( text_of(read(&files, &json!({ "path": "/cut.txt" }))), - " 1|a\n 2|b\u{FFFD}\n\ + "a\nb\u{FFFD}\n\ [Note: 1 invalid UTF-8 sequence in this file were shown as U+FFFD.]" ); } @@ -252,14 +252,14 @@ fn the_replacement_note_comes_before_the_trailer() { let files = seeded("/two.txt", &[0x61, 0xFF, 0x0A, 0x62, 0x0A]); assert_eq!( text_of(read(&files, &json!({ "path": "/two.txt", "limit": 1 }))), - " 1|a\u{FFFD}\n\ + "a\u{FFFD}\n\ [Note: 1 invalid UTF-8 sequence in this file were shown as U+FFFD.]\n\ [Showing lines 1-1 of 2. Use offset=2 to continue.]" ); } #[test] -fn every_successful_read_is_untrusted_output() { +fn every_successful_read_is_trusted_output() { let files = seeded("/a.md", b"one\ntwo\n") .file("/empty.md", b"") .file("/long.md", "x".repeat(150_000)); @@ -271,10 +271,10 @@ fn every_successful_read_is_untrusted_output() { json!({ "path": "/long.md" }), ] { let output = read(&files, &args).expect("the read succeeds"); - assert!(!output.is_trusted(), "{args}"); + assert!(output.is_trusted(), "{args}"); } let capped = read_capped(&files, "/a.md", None, None, 10).expect("a cut read succeeds"); - assert!(!capped.is_trusted()); + assert!(capped.is_trusted()); } #[test] diff --git a/crates/plugin-std/src/read/tests/paging.rs b/crates/plugin-std/src/read/tests/paging.rs index dee22df..48c9949 100644 --- a/crates/plugin-std/src/read/tests/paging.rs +++ b/crates/plugin-std/src/read/tests/paging.rs @@ -27,10 +27,16 @@ fn rebuild(file: &str, total: usize, cap: usize, limit: Option) -> Vec6}|"), "page {pages}"); + let content = if number.is_multiple_of(10) || (page_start > 1 && number == page_start) { + let expected_prefix = format!("{number:>6}|"); + line.strip_prefix(&expected_prefix) + .unwrap_or_else(|| panic!("page {pages} line {number}: {line}")) + } else { + line + }; rebuilt.push(content.to_owned()); } let Some(trailer) = trailer else { diff --git a/crates/plugin-std/src/read/tests/render.rs b/crates/plugin-std/src/read/tests/render.rs index 1559dfc..9652477 100644 --- a/crates/plugin-std/src/read/tests/render.rs +++ b/crates/plugin-std/src/read/tests/render.rs @@ -1,28 +1,33 @@ -//! The render: the numbered lines, the byte cap, the trailer, the cut of a -//! first line that alone passes the cap, and the notes. +//! The render: the sparse line numbers, the byte cap, the trailer, the +//! cut of a first line that alone passes the cap, and the notes. use super::{read_capped, seeded, text_of}; use crate::read::BYTE_CAP; use crate::read::render::{notes, render}; use crate::read::window::Window; -/// The three lines most render tests print. Each costs 11 bytes: a -/// seven-byte prefix, three bytes of text, and a newline. +/// The three lines most render tests print. Each costs 4 bytes from line 1: +/// three bytes of text and a newline. const LINES: [&str; 3] = ["aaa", "bbb", "ccc"]; /// The window over every line of [`LINES`]. const ALL: Window = Window { first: 1, last: 3 }; #[test] -fn every_line_prints_as_a_six_wide_number_a_pipe_and_the_text() { - let text = render(&LINES, &ALL, &[], BYTE_CAP); - assert_eq!(text, " 1|aaa\n 2|bbb\n 3|ccc\n"); +fn every_tenth_line_prints_with_a_six_wide_number_and_lines_between_do_not() { + let lines: Vec = (1..=12).map(|n| format!("l{n}")).collect(); + let refs: Vec<&str> = lines.iter().map(String::as_str).collect(); + let text = render(&refs, &Window { first: 1, last: 12 }, &[], BYTE_CAP); + assert_eq!( + text, + "l1\nl2\nl3\nl4\nl5\nl6\nl7\nl8\nl9\n 10|l10\nl11\nl12\n" + ); } #[test] -fn a_window_in_the_middle_keeps_the_real_line_numbers() { +fn a_window_in_the_middle_anchors_its_first_line_with_its_line_number() { let text = render(&LINES, &Window { first: 2, last: 3 }, &[], BYTE_CAP); - assert_eq!(text, " 2|bbb\n 3|ccc\n"); + assert_eq!(text, " 2|bbb\nccc\n"); } #[test] @@ -36,44 +41,47 @@ fn a_window_that_stops_early_ends_with_the_limit_trailer() { #[test] fn lines_that_exactly_fill_the_cap_all_print_and_no_trailer_follows() { - let text = render(&LINES, &ALL, &[], 33); - assert_eq!(text, " 1|aaa\n 2|bbb\n 3|ccc\n"); + let text = render(&LINES, &ALL, &[], 12); + assert_eq!(text, "aaa\nbbb\nccc\n"); } #[test] fn the_line_that_would_pass_the_cap_is_left_out_and_the_trailer_names_the_cap() { - let text = render(&LINES, &ALL, &[], 32); + let text = render(&LINES, &ALL, &[], 11); assert_eq!( text, - " 1|aaa\n 2|bbb\n\ - [Showing lines 1-2 of 3 (32-byte limit). Use offset=3 to continue.]" + "aaa\nbbb\n\ + [Showing lines 1-2 of 3 (11-byte limit). Use offset=3 to continue.]" ); } #[test] fn the_cap_counts_each_prefix_the_text_and_the_newline() { - for (cap, printed) in [(11, 1), (21, 1), (22, 2), (32, 2), (33, 3)] { + for (cap, printed) in [(4, 1), (7, 1), (8, 2), (11, 2), (12, 3)] { let text = render(&LINES, &ALL, &[], cap); - let shown = text.lines().filter(|line| line.contains('|')).count(); + let shown = text + .lines() + .filter(|line| !line.starts_with("[Showing")) + .count(); assert_eq!(shown, printed, "cap {cap}: {text}"); } } #[test] fn the_cap_trailer_wins_over_the_limit_when_the_cap_stops_first() { - let text = render(&LINES, &Window { first: 1, last: 2 }, &[], 11); + let text = render(&LINES, &Window { first: 1, last: 2 }, &[], 4); assert_eq!( text, - " 1|aaa\n[Showing lines 1-1 of 3 (11-byte limit). Use offset=2 to continue.]" + "aaa\n[Showing lines 1-1 of 3 (4-byte limit). Use offset=2 to continue.]" ); } #[test] fn a_first_line_that_alone_passes_the_cap_is_cut_and_the_trailer_says_so() { - let text = render(&LINES, &ALL, &[], 10); + let text = render(&LINES, &ALL, &[], 3); assert_eq!( text, - " 1|aa\n[Line 1 is 3 bytes and is cut after 2 bytes. \ + "aa\n[Line 1 is 3 bytes and is cut after 2 bytes. \ No parameter reads the rest of a line. Use offset=2 to continue.]" ); } @@ -90,11 +98,11 @@ fn a_cut_first_line_on_the_last_line_of_the_file_offers_no_next_offset() { #[test] fn a_cap_below_the_prefix_keeps_no_text_and_does_not_panic() { - let text = render(&LINES, &ALL, &[], 7); + let text = render(&LINES, &Window { first: 2, last: 3 }, &[], 7); assert_eq!( text, - " 1|\n[Line 1 is 3 bytes and is cut after 0 bytes. \ - No parameter reads the rest of a line. Use offset=2 to continue.]" + " 2|\n[Line 2 is 3 bytes and is cut after 0 bytes. \ + No parameter reads the rest of a line. Use offset=3 to continue.]" ); } @@ -104,14 +112,11 @@ fn notes_come_after_the_lines_and_before_the_trailer_each_on_its_own_line() { let with_trailer = render(&LINES, &Window { first: 1, last: 1 }, ¬e_lines, BYTE_CAP); assert_eq!( with_trailer, - " 1|aaa\n[Note: one]\n[Note: two]\n\ + "aaa\n[Note: one]\n[Note: two]\n\ [Showing lines 1-1 of 3. Use offset=2 to continue.]" ); let without = render(&LINES, &ALL, ¬e_lines, BYTE_CAP); - assert_eq!( - without, - " 1|aaa\n 2|bbb\n 3|ccc\n[Note: one]\n[Note: two]" - ); + assert_eq!(without, "aaa\nbbb\nccc\n[Note: one]\n[Note: two]"); } #[test] @@ -151,12 +156,14 @@ fn the_utf16_note_comes_before_the_replacement_note_and_clean_text_has_none() { } #[test] -fn five_thousand_short_lines_stop_at_2083_lines_under_the_default_cap() { +fn five_thousand_short_lines_stop_under_the_default_cap() { let file = format!("{}\n", "x".repeat(40)).repeat(5_000); let files = seeded("/many.txt", file.as_bytes()); let text = text_of(read_capped(&files, "/many.txt", None, None, BYTE_CAP)); + // Every 10 lines cost 9 * 41 + 48 = 417 bytes; 239 blocks = 99,663 bytes, + // plus 8 more unnumbered lines (8 * 41 = 328) = 99,991 bytes -> 2,398 lines. let trailer = - "[Showing lines 1-2083 of 5000 (100000-byte limit). Use offset=2084 to continue.]"; + "[Showing lines 1-2398 of 5000 (100000-byte limit). Use offset=2399 to continue.]"; assert!( text.ends_with(&format!("\n{trailer}")), "the trailer ends the read" @@ -164,18 +171,18 @@ fn five_thousand_short_lines_stop_at_2083_lines_under_the_default_cap() { let numbered = text .lines() .filter(|line| line.as_bytes().get(6) == Some(&b'|')); - assert_eq!(numbered.count(), 2_083); + assert_eq!(numbered.count(), 239); assert_eq!( text.len() - trailer.len(), - 2_083 * 48, - "each numbered line is 7 + 40 + 1 bytes and the trailer is not counted" + 99_991, + "each 10-line block is 417 bytes and the trailer is not counted" ); assert!(text.len() <= 100_120, "{}", text.len()); } /// What Read answers for a file whose first line is `line`, followed by /// a second line when `later` is set, split into the line it printed -/// after its prefix and the trailer. +/// and the trailer. fn first_line_cut(line: &str, later: bool) -> (String, String) { let mut file = line.to_owned(); file.push('\n'); @@ -185,67 +192,64 @@ fn first_line_cut(line: &str, later: bool) -> (String, String) { let files = seeded("/long.txt", file.as_bytes()); let text = text_of(read_capped(&files, "/long.txt", None, None, BYTE_CAP)); let (shown, trailer) = text.split_once('\n').expect("a cut read has a trailer"); - let kept = shown - .strip_prefix(" 1|") - .expect("the first line is numbered"); - (kept.to_owned(), trailer.to_owned()) + (shown.to_owned(), trailer.to_owned()) } #[test] -fn a_150000_byte_ascii_line_keeps_99992_bytes() { +fn a_150000_byte_ascii_line_keeps_99999_bytes() { let line = "x".repeat(150_000); let (kept, trailer) = first_line_cut(&line, false); - assert_eq!(kept.len(), 99_992); + assert_eq!(kept.len(), 99_999); assert!(line.starts_with(&kept)); assert_eq!( trailer, - "[Line 1 is 150000 bytes and is cut after 99992 bytes. \ + "[Line 1 is 150000 bytes and is cut after 99999 bytes. \ No parameter reads the rest of a line.]" ); let (_, trailer) = first_line_cut(&line, true); assert_eq!( trailer, - "[Line 1 is 150000 bytes and is cut after 99992 bytes. \ + "[Line 1 is 150000 bytes and is cut after 99999 bytes. \ No parameter reads the rest of a line. Use offset=2 to continue.]" ); } #[test] -fn the_cut_numbered_line_fills_the_cap_exactly_for_ascii() { +fn the_cut_first_line_fills_the_cap_exactly_for_ascii() { let files = seeded("/long.txt", "x".repeat(150_000).as_bytes()); let text = text_of(read_capped(&files, "/long.txt", None, None, BYTE_CAP)); - let first = text.split_once('\n').expect("one numbered line").0; + let first = text.split_once('\n').expect("one cut line").0; assert_eq!(first.len() + 1, 100_000); } #[test] -fn fifty_thousand_cjk_characters_keep_99990_bytes() { +fn fifty_thousand_cjk_characters_keep_99999_bytes() { let line = "\u{4E2D}".repeat(50_000); let (kept, trailer) = first_line_cut(&line, false); - assert_eq!(kept.len(), 99_990); - assert_eq!(kept.chars().count(), 33_330); + assert_eq!(kept.len(), 99_999); + assert_eq!(kept.chars().count(), 33_333); assert!( - trailer.contains("is 150000 bytes and is cut after 99990 bytes."), + trailer.contains("is 150000 bytes and is cut after 99999 bytes."), "{trailer}" ); } #[test] -fn a_line_of_two_byte_characters_keeps_99992_bytes() { +fn a_line_of_two_byte_characters_keeps_99998_bytes() { let line = "\u{E9}".repeat(75_000); let (kept, trailer) = first_line_cut(&line, false); - assert_eq!(kept.len(), 99_992); + assert_eq!(kept.len(), 99_998); assert!(line.starts_with(&kept)); - assert!(trailer.contains("cut after 99992 bytes."), "{trailer}"); + assert!(trailer.contains("cut after 99998 bytes."), "{trailer}"); } #[test] -fn a_line_of_four_byte_emoji_keeps_24998_of_them() { +fn a_line_of_four_byte_emoji_keeps_24999_of_them() { let line = "\u{1F600}".repeat(37_500); let (kept, trailer) = first_line_cut(&line, false); - assert_eq!(kept.len(), 99_992); - assert_eq!(kept.chars().count(), 24_998); - assert!(trailer.contains("cut after 99992 bytes."), "{trailer}"); + assert_eq!(kept.len(), 99_996); + assert_eq!(kept.chars().count(), 24_999); + assert!(trailer.contains("cut after 99996 bytes."), "{trailer}"); } #[test] @@ -263,10 +267,10 @@ fn a_cut_at_a_later_line_names_that_line() { #[test] fn a_line_that_only_just_fits_is_not_cut() { - let line = "x".repeat(BYTE_CAP - 8); + let line = "x".repeat(BYTE_CAP - 1); let files = seeded("/fit.txt", format!("{line}\n").as_bytes()); let text = text_of(read_capped(&files, "/fit.txt", None, None, BYTE_CAP)); - assert_eq!(text, format!(" 1|{line}\n")); + assert_eq!(text, format!("{line}\n")); } #[test] @@ -275,11 +279,8 @@ fn a_cap_sweep_never_splits_a_character_and_the_notice_counts_the_kept_bytes() { let files = seeded("/mixed.txt", format!("{line}\n").as_bytes()); for cap in 12..=60 { let text = text_of(read_capped(&files, "/mixed.txt", None, None, cap)); - let (shown, trailer) = text.split_once('\n').expect("a cut read has a trailer"); - let kept = shown - .strip_prefix(" 1|") - .expect("the first line is numbered"); - let allowance = cap - 8; + let (kept, trailer) = text.split_once('\n').expect("a cut read has a trailer"); + let allowance = cap - 1; assert!(line.starts_with(kept), "cap {cap}: a prefix of the line"); assert!( kept.len() <= allowance, diff --git a/crates/plugin-std/src/read/tests/window.rs b/crates/plugin-std/src/read/tests/window.rs index bf16888..023c2f2 100644 --- a/crates/plugin-std/src/read/tests/window.rs +++ b/crates/plugin-std/src/read/tests/window.rs @@ -60,10 +60,10 @@ fn a_one_line_file_has_one_window() { } #[test] -fn a_whole_file_read_numbers_every_line_and_prints_no_trailer() { +fn a_whole_file_read_prints_every_line_and_numbers_every_tenth() { let files = seeded("/notes.md", numbered_file(3, true).as_bytes()); let text = text_of(read(&files, &json!({ "path": "/notes.md" }))); - assert_eq!(text, " 1|line 1\n 2|line 2\n 3|line 3\n"); + assert_eq!(text, "line 1\nline 2\nline 3\n"); } #[test] @@ -78,21 +78,21 @@ fn a_file_without_a_final_newline_has_the_same_lines() { fn a_blank_last_line_counts_as_a_line() { let files = seeded("/a.md", b"a\n\n"); let text = text_of(read(&files, &json!({ "path": "/a.md" }))); - assert_eq!(text, " 1|a\n 2|\n"); + assert_eq!(text, "a\n\n"); } #[test] fn carriage_returns_are_not_part_of_a_line() { let files = seeded("/a.md", b"a\r\nb\r\n"); let text = text_of(read(&files, &json!({ "path": "/a.md" }))); - assert_eq!(text, " 1|a\n 2|b\n"); + assert_eq!(text, "a\nb\n"); } #[test] fn a_lone_carriage_return_inside_a_line_stays_in_the_line() { let files = seeded("/a.md", b"first\rNEEDLE\rthird\n"); let text = text_of(read(&files, &json!({ "path": "/a.md" }))); - assert_eq!(text, " 1|first\rNEEDLE\rthird\n"); + assert_eq!(text, "first\rNEEDLE\rthird\n"); } #[test] @@ -104,7 +104,7 @@ fn a_limit_that_stops_before_the_end_names_the_next_offset() { )); assert_eq!( text, - " 4|line 4\n 5|line 5\n 6|line 6\n\ + " 4|line 4\nline 5\nline 6\n\ [Showing lines 4-6 of 10. Use offset=7 to continue.]" ); } @@ -149,7 +149,7 @@ fn an_offset_of_zero_reads_as_the_first_line() { )); assert_eq!( zero, - " 1|line 1\n 2|line 2\n[Showing lines 1-2 of 10. Use offset=3 to continue.]" + "line 1\nline 2\n[Showing lines 1-2 of 10. Use offset=3 to continue.]" ); } diff --git a/crates/plugin-std/tests/it/changes.rs b/crates/plugin-std/tests/it/changes.rs index 7c34502..8b5a961 100644 --- a/crates/plugin-std/tests/it/changes.rs +++ b/crates/plugin-std/tests/it/changes.rs @@ -5,13 +5,13 @@ use plugin_std::Std; use runvil_plugin_sdk::testing::{self, Files}; -use runvil_plugin_sdk::{FileError, FileErrorKind, ToolError, ToolErrorKind, ToolOutput}; +use runvil_plugin_sdk::{Caller, FileError, FileErrorKind, ToolError, ToolErrorKind, ToolOutput}; use serde_json::{Value, json}; use crate::tools::PACK; -/// Calls the tool `name` with `args` over `files`, and returns what the -/// call answered beside the files as the call left them. +/// Calls the tool `name` with `args` over `files` as `Caller::Script`, and +/// returns what the call answered beside the files as the call left them. fn change(files: Files, name: &str, args: &Value) -> (Result, Files) { let loaded = testing::load::().expect("the Plugin loads"); let pack = loaded @@ -19,7 +19,9 @@ fn change(files: Files, name: &str, args: &Value) -> (Result = output.text().lines().collect(); assert_eq!( rows.len(), @@ -118,7 +118,7 @@ fn abandoning_a_search_at_a_request_or_at_its_first_pause_leaves_the_instance_us .call("read", r#"{"path":"/f0000.txt"}"#) .expect("the call follows the contract") .expect("the files still read after the cancel"); - assert_eq!(read.text(), " 1|x\n"); + assert_eq!(read.text(), "x\n"); let again = pack .call("grep", &args()) .expect("the call follows the contract") diff --git a/crates/plugin-std/tests/it/tools.rs b/crates/plugin-std/tests/it/tools.rs index 5443426..d8737e5 100644 --- a/crates/plugin-std/tests/it/tools.rs +++ b/crates/plugin-std/tests/it/tools.rs @@ -2,28 +2,41 @@ //! Plugin inserts, the seven tools an instance adds, and what a call //! answers over the files of its run. -use plugin_std::{NOT_IMPLEMENTED, Std}; +use plugin_std::Std; use runvil_plugin_sdk::testing::{self, Files}; -use runvil_plugin_sdk::{FileError, FileErrorKind, ToolError, ToolErrorKind, ToolOutput}; +use runvil_plugin_sdk::{Caller, FileError, FileErrorKind, ToolError, ToolErrorKind, ToolOutput}; use serde_json::{Value, json}; /// The name the Plugin inserts its Pack under. pub(crate) const PACK: &str = "runvil/std"; -/// Calls the tool `name` with `args` over `files`, as the Harness does: -/// load the Plugin, make one run's instance of the Pack, and run the call -/// to its end. -fn call_over(files: Files, name: &str, args: &Value) -> Result { +/// Calls the tool `name` with `args` over `files` as `caller`, as the +/// Harness does: load the Plugin, make one run's instance of the Pack, and +/// run the call to its end. +fn call_as( + files: Files, + caller: Caller, + name: &str, + args: &Value, +) -> Result { let loaded = testing::load::().expect("the Plugin loads"); let pack = loaded .new_pack(PACK) .expect("the Pack instance is made") .with_files(files); - pack.call(name, &args.to_string()) + pack.start(name, &args.to_string()) + .with_caller(caller) + .run() .expect("the call follows the contract") } -/// Calls the tool `name` with `args` over a run with no files. +/// Calls the tool `name` with `args` over `files` as `Caller::Script`. +fn call_over(files: Files, name: &str, args: &Value) -> Result { + call_as(files, Caller::Script, name, args) +} + +/// Calls the tool `name` with `args` over a run with no files as +/// `Caller::Script`. fn call(name: &str, args: &Value) -> Result { call_over(Files::new(), name, args) } @@ -71,23 +84,36 @@ fn each_run_gets_an_instance_of_its_own_with_the_same_tools() { } #[test] -fn glob_the_one_stub_answers_the_not_implemented_text_naming_itself() { - let output = - call("glob", &json!({ "glob_pattern": "**/*.md" })).expect("a matching call succeeds"); - assert_eq!(output.text(), NOT_IMPLEMENTED.replace("", "Glob")); +fn glob_matches_files_and_returns_trusted_output() { + let files = Files::new() + .file("/README.md", "hi") + .file("/docs/guide.md", "hi") + .file("/src/lib.rs", "fn main() {}"); + let output = call_over(files, "glob", &json!({ "glob_pattern": "*.md" })) + .expect("a matching call succeeds"); + assert_eq!(output.text(), "/README.md\n/docs/guide.md"); assert!(output.is_trusted()); } #[test] -fn the_not_implemented_text_says_the_result_never_changes() { - let text = NOT_IMPLEMENTED.replace("", "Read"); - assert!( - text.contains("nothing in this session will change that"), - "{text}" +fn model_caller_receives_domain_and_argument_errors_as_trusted_text() { + let missing = call_as( + Files::new(), + Caller::Model, + "read", + &json!({ "path": "/nope.md" }), + ) + .expect("model caller receives text instead of ToolError"); + assert!(missing.is_trusted()); + assert_eq!(missing.text(), "File not found: /nope.md"); + + let invalid = call_as(Files::new(), Caller::Model, "read", &json!({ "path": 7 })) + .expect("model caller receives invalid-argument text instead of ToolError"); + assert!(invalid.is_trusted()); + assert_eq!( + invalid.text(), + "std_Read: `path` must be a JSON string, and the call passed 7" ); - assert!(text.contains("Calling Read again is safe"), "{text}"); - assert!(text.contains("this same result every time"), "{text}"); - assert!(!text.contains('<'), "the name is filled in: {text}"); } #[test] @@ -133,15 +159,15 @@ fn arguments_that_are_not_an_object_fail_as_invalid_arguments() { } #[test] -fn read_answers_the_numbered_lines_of_a_file_as_untrusted_output() { +fn read_answers_the_lines_of_a_file_as_trusted_output() { let output = call_over( Files::new().file("/notes.md", "hello\nworld\n"), "read", &json!({ "path": "/notes.md" }), ) .expect("the file reads"); - assert_eq!(output.text(), " 1|hello\n 2|world\n"); - assert!(!output.is_trusted()); + assert_eq!(output.text(), "hello\nworld\n"); + assert!(output.is_trusted()); } #[test] @@ -153,7 +179,7 @@ fn read_answers_file_is_empty_for_a_zero_byte_file() { ) .expect("an empty file reads"); assert_eq!(output.text(), "File is empty."); - assert!(!output.is_trusted()); + assert!(output.is_trusted()); } #[test] @@ -178,7 +204,7 @@ fn a_read_the_policy_denies_fails_with_the_policys_own_reason() { } #[test] -fn list_dir_answers_the_tree_of_a_directory_as_untrusted_output() { +fn list_dir_answers_the_tree_of_a_directory_as_trusted_output() { let files = Files::new() .file("/proj/README.md", "hello") .file("/proj/src/lib.rs", "fn main() {}") @@ -189,7 +215,7 @@ fn list_dir_answers_the_tree_of_a_directory_as_untrusted_output() { output.text(), "/proj/\n - README.md\n - src/\n - lib.rs" ); - assert!(!output.is_trusted()); + assert!(output.is_trusted()); } #[test] @@ -228,7 +254,7 @@ fn list_dir_leaves_out_and_counts_a_name_that_holds_a_control_character() { } #[test] -fn grep_answers_the_matching_lines_of_a_tree_as_untrusted_output() { +fn grep_answers_the_matching_lines_of_a_tree_as_trusted_output() { let files = Files::new() .file( "/src/a.ts", @@ -243,7 +269,7 @@ fn grep_answers_the_matching_lines_of_a_tree_as_untrusted_output() { "/src/a.ts\n 3:const alpha = 1\n 4-let beta = 2\n --\n 9:const gamma = 3\n \ 10-export default gamma\n\n/src/b.ts\n 1:const first = 0" ); - assert!(!output.is_trusted()); + assert!(output.is_trusted()); } #[test] @@ -254,7 +280,7 @@ fn grep_of_a_missing_path_fails_with_the_does_not_exist_text() { } #[test] -fn grep_refuses_an_undeclared_key_by_name_while_the_stub_lets_it_through() { +fn grep_and_glob_refuse_an_undeclared_key_by_name() { let error = call("grep", &json!({ "pattern": "x", "context": 3 })) .expect_err("context is not a parameter"); assert_eq!(error.kind(), ToolErrorKind::InvalidArguments); @@ -264,7 +290,13 @@ fn grep_refuses_an_undeclared_key_by_name_while_the_stub_lets_it_through() { .starts_with("std_Grep: `context` is not a parameter of this tool."), "{error}" ); - let stub = call("glob", &json!({ "glob_pattern": "*.md", "extra": 1 })) - .expect("a stub ignores an undeclared key"); - assert_eq!(stub.text(), NOT_IMPLEMENTED.replace("", "Glob")); + let glob_error = call("glob", &json!({ "glob_pattern": "*.md", "extra": 1 })) + .expect_err("extra is not a parameter"); + assert_eq!(glob_error.kind(), ToolErrorKind::InvalidArguments); + assert!( + glob_error + .message() + .starts_with("std_Glob: `extra` is not a parameter of this tool."), + "{glob_error}" + ); }