diff --git a/Cargo.lock b/Cargo.lock index d0f2a8f..7821703 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -89,10 +89,17 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "pdfmd" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17859279b05a8e2b117a3ed599be6d1d5314a28029d9fdf959a14062efc4c0dd" + [[package]] name = "plugin-std" version = "0.1.0" dependencies = [ + "pdfmd", "regex", "runvil-plugin-sdk", "serde", diff --git a/Cargo.toml b/Cargo.toml index a16fca6..fc9498b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,8 @@ serde = { version = "1", features = ["derive"] } serde_json = { version = "1", features = ["float_roundtrip"] } # Grep compiles its pattern with Rust regex syntax. regex = "1" +# Read converts PDF files to Markdown without native libraries or a thread pool. +pdfmd = "0.4" # Parses this workspace's sources for the type-size check; `full` is the # feature that parses items. syn = { version = "3", features = ["full"] } diff --git a/crates/plugin-std/Cargo.toml b/crates/plugin-std/Cargo.toml index 1be3696..1f70a5d 100644 --- a/crates/plugin-std/Cargo.toml +++ b/crates/plugin-std/Cargo.toml @@ -21,6 +21,8 @@ serde.workspace = true serde_json.workspace = true # Grep compiles its pattern with Rust regex syntax. regex.workspace = true +# Read converts PDF files to Markdown. +pdfmd.workspace = true [dev-dependencies] # `testing`, the fake Host, and its `Files` tree, which lends the tools a diff --git a/crates/plugin-std/schemas/EDITS.md b/crates/plugin-std/schemas/EDITS.md index 65a819d..962f68b 100644 --- a/crates/plugin-std/schemas/EDITS.md +++ b/crates/plugin-std/schemas/EDITS.md @@ -7,10 +7,10 @@ Each file in this directory except `dir.json` is Cursor's definition of the tool - `Reads a file from the local filesystem.` became `Reads a file from the run's filesystem.`, because every read goes through the run's virtual filesystem, not the real one. - `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 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. +- Removed `Image Support` and the paragraph explaining how images are returned. This build reads text and PDFs (converted to Markdown via `pdfmd`), not images. +- 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 (with no prefix on lines in between) and `... N lines not shown ...` markers for omitted lines, 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 never truncates individual lines; instead, any request whose selected content exceeds `{char_cap}` characters is refused with the file's byte size, matching Cursor's actual behavior. +- 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; 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. - The `offset` text now says that 1 is the first line, that 0 reads as 1, and that a negative value counts back from the end with -1 as the last line. diff --git a/crates/plugin-std/schemas/read.json b/crates/plugin-std/schemas/read.json index dcde0ba..163cf68 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- 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.'", + "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; lines in between have no prefix. Treat the `LINE_NUMBER|` prefix as metadata, not part of the file. Omitted lines before or after a window appear as `... N lines not shown ...`.\n- A request whose selected content exceeds {char_cap} characters is refused with the file's byte size; pass `offset` and `limit` to read a smaller slice.\n- PDF files are converted to Markdown automatically (subject to the same character limits as other files).\n- Other than PDFs, 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/pack-tests.rs b/crates/plugin-std/src/pack-tests.rs index a3a975b..df3675b 100644 --- a/crates/plugin-std/src/pack-tests.rs +++ b/crates/plugin-std/src/pack-tests.rs @@ -129,7 +129,7 @@ fn model_caller_receives_errors_as_trusted_text_and_script_caller_receives_tool_ )) .expect("model caller gets plain text"); assert!(model.is_trusted()); - assert_eq!(model.text(), "File not found: /missing.md"); + assert_eq!(model.text(), "Error: File not found"); let script = block_on(dispatch( spec::all(), @@ -140,7 +140,7 @@ fn model_caller_receives_errors_as_trusted_text_and_script_caller_receives_tool_ )) .expect_err("script caller gets ToolError"); assert_eq!(script.kind(), ToolErrorKind::Other); - assert_eq!(script.message(), "File not found: /missing.md"); + assert_eq!(script.message(), "Error: File not found"); } #[test] diff --git a/crates/plugin-std/src/read.rs b/crates/plugin-std/src/read.rs index dd3270f..1d91c69 100644 --- a/crates/plugin-std/src/read.rs +++ b/crates/plugin-std/src/read.rs @@ -2,31 +2,44 @@ //! //! Read opens the path the call names through the call's [`Source`], so //! 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 trusted output. +//! file, a file over 16 MiB, blocked binary extensions, and binary data. +//! A window whose raw content exceeds [`CHAR_CAP`] characters is refused +//! with a message naming the file's byte size and asking for `offset` and +//! `limit`. File text is returned as trusted output. mod args; +mod pdf; mod render; mod window; #[cfg(test)] mod tests; -use runvil_plugin_sdk::{FileError, FileType, ToolError, ToolErrorKind, ToolOutput}; +use runvil_plugin_sdk::{FileError, FileErrorKind, FileType, ToolError, ToolErrorKind, ToolOutput}; use serde_json::Value; use crate::check::plural; use crate::refusal::{is_a_directory, neither_file_nor_directory, refusal}; use crate::source::Source; use crate::spec::Definition; -use crate::text::{MAX_FILE_BYTES, decode, sniff_binary, split_lines}; +use crate::text::{MAX_FILE_BYTES, decode, sniff_binary}; use self::args::Request; +use self::window::Window; -/// The most bytes of numbered lines one read returns: each line's prefix, -/// its text, and its newline count, and the notes and the trailer do not. -pub(crate) const BYTE_CAP: usize = 100_000; +/// The most raw characters of selected file content one read returns: +/// measured across the selected lines and their `\n` separators, before +/// line-number prefixes or omitted-line markers are added. +pub(crate) const CHAR_CAP: usize = 100_000; + +/// Lowercase file extensions Read refuses by type before reading bytes: +/// executables, shared libraries, raw binary blobs, archives, media, and +/// compiled bytecode. Formats such as `.wasm`, `.ttf`, `.o`, `.lib`, and +/// `.rlib` are left to [`sniff_binary`]. +const BLOCKED_BINARY_EXTENSIONS: &[&str] = &[ + "7z", "avi", "bin", "class", "dll", "dmg", "dylib", "exe", "flac", "gz", "iso", "jar", "mkv", + "mov", "mp3", "mp4", "pyc", "rar", "so", "tar", "wav", "zip", +]; /// Runs one `Read` call whose arguments already passed the shared schema /// check. @@ -41,12 +54,12 @@ pub(crate) async fn call( args: &Value, ) -> Result { let request = args::parse(definition, args)?; - read_file(source, &definition.wire_name, &request, BYTE_CAP).await + read_file(source, &definition.wire_name, &request, CHAR_CAP).await } -/// Reads the file `request` names, in the window it asks for, with at -/// most `cap` bytes of numbered lines. `tool` is the name the model -/// called the tool by. +/// Reads the file `request` names, in the window it asks for, refusing a +/// window whose raw character count exceeds `cap`. `tool` is the name the +/// model called the tool by. async fn read_file( source: &impl Source, tool: &str, @@ -55,33 +68,136 @@ async fn read_file( ) -> Result { let path = request.path; let message = |text: String| ToolError::new(ToolErrorKind::Other, text); - let bytes = load(source, tool, path).await.map_err(message)?; + let failed = |error: FileError| read_refusal(tool, path, &error); + + let stat = source.stat(path).await.map_err(failed).map_err(message)?; + check_read_type(path, stat.file_type).map_err(message)?; + if let Some(ext) = blocked_binary_extension(path) { + return Err(message(format!( + "Error: Cannot read binary files of type {ext}" + ))); + } + let bytes = source + .read_prefix(path, MAX_FILE_BYTES + 1) + .await + .map_err(failed) + .map_err(message)?; + if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > MAX_FILE_BYTES { + return Err(message(format!( + "Error: File is too large to read: {path} is over the limit of {MAX_FILE_BYTES} bytes." + ))); + } + if bytes.is_empty() { + return Ok(ToolOutput::trusted("File is empty.")); + } + if pdf::is_pdf_path(path) { + let markdown = pdf::extract(path, &bytes).map_err(message)?; + return render_text(path, &markdown, bytes.len(), &[], request, cap).map_err(message); + } if sniff_binary(&bytes) { return Err(message(format!( - "File content is binary data, not text: {path}" + "Error: File content is binary data, not text: {path}" ))); } let decoded = decode(&bytes); - let lines = split_lines(&decoded.text); + let notes = render::notes(decoded.utf16, decoded.invalid); + render_text(path, &decoded.text, bytes.len(), ¬es, request, cap).map_err(message) +} + +/// Splits `text` into lines, picks `request`'s window, enforces `cap` +/// against the raw character count, and renders the result. +fn render_text( + _path: &str, + text: &str, + file_bytes: usize, + notes: &[String], + request: &Request<'_>, + cap: usize, +) -> Result { + let lines = split_read_lines(text); if lines.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!( - "Offset {} is beyond the end of {path}, which has {}.", + return Err(format!( + "Error: Offset {} is beyond file length ({})", request.offset.unwrap_or_default(), plural(lines.len(), "line") - ))); + )); }; - let notes = render::notes(decoded.utf16, decoded.invalid); - Ok(ToolOutput::trusted(render::render( - &lines, &window, ¬es, cap, - ))) + if raw_window_chars(&lines, &window) > cap { + return Ok(ToolOutput::trusted(format!( + "Requested content exceeds maximum allowed characters ({cap} characters). \ + The file is {file_bytes} bytes.\n\ + Please use offset and limit parameters to read specific portions of the file, \ + or use the 'grep' tool to search for specific content." + ))); + } + Ok(ToolOutput::trusted(render::render(&lines, &window, notes))) +} + +/// Splits `text` into lines on `\n`, keeping a trailing empty line when +/// `text` ends with `\n`, and stripping one trailing `\r` from each line. +/// An empty string has no lines. +fn split_read_lines(text: &str) -> Vec<&str> { + if text.is_empty() { + return Vec::new(); + } + text.split('\n') + .map(|line| line.strip_suffix('\r').unwrap_or(line)) + .collect() +} + +/// The number of raw characters in `window` over `lines`, counting each +/// line's Unicode scalar values and the `\n` separators between them. +fn raw_window_chars(lines: &[&str], window: &Window) -> usize { + let slice = lines + .get((window.first - 1)..window.last) + .unwrap_or_default(); + let content: usize = slice.iter().map(|line| line.chars().count()).sum(); + content + slice.len().saturating_sub(1) +} + +/// The lowercased extension of `path` when it is in +/// [`BLOCKED_BINARY_EXTENSIONS`], or `None` otherwise. +fn blocked_binary_extension(path: &str) -> Option { + let file_name = path.rsplit(['/', '\\']).next().unwrap_or(path); + let (stem, ext) = file_name.rsplit_once('.')?; + if stem.is_empty() || ext.is_empty() { + return None; + } + let lower = ext.to_ascii_lowercase(); + BLOCKED_BINARY_EXTENSIONS + .binary_search(&lower.as_str()) + .ok() + .map(|_| lower) +} + +/// The Read-specific sentence for `error`: Cursor's exact text for +/// missing files and directories, the Host's policy text verbatim for +/// denials, and [`refusal`] for everything else. +fn read_refusal(tool: &str, path: &str, error: &FileError) -> String { + match error.kind() { + FileErrorKind::NotFound => "Error: File not found".to_owned(), + FileErrorKind::IsADirectory => format!("Error: {}", is_a_directory(path)), + FileErrorKind::Denied => error.text().to_owned(), + _ => refusal(tool, path, error), + } +} + +/// Decides from the kind of node at `path` whether Read reads its bytes. +fn check_read_type(path: &str, file_type: FileType) -> Result<(), String> { + match file_type { + FileType::File | FileType::Symlink => Ok(()), + FileType::Directory => Err(format!("Error: {}", is_a_directory(path))), + // A pipe, a socket, or a device, and any kind added later: none + // of them holds text, and a read of one can block for good. + _ => Err(format!("Error: {}", neither_file_nor_directory(path))), + } } -/// The bytes of the file at `path`, for a tool that works on a file's -/// text: Read, and StrReplace, which edits what Read shows. `tool` is the -/// name the model called the tool by. +/// The bytes of the file at `path`, for `StrReplace`, which edits what +/// `Read` shows. `tool` is the name the model called the tool by. /// /// The stat comes first, so a directory and a special file are refused /// and never opened. The read stops one byte past the ceiling, so a file diff --git a/crates/plugin-std/src/read/args.rs b/crates/plugin-std/src/read/args.rs index 19f3ec7..ab3632d 100644 --- a/crates/plugin-std/src/read/args.rs +++ b/crates/plugin-std/src/read/args.rs @@ -1,10 +1,10 @@ //! Read's arguments: what the call asks for, and what is refused before //! any file is touched. -use runvil_plugin_sdk::ToolError; +use runvil_plugin_sdk::{ToolError, ToolErrorKind}; use serde_json::Value; -use crate::check::{make_invalid_arguments_error, refuse_blank, refuse_unknown}; +use crate::check::{make_invalid_arguments_error, refuse_unknown}; use crate::spec::Definition; /// What a call asks Read for. @@ -34,13 +34,18 @@ pub(super) fn parse<'a>( let tool = definition.wire_name.as_str(); refuse_unknown(tool, &definition.parameters, args)?; let path = args.get("path").and_then(Value::as_str).unwrap_or_default(); - refuse_blank(tool, "path", path)?; + if path.trim().is_empty() { + return Err(ToolError::new( + ToolErrorKind::InvalidArguments, + "Error: path is empty or only whitespace", + )); + } let offset = integer(tool, "offset", args)?.map(|(offset, _)| offset); let limit = match integer(tool, "limit", args)? { - Some((limit, given)) if limit < 1 => { - return Err(make_invalid_arguments_error( - tool, - format!("`limit` must be at least 1, and the call passed {given}"), + Some((limit, _)) if limit < 1 => { + return Err(ToolError::new( + ToolErrorKind::InvalidArguments, + "Error: Invalid arguments:\nlimit: Limit must be >= 1.", )); } Some((limit, _)) => Some(usize::try_from(limit).unwrap_or(usize::MAX)), diff --git a/crates/plugin-std/src/read/pdf.rs b/crates/plugin-std/src/read/pdf.rs new file mode 100644 index 0000000..4599216 --- /dev/null +++ b/crates/plugin-std/src/read/pdf.rs @@ -0,0 +1,32 @@ +//! PDF-to-Markdown conversion for the `Read` tool. +//! +//! Uses `pdfmd` (pure Rust, zero dependencies, single-threaded) so a PDF +//! file is converted in memory without spawning a global thread pool inside +//! the Plugin dynamic library. + +use pdfmd::{ConvertOptions, convert_pdf_to_markdown}; + +/// Whether `path` names a PDF file by its extension (case-insensitive). +pub(super) fn is_pdf_path(path: &str) -> bool { + let file_name = path.rsplit(['/', '\\']).next().unwrap_or(path); + let Some((stem, ext)) = file_name.rsplit_once('.') else { + return false; + }; + !stem.is_empty() && ext.eq_ignore_ascii_case("pdf") +} + +/// Converts the PDF `bytes` at `path` into Markdown text. +/// +/// # Errors +/// Returns a model-readable error sentence when the PDF fails to parse, is +/// encrypted, or yields no extractable text (such as a scanned document). +pub(super) fn extract(path: &str, bytes: &[u8]) -> Result { + let result = convert_pdf_to_markdown(bytes, &ConvertOptions::default()) + .map_err(|error| format!("Error: Failed to read PDF {path}: {error}"))?; + if result.markdown.trim().is_empty() { + return Err(format!( + "Error: PDF contains no extractable text (it may be scanned or image-only): {path}" + )); + } + Ok(result.markdown) +} diff --git a/crates/plugin-std/src/read/render.rs b/crates/plugin-std/src/read/render.rs index a8678f2..a0e991d 100644 --- a/crates/plugin-std/src/read/render.rs +++ b/crates/plugin-std/src/read/render.rs @@ -1,111 +1,68 @@ //! The render: turns a window of lines into the text Read answers with. //! -//! 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. +//! Every 10th line 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 multiples of 10 print their text +//! with no prefix. When lines before or after the window are omitted, a +//! `... N line(s) not shown ...` marker sits above or below the lines. + +use std::fmt::Write as _; use crate::check::plural; -use crate::text::clip_to_boundary; use super::window::Window; -/// 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) { +/// The numbered prefix of line `number`: present on every 10th line and +/// empty otherwise. +fn line_prefix(number: usize) -> String { + if number.is_multiple_of(10) { format!("{number:>6}|") } else { String::new() } } -/// The text of the `window` over `lines`, with `notes` and a trailer when -/// the read stops early. -/// -/// 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 -/// cut to fit and printed alone, and the trailer says so: this is the only -/// cut inside a line. A read that reaches the last line prints no trailer. +/// The text of `window` over `lines`, with `... N line(s) not shown ...` +/// markers when lines before or after the window are omitted, and any +/// decoding `notes` appended at the end. /// /// `window` lies inside `lines`. -pub(super) fn render(lines: &[&str], window: &Window, notes: &[String], cap: usize) -> String { +pub(super) fn render(lines: &[&str], window: &Window, notes: &[String]) -> String { let total = lines.len(); let mut body = String::new(); - let mut used = 0usize; - let mut shown = 0usize; + if window.first > 1 { + let _ = writeln!( + body, + "... {} not shown ...", + plural(window.first - 1, "line") + ); + } for number in window.first..=window.last { let Some(text) = lines.get(number - 1) else { break; }; - let prefix = line_prefix(number, window.first); - let cost = prefix.len() + text.len() + 1; - if used + cost > cap { - break; + if number > window.first { + body.push('\n'); } - body.push_str(&prefix); + body.push_str(&line_prefix(number)); body.push_str(text); - body.push('\n'); - used += cost; - shown = number; } - let trailer = if shown == 0 { - Some(cut_first_line(lines, window.first, cap, &mut body)) - } else if shown < window.last { - Some(format!( - "[Showing lines {first}-{shown} of {total} ({cap}-byte limit). \ - Use offset={next} to continue.]", - first = window.first, - next = shown + 1, - )) - } else if window.last < total { - Some(format!( - "[Showing lines {first}-{last} of {total}. Use offset={next} to continue.]", - first = window.first, - last = window.last, - next = window.last + 1, - )) - } else { - None - }; - let tail: Vec<&str> = notes - .iter() - .map(String::as_str) - .chain(trailer.as_deref()) - .collect(); - body.push_str(&tail.join("\n")); + if window.last < total { + let _ = write!( + body, + "\n... {} not shown ...", + plural(total - window.last, "line") + ); + } + if !notes.is_empty() { + if !body.is_empty() && !body.ends_with('\n') { + body.push('\n'); + } + body.push_str(¬es.join("\n")); + } body } -/// Prints the first line of the window, number `number`, cut to fit -/// `cap` bytes, into `body`, and returns the trailer that says it was -/// 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 = line_prefix(number, number); - let allowance = cap.saturating_sub(prefix.len() + 1); - let kept = clip_to_boundary(text, 0, allowance); - body.push_str(&prefix); - body.push_str(kept); - body.push('\n'); - let next = if number < lines.len() { - format!(" Use offset={} to continue.", number + 1) - } else { - String::new() - }; - format!( - "[Line {number} is {bytes} bytes and is cut after {cut} bytes. \ - No parameter reads the rest of a line.{next}]", - bytes = text.len(), - cut = kept.len(), - ) -} - /// The notes for a file that was decoded, in the order they print: the /// UTF-16 note first, then the note that counts replaced bytes. pub(super) fn notes(utf16: Option<&str>, invalid: usize) -> Vec { diff --git a/crates/plugin-std/src/read/tests.rs b/crates/plugin-std/src/read/tests.rs index 7a15b0a..8f2eba8 100644 --- a/crates/plugin-std/src/read/tests.rs +++ b/crates/plugin-std/src/read/tests.rs @@ -5,6 +5,7 @@ mod arguments; mod failures; mod paging; +mod pdf; mod render; mod window; diff --git a/crates/plugin-std/src/read/tests/arguments.rs b/crates/plugin-std/src/read/tests/arguments.rs index ca2b246..32f83d9 100644 --- a/crates/plugin-std/src/read/tests/arguments.rs +++ b/crates/plugin-std/src/read/tests/arguments.rs @@ -17,13 +17,13 @@ fn refused(args: &Value) -> (ToolErrorKind, String) { } #[test] -fn a_limit_below_one_is_refused_with_the_value_as_given() { - for (limit, passed) in [(json!(0), "0"), (json!(-3), "-3")] { +fn a_limit_below_one_is_refused_with_cursors_message() { + for limit in [json!(0), json!(-3)] { let (kind, message) = refused(&json!({ "path": "/a.md", "limit": limit })); assert_eq!(kind, ToolErrorKind::InvalidArguments); assert_eq!( message, - format!("std_Read: `limit` must be at least 1, and the call passed {passed}") + "Error: Invalid arguments:\nlimit: Limit must be >= 1." ); } } @@ -121,12 +121,12 @@ fn a_whole_number_float_past_the_64_bit_range_is_refused() { } #[test] -fn a_float_limit_below_one_is_refused_with_the_value_as_given() { +fn a_float_limit_below_one_is_refused_with_cursors_message() { let (kind, message) = refused(&json!({ "path": "/a.md", "limit": 0.0 })); assert_eq!(kind, ToolErrorKind::InvalidArguments); assert_eq!( message, - "std_Read: `limit` must be at least 1, and the call passed 0.0" + "Error: Invalid arguments:\nlimit: Limit must be >= 1." ); } @@ -143,15 +143,10 @@ fn an_undeclared_key_is_refused_naming_it_and_the_parameters() { #[test] fn a_blank_path_is_refused_before_any_io() { - for (blank, shown) in [("", ""), (" ", " ")] { + for blank in ["", " "] { let (kind, message) = refused(&json!({ "path": blank })); assert_eq!(kind, ToolErrorKind::InvalidArguments); - assert_eq!( - message, - format!( - "std_Read: `path` is empty or only whitespace, and the call passed \"{shown}\"" - ) - ); + assert_eq!(message, "Error: path is empty or only whitespace"); } } @@ -174,24 +169,24 @@ fn the_unknown_key_is_refused_before_the_blank_path() { #[test] fn the_blank_path_is_refused_before_the_limit() { let (_, message) = refused(&json!({ "path": "", "limit": 0 })); - assert!( - message.contains("`path` is empty or only whitespace"), - "{message}" - ); + assert_eq!(message, "Error: path is empty or only whitespace"); } #[test] fn the_limit_is_refused_before_the_file_is_looked_up() { let (kind, message) = refused(&json!({ "path": "/missing.md", "limit": 0 })); assert_eq!(kind, ToolErrorKind::InvalidArguments); - assert!(message.contains("`limit` must be at least 1"), "{message}"); + assert_eq!( + message, + "Error: Invalid arguments:\nlimit: Limit must be >= 1." + ); } #[test] fn a_missing_file_is_a_plain_message_and_not_an_invalid_arguments_error() { let (kind, message) = refused(&json!({ "path": "/missing.md" })); assert_ne!(kind, ToolErrorKind::InvalidArguments); - assert_eq!(message, "File not found: /missing.md"); + assert_eq!(message, "Error: File not found"); } #[test] diff --git a/crates/plugin-std/src/read/tests/failures.rs b/crates/plugin-std/src/read/tests/failures.rs index c51e708..296865d 100644 --- a/crates/plugin-std/src/read/tests/failures.rs +++ b/crates/plugin-std/src/read/tests/failures.rs @@ -1,5 +1,6 @@ //! What Read says when it cannot read, and how it treats the files it can: -//! encodings, binary data, empty files, and the size ceiling. +//! encodings, binary data, blocked binary extensions, empty files, and the +//! size ceiling. use runvil_plugin_sdk::testing::Files; use runvil_plugin_sdk::{FileError, FileErrorKind, FileType}; @@ -7,32 +8,32 @@ use serde_json::json; use super::{failure_of, read, read_capped, seeded, text_of}; use crate::fake::{FakeSource, Node}; -use crate::read::{BYTE_CAP, check_type}; +use crate::read::{CHAR_CAP, check_read_type, check_type}; #[test] -fn a_missing_path_fails_with_the_not_found_text() { +fn a_missing_path_fails_with_cursors_not_found_text() { let files = Files::new(); assert_eq!( failure_of(read(&files, &json!({ "path": "/nope.md" }))), - "File not found: /nope.md" + "Error: File not found" ); } #[test] -fn a_relative_path_is_echoed_as_written() { +fn a_missing_relative_path_fails_with_cursors_not_found_text() { let files = Files::new(); assert_eq!( failure_of(read(&files, &json!({ "path": "notes/a.md" }))), - "File not found: notes/a.md" + "Error: File not found" ); } #[test] -fn a_directory_fails_with_the_directory_text() { +fn a_directory_fails_with_cursors_directory_text() { let files = seeded("/dir/a.md", b"x\n"); assert_eq!( failure_of(read(&files, &json!({ "path": "/dir" }))), - "Path is a directory, not a file: /dir" + "Error: Path is a directory, not a file: /dir" ); } @@ -44,11 +45,21 @@ fn the_file_type_decision_covers_every_kind_of_node() { check_type("/p", FileType::Directory), Err("Path is a directory, not a file: /p".to_owned()) ); - // A pipe, a socket, and a device all reach the Plugin as `Other`. assert_eq!( check_type("/p", FileType::Other), Err("Path is neither a file nor a directory: /p".to_owned()) ); + assert_eq!(check_read_type("/p", FileType::File), Ok(())); + assert_eq!(check_read_type("/p", FileType::Symlink), Ok(())); + assert_eq!( + check_read_type("/p", FileType::Directory), + Err("Error: Path is a directory, not a file: /p".to_owned()) + ); + // A pipe, a socket, and a device all reach the Plugin as `Other`. + assert_eq!( + check_read_type("/p", FileType::Other), + Err("Error: Path is neither a file nor a directory: /p".to_owned()) + ); } #[test] @@ -106,7 +117,7 @@ fn a_link_is_read_through_and_a_link_to_a_directory_is_a_directory() { ); assert_eq!( failure_of(read(&source, &json!({ "path": "/dirlink" }))), - "Path is a directory, not a file: /dirlink" + "Error: Path is a directory, not a file: /dirlink" ); } @@ -117,50 +128,76 @@ fn a_pipe_is_refused_by_its_stat_and_never_read() { let source = FakeSource::default().with("/pipe", Node::Pipe); assert_eq!( failure_of(read(&source, &json!({ "path": "/pipe" }))), - "Path is neither a file nor a directory: /pipe" + "Error: Path is neither a file nor a directory: /pipe" ); } #[test] -fn a_binary_file_is_refused_by_its_content_not_its_name() { - let files = seeded("/data.md", &[0x00, 0x01, 0x02, 0x03, 0xFF]); +fn blocked_binary_extensions_are_refused_by_type_after_stat() { + let files = seeded("/app.EXE", b"plain text\n") + .file("/lib.dll", b"\x00\x01") + .file("/blob.bin", b"plain text\n"); + assert_eq!( + failure_of(read(&files, &json!({ "path": "/app.EXE" }))), + "Error: Cannot read binary files of type exe" + ); + assert_eq!( + failure_of(read(&files, &json!({ "path": "/lib.dll" }))), + "Error: Cannot read binary files of type dll" + ); assert_eq!( - failure_of(read(&files, &json!({ "path": "/data.md" }))), - "File content is binary data, not text: /data.md" + failure_of(read(&files, &json!({ "path": "/blob.bin" }))), + "Error: Cannot read binary files of type bin" ); - let text = seeded("/data.bin", b"plain text\n"); + // Missing and denied blocked-extension paths still report not found / denied. assert_eq!( - text_of(read(&text, &json!({ "path": "/data.bin" }))), - "plain text\n" + failure_of(read(&files, &json!({ "path": "/missing.dll" }))), + "Error: File not found" ); } +#[test] +fn other_binary_files_are_refused_by_content_sniff() { + let files = seeded("/data.md", &[0x00, 0x01, 0x02, 0x03, 0xFF]) + .file("/mod.wasm", [0x00, b'a', b's', b'm']) + .file("/lib.rlib", [0x00, 0x01]) + .file("/obj.o", [0x7F, b'E', b'L', b'F', 0x00]); + for path in ["/data.md", "/mod.wasm", "/lib.rlib", "/obj.o"] { + assert_eq!( + failure_of(read(&files, &json!({ "path": path }))), + format!("Error: File content is binary data, not text: {path}") + ); + } +} + #[test] fn a_file_one_byte_over_the_ceiling_is_refused_and_never_truncated() { let files = seeded("/big.txt", &vec![b'a'; 16_777_217]); assert_eq!( failure_of(read(&files, &json!({ "path": "/big.txt" }))), - "File is too large to read: /big.txt is over the limit of 16777216 bytes." + "Error: File is too large to read: /big.txt is over the limit of 16777216 bytes." ); } #[test] -fn a_file_exactly_at_the_ceiling_is_read() { +fn a_file_exactly_at_the_ceiling_is_checked_against_the_char_cap() { 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("aaaa"), "the line is read"); - assert!( - text.contains("[Line 1 is 16777216 bytes and is cut after 99999 bytes."), - "{}", - &text[text.len() - 150..] + assert_eq!( + text, + "Requested content exceeds maximum allowed characters (100000 characters). \ + The file is 16777216 bytes.\n\ + Please use offset and limit parameters to read specific portions of the file, \ + or use the 'grep' tool to search for specific content." ); } #[test] fn the_ceiling_is_checked_before_the_binary_sniff() { - let files = seeded("/big.bin", &vec![0u8; 16_777_217]); + let files = seeded("/big.dat", &vec![0u8; 16_777_217]); assert!( - failure_of(read(&files, &json!({ "path": "/big.bin" }))).starts_with("File is too large") + failure_of(read(&files, &json!({ "path": "/big.dat" }))) + .starts_with("Error: File is too large") ); } @@ -223,7 +260,7 @@ fn a_utf16_file_without_a_mark_is_binary() { let files = seeded("/bare16.txt", &[b'h', 0, b'i', 0, b'\n', 0]); assert_eq!( failure_of(read(&files, &json!({ "path": "/bare16.txt" }))), - "File content is binary data, not text: /bare16.txt" + "Error: File content is binary data, not text: /bare16.txt" ); } @@ -248,13 +285,13 @@ fn a_file_that_ends_mid_sequence_counts_one_replacement() { } #[test] -fn the_replacement_note_comes_before_the_trailer() { +fn the_replacement_note_comes_after_the_bottom_marker() { let files = seeded("/two.txt", &[0x61, 0xFF, 0x0A, 0x62, 0x0A]); assert_eq!( text_of(read(&files, &json!({ "path": "/two.txt", "limit": 1 }))), "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.]" + ... 2 lines not shown ...\n\ + [Note: 1 invalid UTF-8 sequence in this file were shown as U+FFFD.]" ); } @@ -273,11 +310,11 @@ fn every_successful_read_is_trusted_output() { let output = read(&files, &args).expect("the read succeeds"); assert!(output.is_trusted(), "{args}"); } - let capped = read_capped(&files, "/a.md", None, None, 10).expect("a cut read succeeds"); + let capped = read_capped(&files, "/a.md", None, None, 2).expect("an oversized read succeeds"); assert!(capped.is_trusted()); } #[test] -fn the_byte_cap_is_one_hundred_thousand_bytes() { - assert_eq!(BYTE_CAP, 100_000); +fn the_char_cap_is_one_hundred_thousand_characters() { + assert_eq!(CHAR_CAP, 100_000); } diff --git a/crates/plugin-std/src/read/tests/paging.rs b/crates/plugin-std/src/read/tests/paging.rs index 48c9949..cc95bec 100644 --- a/crates/plugin-std/src/read/tests/paging.rs +++ b/crates/plugin-std/src/read/tests/paging.rs @@ -1,101 +1,85 @@ -//! Paging: following each `Use offset=N` trailer until the read ends must -//! rebuild the file exactly, whatever the cap and the limit. +//! Paging: stepping through a file with `offset` and `limit` under the raw +//! character cap rebuilds the file exactly, and oversized slices are refused. use super::{numbered_file, read_capped, seeded, text_of}; -use crate::read::BYTE_CAP; +use crate::read::CHAR_CAP; -/// Reads `/file.txt` page by page under `cap` and `limit`, following each -/// trailer's offset, and returns the text of every line it printed. -fn rebuild(file: &str, total: usize, cap: usize, limit: Option) -> Vec { +/// Reads `/file.txt` in fixed `limit`-line slices and returns every line +/// stripped of multiple-of-10 prefixes and omitted-line markers. +fn rebuild_with_limit(file: &str, total: usize, cap: usize, limit: usize) -> Vec { let files = seeded("/file.txt", file.as_bytes()); - let mut rebuilt: Vec = Vec::new(); - let mut offset: Option = None; - let mut pages = 0usize; - loop { - pages += 1; - assert!(pages <= total + 1, "paging does not advance"); - let text = text_of(read_capped(&files, "/file.txt", offset, limit, cap)); + let mut rebuilt = Vec::new(); + let mut offset = 1i64; + while rebuilt.len() < total { + let text = text_of(read_capped( + &files, + "/file.txt", + Some(offset), + Some(limit), + cap, + )); let mut shown: Vec<&str> = text.split('\n').collect(); - if shown.last() == Some(&"") { - shown.pop(); + if offset > 1 { + let top = shown.remove(0); + assert!( + top.starts_with("... ") && top.ends_with(" not shown ..."), + "{top}" + ); } - let trailer = shown - .last() - .copied() - .filter(|line| line.starts_with("[Showing lines ")); - if trailer.is_some() { - shown.pop(); + let expected_end = (rebuilt.len() + limit).min(total); + if expected_end < total { + let bottom = shown.pop().expect("bottom marker exists"); + assert!( + bottom.starts_with("... ") && bottom.ends_with(" not shown ..."), + "{bottom}" + ); } - assert!(!shown.is_empty(), "a page is never empty: {text}"); - let page_start = rebuilt.len() + 1; for line in shown { let number = rebuilt.len() + 1; - let content = if number.is_multiple_of(10) || (page_start > 1 && number == page_start) { + let content = if number.is_multiple_of(10) { let expected_prefix = format!("{number:>6}|"); line.strip_prefix(&expected_prefix) - .unwrap_or_else(|| panic!("page {pages} line {number}: {line}")) + .unwrap_or_else(|| panic!("line {number}: {line}")) } else { line }; rebuilt.push(content.to_owned()); } - let Some(trailer) = trailer else { - break; - }; - let next: i64 = trailer - .split("offset=") - .nth(1) - .and_then(|rest| rest.split(' ').next()) - .and_then(|digits| digits.parse().ok()) - .unwrap_or_else(|| panic!("the trailer names an offset: {trailer}")); - assert_eq!( - usize::try_from(next).expect("the offset is positive"), - rebuilt.len() + 1, - "the trailer continues where the page stopped" - ); - offset = Some(next); + offset = i64::try_from(rebuilt.len() + 1).expect("offset fits in i64"); } - assert_eq!(rebuilt.len(), total, "the pages cover the file"); + assert_eq!(rebuilt.len(), total); rebuilt } #[test] -fn following_the_trailers_rebuilds_the_file_under_every_cap_and_limit() { - for total in [1, 2, 5, 37, 2_000, 2_001] { +fn stepping_with_offset_and_limit_rebuilds_the_file_exactly() { + for count in [1, 2, 10, 37] { for final_newline in [true, false] { - let file = numbered_file(total, final_newline); - let expected: Vec = (1..=total).map(|n| format!("line {n}")).collect(); - for cap in [BYTE_CAP, 300, 90] { - for limit in [None, Some(50), Some(7)] { - let rebuilt = rebuild(&file, total, cap, limit); - assert_eq!( - rebuilt, expected, - "{total} lines, final newline {final_newline}, cap {cap}, limit {limit:?}" - ); - } + let file = numbered_file(count, final_newline); + let mut expected: Vec = (1..=count).map(|n| format!("line {n}")).collect(); + if final_newline { + expected.push(String::new()); + } + for limit in [1, 5, 13, 50] { + let rebuilt = rebuild_with_limit(&file, expected.len(), CHAR_CAP, limit); + assert_eq!( + rebuilt, expected, + "{count} lines, final newline {final_newline}, limit {limit}" + ); } } } } #[test] -fn a_small_cap_makes_more_pages_than_a_large_one() { - let file = numbered_file(37, true); - let pages = |cap: usize| { - let files = seeded("/file.txt", file.as_bytes()); - let mut count = 0; - let mut offset: Option = None; - loop { - count += 1; - let text = text_of(read_capped(&files, "/file.txt", offset, None, cap)); - let Some(rest) = text.rsplit_once("offset=") else { - return count; - }; - let digits = rest.1.trim_end_matches(" to continue.]"); - offset = Some(digits.parse().expect("the offset is a number")); - } - }; - assert_eq!(pages(BYTE_CAP), 1); - assert!(pages(90) > pages(300)); - assert!(pages(300) > 1); +fn an_oversized_window_is_refused_while_a_smaller_slice_succeeds() { + let file = numbered_file(20, true); + let files = seeded("/file.txt", file.as_bytes()); + let refused = text_of(read_capped(&files, "/file.txt", None, None, 50)); + assert!( + refused + .starts_with("Requested content exceeds maximum allowed characters (50 characters).") + ); + let slice = text_of(read_capped(&files, "/file.txt", Some(1), Some(3), 50)); + assert_eq!(slice, "line 1\nline 2\nline 3\n... 18 lines not shown ..."); } diff --git a/crates/plugin-std/src/read/tests/pdf.rs b/crates/plugin-std/src/read/tests/pdf.rs new file mode 100644 index 0000000..072c454 --- /dev/null +++ b/crates/plugin-std/src/read/tests/pdf.rs @@ -0,0 +1,134 @@ +//! PDF-to-Markdown conversion through Read: valid multi-page documents, +//! offset/limit paging, the character cap, empty PDFs, scanned PDFs, and +//! corrupt PDF bytes. + +use std::fmt::Write as _; + +use serde_json::json; + +use super::{failure_of, read, read_capped, seeded, text_of}; + +/// Builds a minimal valid PDF 1.4 document with one page per entry in +/// `pages`, each page drawing its lines with Helvetica at 12pt. +fn minimal_pdf(pages: &[&[&str]]) -> Vec { + let mut objects: Vec = Vec::new(); + // Object 1: Catalog + objects.push("<< /Type /Catalog /Pages 2 0 R >>".to_owned()); + // Object 2: Pages (kids start at object 4, 2 objects per page) + let kids: Vec = (0..pages.len()) + .map(|index| format!("{} 0 R", 4 + index * 2)) + .collect(); + objects.push(format!( + "<< /Type /Pages /Kids [{}] /Count {} >>", + kids.join(" "), + pages.len() + )); + // Object 3: Font + objects.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_owned()); + + for (index, lines) in pages.iter().enumerate() { + let content_id = 5 + index * 2; + objects.push(format!( + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] \ + /Resources << /Font << /F1 3 0 R >> >> /Contents {content_id} 0 R >>" + )); + let mut stream = String::new(); + for (line_index, line) in lines.iter().enumerate() { + let y = 720usize.saturating_sub(line_index * 16); + let escaped = line + .replace('\\', "\\\\") + .replace('(', "\\(") + .replace(')', "\\)"); + let _ = writeln!(stream, "BT /F1 12 Tf 72 {y} Td ({escaped}) Tj ET"); + } + objects.push(format!( + "<< /Length {} >>\nstream\n{stream}endstream", + stream.len() + )); + } + + let mut out = Vec::from(&b"%PDF-1.4\n"[..]); + let mut offsets = Vec::with_capacity(objects.len()); + for (index, body) in objects.iter().enumerate() { + offsets.push(out.len()); + let obj = format!("{} 0 obj\n{body}\nendobj\n", index + 1); + out.extend_from_slice(obj.as_bytes()); + } + let xref_offset = out.len(); + let mut xref = format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1); + for offset in offsets { + let _ = writeln!(xref, "{offset:010} 00000 n "); + } + let _ = write!( + xref, + "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_offset}\n%%EOF\n", + objects.len() + 1 + ); + out.extend_from_slice(xref.as_bytes()); + out +} + +#[test] +fn a_pdf_is_converted_to_markdown_and_supports_offset_and_limit() { + let bytes = minimal_pdf(&[ + &["First page line one", "First page line two"], + &["Second page line one"], + ]); + let files = seeded("/report.PDF", &bytes); + let full = text_of(read(&files, &json!({ "path": "/report.PDF" }))); + assert!(full.contains("First page line one"), "{full}"); + assert!(full.contains("Second page line one"), "{full}"); + + let slice = text_of(read( + &files, + &json!({ "path": "/report.PDF", "offset": 1, "limit": 1 }), + )); + assert!(slice.contains("First page line one"), "{slice}"); + assert!(slice.contains("not shown ..."), "{slice}"); +} + +#[test] +fn an_oversized_pdf_window_is_refused_with_the_pdf_byte_size() { + let bytes = minimal_pdf(&[&["Hello world from a PDF document"]]); + let files = seeded("/doc.pdf", &bytes); + let text = text_of(read_capped(&files, "/doc.pdf", None, None, 10)); + assert_eq!( + text, + format!( + "Requested content exceeds maximum allowed characters (10 characters). \ + The file is {} bytes.\n\ + Please use offset and limit parameters to read specific portions of the file, \ + or use the 'grep' tool to search for specific content.", + bytes.len() + ) + ); +} + +#[test] +fn a_zero_byte_pdf_answers_file_is_empty() { + let files = seeded("/empty.pdf", b""); + assert_eq!( + text_of(read(&files, &json!({ "path": "/empty.pdf" }))), + "File is empty." + ); +} + +#[test] +fn a_pdf_with_no_text_layer_fails_with_a_clear_error() { + let bytes = minimal_pdf(&[&[]]); + let files = seeded("/scanned.pdf", &bytes); + assert_eq!( + failure_of(read(&files, &json!({ "path": "/scanned.pdf" }))), + "Error: PDF contains no extractable text (it may be scanned or image-only): /scanned.pdf" + ); +} + +#[test] +fn a_corrupt_pdf_fails_with_a_parse_error() { + let files = seeded("/broken.pdf", b"not a real pdf at all"); + let message = failure_of(read(&files, &json!({ "path": "/broken.pdf" }))); + assert!( + message.starts_with("Error: Failed to read PDF /broken.pdf: "), + "{message}" + ); +} diff --git a/crates/plugin-std/src/read/tests/render.rs b/crates/plugin-std/src/read/tests/render.rs index 9652477..e33fbac 100644 --- a/crates/plugin-std/src/read/tests/render.rs +++ b/crates/plugin-std/src/read/tests/render.rs @@ -1,13 +1,12 @@ -//! 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. +//! The render: sparse multiple-of-10 line numbers, omitted-line markers, +//! the 100,000 raw-character cap, and decoding notes. use super::{read_capped, seeded, text_of}; -use crate::read::BYTE_CAP; +use crate::read::CHAR_CAP; use crate::read::render::{notes, render}; use crate::read::window::Window; -/// The three lines most render tests print. Each costs 4 bytes from line 1: -/// three bytes of text and a newline. +/// The three lines most render tests print. const LINES: [&str; 3] = ["aaa", "bbb", "ccc"]; /// The window over every line of [`LINES`]. @@ -17,106 +16,41 @@ const ALL: Window = Window { first: 1, last: 3 }; 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); + let text = render(&refs, &Window { first: 1, last: 12 }, &[]); assert_eq!( text, - "l1\nl2\nl3\nl4\nl5\nl6\nl7\nl8\nl9\n 10|l10\nl11\nl12\n" + "l1\nl2\nl3\nl4\nl5\nl6\nl7\nl8\nl9\n 10|l10\nl11\nl12" ); } #[test] -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\nccc\n"); +fn a_window_in_the_middle_has_no_start_anchor_unless_multiple_of_ten() { + let text = render(&LINES, &Window { first: 2, last: 3 }, &[]); + assert_eq!(text, "... 1 line not shown ...\nbbb\nccc"); } #[test] -fn a_window_that_stops_early_ends_with_the_limit_trailer() { - let text = render(&LINES, &Window { first: 2, last: 2 }, &[], BYTE_CAP); +fn a_window_that_stops_early_prints_both_top_and_bottom_markers() { + let text = render(&LINES, &Window { first: 2, last: 2 }, &[]); assert_eq!( text, - " 2|bbb\n[Showing lines 2-2 of 3. Use offset=3 to continue.]" + "... 1 line not shown ...\nbbb\n... 1 line not shown ..." ); } #[test] -fn lines_that_exactly_fill_the_cap_all_print_and_no_trailer_follows() { - 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, &[], 11); - assert_eq!( - text, - "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 [(4, 1), (7, 1), (8, 2), (11, 2), (12, 3)] { - let text = render(&LINES, &ALL, &[], cap); - 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 }, &[], 4); - assert_eq!( - text, - "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, &[], 3); - assert_eq!( - text, - "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.]" - ); -} - -#[test] -fn a_cut_first_line_on_the_last_line_of_the_file_offers_no_next_offset() { - let text = render(&LINES, &Window { first: 3, last: 3 }, &[], 10); - assert_eq!( - text, - " 3|cc\n[Line 3 is 3 bytes and is cut after 2 bytes. \ - No parameter reads the rest of a line.]" - ); -} - -#[test] -fn a_cap_below_the_prefix_keeps_no_text_and_does_not_panic() { - let text = render(&LINES, &Window { first: 2, last: 3 }, &[], 7); - assert_eq!( - text, - " 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.]" - ); -} - -#[test] -fn notes_come_after_the_lines_and_before_the_trailer_each_on_its_own_line() { +fn notes_come_after_the_lines_and_markers_without_double_blank_lines() { let note_lines = ["[Note: one]".to_owned(), "[Note: two]".to_owned()]; - let with_trailer = render(&LINES, &Window { first: 1, last: 1 }, ¬e_lines, BYTE_CAP); + let with_marker = render(&LINES, &Window { first: 1, last: 1 }, ¬e_lines); assert_eq!( - with_trailer, - "aaa\n[Note: one]\n[Note: two]\n\ - [Showing lines 1-1 of 3. Use offset=2 to continue.]" + with_marker, + "aaa\n... 2 lines not shown ...\n[Note: one]\n[Note: two]" ); - let without = render(&LINES, &ALL, ¬e_lines, BYTE_CAP); + let without = render(&LINES, &ALL, ¬e_lines); assert_eq!(without, "aaa\nbbb\nccc\n[Note: one]\n[Note: two]"); + let trailing_empty = ["aaa", ""]; + let with_trailing_nl = render(&trailing_empty, &Window { first: 1, last: 2 }, ¬e_lines); + assert_eq!(with_trailing_nl, "aaa\n[Note: one]\n[Note: two]"); } #[test] @@ -156,150 +90,40 @@ fn the_utf16_note_comes_before_the_replacement_note_and_clean_text_has_none() { } #[test] -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-2398 of 5000 (100000-byte limit). Use offset=2399 to continue.]"; - assert!( - text.ends_with(&format!("\n{trailer}")), - "the trailer ends the read" - ); - let numbered = text - .lines() - .filter(|line| line.as_bytes().get(6) == Some(&b'|')); - assert_eq!(numbered.count(), 239); - assert_eq!( - text.len() - trailer.len(), - 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 -/// and the trailer. -fn first_line_cut(line: &str, later: bool) -> (String, String) { - let mut file = line.to_owned(); - file.push('\n'); - if later { - file.push_str("next\n"); - } - 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"); - (shown.to_owned(), trailer.to_owned()) -} - -#[test] -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_999); - assert!(line.starts_with(&kept)); - assert_eq!( - trailer, - "[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 99999 bytes. \ - No parameter reads the rest of a line. Use offset=2 to continue.]" - ); -} - -#[test] -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 cut line").0; - assert_eq!(first.len() + 1, 100_000); -} - -#[test] -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_999); - assert_eq!(kept.chars().count(), 33_333); +fn a_request_at_the_raw_char_cap_succeeds_even_when_prefixes_push_rendered_over() { + // 100 lines of 999 'x's + 99 '\n's = 99,999 raw chars (plus 10 prefixes of 7 bytes = 100,069 rendered). + let file = (0..100) + .map(|_| "x".repeat(999)) + .collect::>() + .join("\n"); + assert_eq!(file.len(), 99_999); + let files = seeded("/fit.txt", file.as_bytes()); + let text = text_of(read_capped(&files, "/fit.txt", None, None, CHAR_CAP)); assert!( - trailer.contains("is 150000 bytes and is cut after 99999 bytes."), - "{trailer}" + text.len() > CHAR_CAP, + "prefixes push rendered output past cap" ); + assert!(text.contains(" 10|"), "10th line is numbered"); } #[test] -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_998); - assert!(line.starts_with(&kept)); - assert!(trailer.contains("cut after 99998 bytes."), "{trailer}"); -} - -#[test] -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_996); - assert_eq!(kept.chars().count(), 24_999); - assert!(trailer.contains("cut after 99996 bytes."), "{trailer}"); -} - -#[test] -fn a_cut_at_a_later_line_names_that_line() { - let file = format!("short\n{}\ntail\n", "x".repeat(150_000)); - let files = seeded("/long.txt", file.as_bytes()); - let text = text_of(read_capped(&files, "/long.txt", Some(2), None, BYTE_CAP)); - let trailer = text.split_once('\n').expect("a cut read has a trailer").1; +fn a_request_one_char_over_the_cap_returns_cursors_refusal_with_file_bytes() { + let file = "x".repeat(CHAR_CAP + 1); + let files = seeded("/over.txt", file.as_bytes()); + let text = text_of(read_capped(&files, "/over.txt", None, None, CHAR_CAP)); assert_eq!( - trailer, - "[Line 2 is 150000 bytes and is cut after 99992 bytes. \ - No parameter reads the rest of a line. Use offset=3 to continue.]" + text, + "Requested content exceeds maximum allowed characters (100000 characters). \ + The file is 100001 bytes.\n\ + Please use offset and limit parameters to read specific portions of the file, \ + or use the 'grep' tool to search for specific content." ); } #[test] -fn a_line_that_only_just_fits_is_not_cut() { - 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!("{line}\n")); -} - -#[test] -fn a_cap_sweep_never_splits_a_character_and_the_notice_counts_the_kept_bytes() { - let line = "a\u{E9}\u{20AC}\u{1F600}".repeat(30); - 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 (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, - "cap {cap}: {} bytes kept", - kept.len() - ); - assert!( - allowance - kept.len() < 4, - "cap {cap}: the cut stops within one character of the allowance" - ); - assert_eq!( - trailer, - format!( - "[Line 1 is {} bytes and is cut after {} bytes. \ - No parameter reads the rest of a line.]", - line.len(), - kept.len() - ), - "cap {cap}" - ); - } +fn a_long_single_line_under_the_cap_is_never_truncated() { + let line = "x".repeat(12_147); + let files = seeded("/bidi.min.js", line.as_bytes()); + let text = text_of(read_capped(&files, "/bidi.min.js", None, None, CHAR_CAP)); + assert_eq!(text, line); } diff --git a/crates/plugin-std/src/read/tests/window.rs b/crates/plugin-std/src/read/tests/window.rs index 023c2f2..3244162 100644 --- a/crates/plugin-std/src/read/tests/window.rs +++ b/crates/plugin-std/src/read/tests/window.rs @@ -2,7 +2,7 @@ //! prints for them. use super::{failure_of, numbered_file, read, read_capped, seeded, text_of}; -use crate::read::BYTE_CAP; +use crate::read::CHAR_CAP; use crate::read::window::{Window, window}; use serde_json::json; @@ -60,25 +60,39 @@ fn a_one_line_file_has_one_window() { } #[test] -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, "line 1\nline 2\nline 3\n"); -} - -#[test] -fn a_file_without_a_final_newline_has_the_same_lines() { - let with = seeded("/a.md", numbered_file(3, true).as_bytes()); - let without = seeded("/a.md", numbered_file(3, false).as_bytes()); - let args = json!({ "path": "/a.md" }); - assert_eq!(text_of(read(&with, &args)), text_of(read(&without, &args))); +fn a_whole_file_read_prints_every_line_and_preserves_trailing_newline() { + let with = seeded("/notes.md", numbered_file(3, true).as_bytes()); + assert_eq!( + text_of(read(&with, &json!({ "path": "/notes.md" }))), + "line 1\nline 2\nline 3\n" + ); + let without = seeded("/notes.md", numbered_file(3, false).as_bytes()); + assert_eq!( + text_of(read(&without, &json!({ "path": "/notes.md" }))), + "line 1\nline 2\nline 3" + ); } #[test] -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, "a\n\n"); +fn a_trailing_newline_counts_as_a_trailing_empty_line() { + let with = seeded("/a.md", b"a\nb\n"); + assert_eq!( + text_of(read(&with, &json!({ "path": "/a.md", "offset": -1 }))), + "... 2 lines not shown ...\n" + ); + assert_eq!( + failure_of(read(&with, &json!({ "path": "/a.md", "offset": 4 }))), + "Error: Offset 4 is beyond file length (3 lines)" + ); + let without = seeded("/b.md", b"a\nb"); + assert_eq!( + text_of(read(&without, &json!({ "path": "/b.md", "offset": -1 }))), + "... 1 line not shown ...\nb" + ); + assert_eq!( + failure_of(read(&without, &json!({ "path": "/b.md", "offset": 3 }))), + "Error: Offset 3 is beyond file length (2 lines)" + ); } #[test] @@ -96,23 +110,24 @@ fn a_lone_carriage_return_inside_a_line_stays_in_the_line() { } #[test] -fn a_limit_that_stops_before_the_end_names_the_next_offset() { - let files = seeded("/ten.md", numbered_file(10, true).as_bytes()); +fn a_limit_in_the_middle_prints_top_and_bottom_markers() { + let files = seeded("/ten.md", numbered_file(10, false).as_bytes()); let text = text_of(read( &files, &json!({ "path": "/ten.md", "offset": 4, "limit": 3 }), )); assert_eq!( text, - " 4|line 4\nline 5\nline 6\n\ - [Showing lines 4-6 of 10. Use offset=7 to continue.]" + "... 3 lines not shown ...\n\ + line 4\nline 5\nline 6\n\ + ... 4 lines not shown ..." ); } #[test] -fn a_read_that_reaches_the_last_line_prints_no_trailer() { - let files = seeded("/ten.md", numbered_file(10, true).as_bytes()); - let tail = " 9|line 9\n 10|line 10\n"; +fn a_read_that_reaches_the_last_line_prints_no_bottom_marker() { + let files = seeded("/ten.md", numbered_file(10, false).as_bytes()); + let tail = "... 8 lines not shown ...\nline 9\n 10|line 10"; for args in [ json!({ "path": "/ten.md", "offset": 9, "limit": 5 }), json!({ "path": "/ten.md", "offset": 9 }), @@ -124,54 +139,43 @@ fn a_read_that_reaches_the_last_line_prints_no_trailer() { } } -#[test] -fn a_limit_that_ends_exactly_on_the_last_line_prints_no_trailer() { - let files = seeded("/ten.md", numbered_file(10, true).as_bytes()); - let text = text_of(read(&files, &json!({ "path": "/ten.md", "limit": 10 }))); - assert!(!text.contains("[Showing"), "{text}"); -} - #[test] fn the_negative_offsets_read_the_tail_of_the_file() { - let files = seeded("/ten.md", numbered_file(10, true).as_bytes()); + let files = seeded("/ten.md", numbered_file(10, false).as_bytes()); let last = text_of(read(&files, &json!({ "path": "/ten.md", "offset": -1 }))); - assert_eq!(last, " 10|line 10\n"); + assert_eq!(last, "... 9 lines not shown ...\n 10|line 10"); let all = text_of(read(&files, &json!({ "path": "/ten.md", "offset": -100 }))); assert_eq!(all, text_of(read(&files, &json!({ "path": "/ten.md" })))); } #[test] fn an_offset_of_zero_reads_as_the_first_line() { - let files = seeded("/ten.md", numbered_file(10, true).as_bytes()); + let files = seeded("/ten.md", numbered_file(10, false).as_bytes()); let zero = text_of(read( &files, &json!({ "path": "/ten.md", "offset": 0, "limit": 2 }), )); - assert_eq!( - zero, - "line 1\nline 2\n[Showing lines 1-2 of 10. Use offset=3 to continue.]" - ); + assert_eq!(zero, "line 1\nline 2\n... 8 lines not shown ..."); } #[test] -fn an_offset_past_the_end_fails_with_the_line_count() { - let ten = seeded("/notes.md", numbered_file(10, true).as_bytes()); +fn an_offset_past_the_end_fails_with_cursors_line_count() { + let ten = seeded("/notes.md", numbered_file(10, false).as_bytes()); assert_eq!( failure_of(read(&ten, &json!({ "path": "/notes.md", "offset": 11 }))), - "Offset 11 is beyond the end of /notes.md, which has 10 lines." + "Error: Offset 11 is beyond file length (10 lines)" ); - let one = seeded("/one.md", b"only\n"); + let one = seeded("/one.md", b"only"); assert_eq!( failure_of(read(&one, &json!({ "path": "/one.md", "offset": 2 }))), - "Offset 2 is beyond the end of /one.md, which has 1 line." + "Error: Offset 2 is beyond file length (1 line)" ); } #[test] -fn the_line_number_widens_past_six_digits_and_the_prefix_stays_in_the_cap() { +fn the_line_number_widens_past_six_digits() { + // 1_000_000 '\n's produces 1_000_001 lines; line 1_000_000 is the second-to-last. let files = seeded("/many.txt", "\n".repeat(1_000_000).as_bytes()); - let last = text_of(read_capped(&files, "/many.txt", Some(-1), None, BYTE_CAP)); - assert_eq!(last, "1000000|\n"); - let two = text_of(read_capped(&files, "/many.txt", Some(-2), None, BYTE_CAP)); - assert_eq!(two, "999999|\n1000000|\n"); + let two = text_of(read_capped(&files, "/many.txt", Some(-2), None, CHAR_CAP)); + assert_eq!(two, "... 999999 lines not shown ...\n1000000|\n"); } diff --git a/crates/plugin-std/src/spec-tests.rs b/crates/plugin-std/src/spec-tests.rs index cf9ff28..8d8091b 100644 --- a/crates/plugin-std/src/spec-tests.rs +++ b/crates/plugin-std/src/spec-tests.rs @@ -133,7 +133,7 @@ fn the_read_description_holds_the_limits_the_code_uses_and_no_unfilled_placehold !text.contains("2000 characters"), "the 2000-character line is gone: {text}" ); - for placeholder in ["{byte_cap}", "{file_ceiling}"] { + for placeholder in ["{char_cap}", "{file_ceiling}"] { assert!( !text.contains(placeholder), "{placeholder} is filled in: {text}" @@ -310,7 +310,7 @@ fn the_read_schema_takes_integers_for_offset_and_limit() { fn no_definition_names_behavior_this_build_does_not_have() { for definition in all() { let text = format!("{} {}", definition.description, definition.parameters); - for absent in ["PDF", "Shell tool", "Cursor workspace"] { + for absent in ["Shell tool", "Cursor workspace"] { assert!( !text.contains(absent), "the {} tool mentions {absent}: {text}", diff --git a/crates/plugin-std/src/spec.rs b/crates/plugin-std/src/spec.rs index 53cd174..40d314e 100644 --- a/crates/plugin-std/src/spec.rs +++ b/crates/plugin-std/src/spec.rs @@ -88,7 +88,7 @@ fn parse(sources: &[(&'static str, &str)]) -> Result, ToolError> fn fill(segment: &str, description: &str) -> String { match segment { "read" => description - .replace("{byte_cap}", &crate::read::BYTE_CAP.to_string()) + .replace("{char_cap}", &crate::read::CHAR_CAP.to_string()) .replace("{file_ceiling}", &crate::text::MAX_FILE_BYTES.to_string()), "write" => description.replace( "{write_limit}", diff --git a/crates/plugin-std/tests/it/changes.rs b/crates/plugin-std/tests/it/changes.rs index 8b5a961..c2e7dac 100644 --- a/crates/plugin-std/tests/it/changes.rs +++ b/crates/plugin-std/tests/it/changes.rs @@ -403,5 +403,5 @@ fn the_calls_of_one_run_write_edit_read_and_delete_one_file_in_turn() { assert_eq!(answer("read", json!({ "path": path })), "one\n2\n"); assert_eq!(answer("rm", json!({ "path": path })), "Deleted the file."); let gone = answer("read", json!({ "path": path })); - assert_eq!(gone, "File not found: /notes/a.md"); + assert_eq!(gone, "Error: File not found"); } diff --git a/crates/plugin-std/tests/it/tools.rs b/crates/plugin-std/tests/it/tools.rs index d8737e5..2bfb3eb 100644 --- a/crates/plugin-std/tests/it/tools.rs +++ b/crates/plugin-std/tests/it/tools.rs @@ -105,7 +105,7 @@ fn model_caller_receives_domain_and_argument_errors_as_trusted_text() { ) .expect("model caller receives text instead of ToolError"); assert!(missing.is_trusted()); - assert_eq!(missing.text(), "File not found: /nope.md"); + assert_eq!(missing.text(), "Error: File not found"); let invalid = call_as(Files::new(), Caller::Model, "read", &json!({ "path": 7 })) .expect("model caller receives invalid-argument text instead of ToolError"); @@ -185,7 +185,7 @@ fn read_answers_file_is_empty_for_a_zero_byte_file() { #[test] fn read_of_a_missing_path_fails_with_the_not_found_text() { let error = call("read", &json!({ "path": "/nope.md" })).expect_err("the file is missing"); - assert_eq!(error.message(), "File not found: /nope.md"); + assert_eq!(error.message(), "Error: File not found"); assert_eq!(error.kind(), ToolErrorKind::Other); }