Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down
2 changes: 2 additions & 0 deletions crates/plugin-std/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions crates/plugin-std/schemas/EDITS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion crates/plugin-std/schemas/read.json
Original file line number Diff line number Diff line change
@@ -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": {
Expand Down
4 changes: 2 additions & 2 deletions crates/plugin-std/src/pack-tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand 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]
Expand Down
166 changes: 141 additions & 25 deletions crates/plugin-std/src/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -41,12 +54,12 @@ pub(crate) async fn call(
args: &Value,
) -> Result<ToolOutput, ToolError> {
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,
Expand All @@ -55,33 +68,136 @@ async fn read_file(
) -> Result<ToolOutput, ToolError> {
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(), &notes, 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<ToolOutput, String> {
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, &notes, 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<String> {
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
Expand Down
19 changes: 12 additions & 7 deletions crates/plugin-std/src/read/args.rs
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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)),
Expand Down
Loading
Loading