diff --git a/Cargo.toml b/Cargo.toml index 21606db..4d810dd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,9 +12,9 @@ rig-core = { version = "0.47.2", default-features = false, features = ["reqwest" rig-tools = "0.47.2" serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" +tempfile = "3.27.0" tokio = { version = "1.54.1", features = ["macros", "rt-multi-thread"] } yaml_serde = "0.10.7" [dev-dependencies] rig-core = { version = "0.47.2", default-features = false, features = ["test-utils"] } -tempfile = "3.27.0" diff --git a/README.md b/README.md index e69de29..4f57d72 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,111 @@ +# killall-agent + +A Rust CLI for running YAML-defined, read-only coding agents with Rig. Each run +loads the configured tools and instructions, sends one prompt, and prints the +answer. Tools may inspect the current directory but cannot write files or escape +that workspace. + +## Run + +Requires Rust 1.97.1 or newer and provider configuration in +`~/.pi/agent/models.json`. GitHub skill sources also require `git` on `PATH` and +network access. + +```sh +cargo run --locked -- --agent sandbox/default.yaml --prompt "Explain this project" +``` + +The default definition uses `strata/qwen3.8-flash-next-q2_0`. Use a definition +matching your Pi configuration, or override its model: + +```sh +cargo run --locked -- --agent sandbox/default.yaml --model provider/model --tools read,search +``` + +## Agent definitions + +```yaml +name: reader +model: provider/model +tools: [Read, Search] +agentfile: instructions.md +skills: + - file://skills/explain + - github://killallgit/killall-skills/skills/parse-dont-validate +``` + +- `name` and `model` are required. Unknown YAML fields are rejected. +- `model` is a provider key and declared model ID from Pi's `models.json`, split + at the first slash. Supported provider APIs are `openai-completions`, + `openai-responses`, and `anthropic-messages`. Credentials may be literal keys + or `!command` values; Anthropic models need a positive configured or built-in + output-token limit. +- `tools` selects `read`, `list`, and `search`, case-insensitively. `ALL`, an + omitted list, or an empty list enables all three. Duplicates are ignored; + unknown names are errors, including alongside `ALL`. +- `agentfile` is optional. Its contents follow the built-in read-only + instructions in the system prompt. +- `skills` is optional. All selected `SKILL.md` instructions follow the + agentfile in source order, with collection entries sorted by path. Missing or + malformed sources and duplicate skill names are errors, not silent skips. + +Relative agentfile paths and `file://` paths resolve from the YAML file's +containing directory. They do not change the workspace: tool paths still +resolve from the directory where you launched the CLI. + +### Overrides + +`--name`, `--model`, `--tools`, `--skills`, and `--agentfile` replace the matching +YAML values. CLI resource paths resolve from the current directory instead. +`--tools` accepts space- or comma-separated names; `--skills` accepts +space-separated sources. A bare `--skills` clears the YAML skills list. + +```sh +cargo run --locked -- --agent sandbox/default.yaml \ + --agentfile ./instructions.md --tools read list \ + --skills file://./skills/explain github://owner/repository/path/to/skill \ + --prompt "Review the implementation" +``` + +## Skill sources and trust + +A skill requires a `SKILL.md` with YAML frontmatter containing nonempty `name` +and `description` fields, followed by a nonempty Markdown body. + +- `file://path` accepts a skill file, a directory containing `SKILL.md`, or a + collection with immediate child skill directories. Repository collections + under `skills/` are also discovered. +- `github://owner/repository[/path]` shallow-clones the default branch over + HTTPS into a temporary directory, then loads the same formats. Checkouts are + discarded after reading. There is no cache, ref selection, or private-repo + authentication support; global Git configuration and hooks are disabled. + +Only configure sources you trust: their text is supplied as model instructions. +Fetching does not run skill scripts, install packages, or initialize submodules. +Companion references and assets are not loaded, and skills do not expand the +workspace boundary of the read-only tools. + +## Checks + +```sh +cargo test --locked --all-targets +cargo fmt --all --check +cargo clippy --locked --all-targets -- -D warnings +``` + +The default tests use temporary files, local Git repositories, mock models, and +local HTTP servers; no external model API or GitHub access is needed. An +optional end-to-end GitHub fetch check uses a public skill and a local mock +model: + +```sh +cargo test --locked --test agent_runtime github_skill_instructions -- --ignored +``` + +## Releases + +From a clean, up-to-date `main`, maintainers can run `npm ci` followed by +`npm run release -- patch` (or `minor` / `major`). Release-it runs the local +checks, updates the Cargo version and lockfile, and commits, tags, and pushes. +The tag-triggered GitHub workflow verifies the version, reruns CI and security +checks, and publishes Linux and macOS binaries with checksums. diff --git a/sandbox/example-def.yaml b/sandbox/example-def.yaml index bfb62fe..d869e38 100644 --- a/sandbox/example-def.yaml +++ b/sandbox/example-def.yaml @@ -2,9 +2,6 @@ name: lenny model: openai/sol tools: - ALL - - Read - - List - - Etc skills: - github://owner/repo - file://path/to/dir diff --git a/src/cli.rs b/src/cli.rs index f4c0f6f..d4bc9ac 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,7 +1,11 @@ -use std::path::PathBuf; +use std::path::{Path, PathBuf}; +use anyhow::{Result, ensure}; use clap::Parser; -use killall_agent::models::ModelSelection; +use killall_agent::{ + definition::{self, Definition}, + models::ModelSelection, +}; #[derive(Debug, Parser)] #[command( @@ -20,6 +24,53 @@ pub struct Args { /// Override the agent definition's model #[arg(short, long, value_name = "PROVIDER/MODEL")] pub model: Option, + + /// Override the agent's name + #[arg(long)] + pub name: Option, + + /// Replace tool selection (read, list, search, or ALL); empty means ALL + #[arg(long, value_name = "TOOL", num_args = 0.., value_delimiter = ',')] + pub tools: Option>, + + /// Replace skill sources; an empty --skills clears the YAML list + #[arg(long, value_name = "SOURCE", num_args = 0..)] + pub skills: Option>, + + /// Override the instruction file, relative to the current directory + #[arg(long, value_name = "PATH")] + pub agentfile: Option, +} + +impl Args { + pub fn load_definition(&self, workspace: &Path) -> Result { + let mut definition = definition::load(&workspace.join(&self.agent))?; + if let Some(name) = &self.name { + ensure!(!name.trim().is_empty(), "Agent name must not be empty"); + definition.name.clone_from(name); + } + if let Some(model) = &self.model { + definition.model = model.clone(); + } + if let Some(tools) = &self.tools { + definition.tools.clone_from(tools); + } + if let Some(sources) = &self.skills { + definition.skills = sources + .iter() + .map(|source| match source.strip_prefix("file://") { + Some(path) if !path.trim().is_empty() => { + format!("file://{}", workspace.join(path).display()) + } + _ => source.clone(), + }) + .collect(); + } + if let Some(path) = &self.agentfile { + definition.agentfile = Some(workspace.join(path)); + } + Ok(definition) + } } #[cfg(test)] @@ -60,6 +111,88 @@ mod tests { } } + #[test] + fn cli_resources_replace_yaml_values_and_use_the_workspace_for_relative_paths() { + let directory = tempfile::tempdir().unwrap(); + let definitions = directory.path().join("definitions"); + std::fs::create_dir(&definitions).unwrap(); + let path = definitions.join("agent.yaml"); + std::fs::write(&path, "name: yaml\nmodel: yaml/model\ntools: [search]\nskills: [file://old]\nagentfile: old.md\n").unwrap(); + let args = Args::try_parse_from([ + "killall-agent", + "--agent", + path.to_str().unwrap(), + "--name", + "cli", + "--model", + "cli/model", + "--tools", + "Read,List", + "--skills", + "file://guide", + "github://owner/repo", + "--agentfile", + "new.md", + ]) + .unwrap(); + + let definition = args.load_definition(directory.path()).unwrap(); + + assert_eq!(definition.name, "cli"); + assert_eq!(definition.model, "cli/model".parse().unwrap()); + assert_eq!(definition.tools, ["Read", "List"]); + assert_eq!( + definition.skills, + [ + format!("file://{}", directory.path().join("guide").display()), + "github://owner/repo".into() + ] + ); + assert_eq!(definition.agentfile, Some(directory.path().join("new.md"))); + } + + #[test] + fn an_empty_skills_override_clears_yaml_skills() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("agent.yaml"); + std::fs::write( + &path, + "name: yaml\nmodel: yaml/model\nskills: [file://old]\n", + ) + .unwrap(); + let args = Args::try_parse_from([ + "killall-agent", + "--agent", + path.to_str().unwrap(), + "--skills", + ]) + .unwrap(); + + assert!( + args.load_definition(directory.path()) + .unwrap() + .skills + .is_empty() + ); + } + + #[test] + fn rejects_a_blank_name_override() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("agent.yaml"); + std::fs::write(&path, "name: yaml\nmodel: yaml/model\n").unwrap(); + let args = Args::try_parse_from([ + "killall-agent", + "--agent", + path.to_str().unwrap(), + "--name", + " ", + ]) + .unwrap(); + + assert!(args.load_definition(directory.path()).is_err()); + } + #[test] fn rejects_malformed_model_selections() { for model in ["qwen3.8", "strata/", "/qwen3.8"] { diff --git a/src/definition.rs b/src/definition.rs index e8ce91a..5531d43 100644 --- a/src/definition.rs +++ b/src/definition.rs @@ -51,7 +51,7 @@ mod tests { assert_eq!(definition.name, "lenny"); assert_eq!(definition.model.provider(), "openai"); assert_eq!(definition.model.id(), "sol"); - assert_eq!(definition.tools, ["ALL", "Read", "List", "Etc"]); + assert_eq!(definition.tools, ["ALL"]); assert_eq!( definition.skills, ["github://owner/repo", "file://path/to/dir"] diff --git a/src/lib.rs b/src/lib.rs index 12b74f8..7e5f5d5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,6 @@ pub mod config; pub mod definition; pub mod models; +pub mod runtime; +pub mod skills; pub mod tools; diff --git a/src/main.rs b/src/main.rs index a524f0b..5a8d08f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,21 +2,22 @@ mod cli; use anyhow::{Context, Result}; use clap::Parser; -use killall_agent::{config, definition, models, tools}; +use killall_agent::{config, models, runtime}; use rig_agent::AgentBuilder; #[tokio::main] async fn main() -> Result<()> { let args = cli::Args::parse(); - let definition = definition::load(&args.agent)?; let workspace = std::env::current_dir().context("Cannot determine workspace directory")?; - let tools = tools::load(&workspace)?; + let definition = args.load_definition(&workspace)?; + let path = workspace.join(&args.agent); + let resources = runtime::load(&definition, path.parent().unwrap_or(&workspace), &workspace)?; let config = config::load()?; - let model = models::load(&config, args.model.unwrap_or(definition.model))?; + let model = models::load(&config, definition.model)?; let agent = AgentBuilder::new(model) - .tool_server_handle(tools) + .tool_server_handle(resources.tools) .default_max_turns(10) - .preamble("You are a coding assistant with read-only tools. Relative tool paths resolve from the workspace directory. Use the tools when needed to inspect files; do not claim to have changed files.") + .preamble(resources.instructions) .build(); let response = agent .prompt(args.prompt) diff --git a/src/runtime.rs b/src/runtime.rs new file mode 100644 index 0000000..2e378d7 --- /dev/null +++ b/src/runtime.rs @@ -0,0 +1,33 @@ +use std::{fs, path::Path}; + +use anyhow::{Context, Result}; +use rig_agent::tool::server::ToolServerHandle; + +use crate::{definition::Definition, skills, tools}; + +pub struct Resources { + pub tools: ToolServerHandle, + pub instructions: String, +} + +pub fn load(definition: &Definition, base: &Path, workspace: &Path) -> Result { + let tools = tools::select(workspace, &definition.tools)?; + let mut instructions = format!( + "You are {}, a coding assistant with read-only tools. Relative tool paths resolve from the workspace directory. Use only the tools available to you; do not claim to have changed files.", + definition.name + ); + if let Some(path) = &definition.agentfile { + let contents = fs::read_to_string(path) + .with_context(|| format!("Could not read agent instructions {}", path.display()))?; + instructions.push_str("\n\n# Agent instructions\n\n"); + instructions.push_str(&contents); + } + for skill in skills::load(&definition.skills, base)? { + instructions.push_str(&format!("\n\n# Skill: {}\n\n", skill.name)); + instructions.push_str(&skill.instructions); + } + Ok(Resources { + tools, + instructions, + }) +} diff --git a/src/skills.rs b/src/skills.rs new file mode 100644 index 0000000..a04ad89 --- /dev/null +++ b/src/skills.rs @@ -0,0 +1,754 @@ +use std::{ + collections::HashSet, + fs, + path::{Path, PathBuf}, +}; + +use anyhow::{Context, Result, ensure}; +use serde::Deserialize; + +#[derive(Debug)] +pub struct Skill { + pub name: String, + pub instructions: String, +} + +pub fn load(sources: &[String], base: &Path) -> Result> { + load_with_fetch(sources, base, clone_repository) +} + +fn load_with_fetch( + sources: &[String], + base: &Path, + mut fetch: impl FnMut(&str, &Path) -> Result<()>, +) -> Result> { + let mut skills = Vec::new(); + let mut names = HashSet::new(); + for source in sources { + let checkout; + let path = if let Some(relative) = source.strip_prefix("file://") { + ensure!(!relative.trim().is_empty(), "Empty file skill source"); + base.join(relative) + } else if let Some(repository) = source.strip_prefix("github://") { + let (url, subpath) = github_source(repository)?; + checkout = tempfile::tempdir().context("Could not create skill checkout directory")?; + let root = checkout.path().join("repository"); + fetch(&url, &root).with_context(|| format!("Could not fetch skill source {source}"))?; + let root = root.canonicalize()?; + check_fetched_links(&root, &root)?; + root.join(subpath) + } else { + anyhow::bail!("Unsupported skill source: {source}"); + }; + for path in discover(&path)? { + let skill = + read_skill(&path).with_context(|| format!("Invalid skill {}", path.display()))?; + ensure!( + names.insert(skill.name.clone()), + "Duplicate skill name: {}", + skill.name + ); + skills.push(skill); + } + } + Ok(skills) +} + +fn github_source(repository: &str) -> Result<(String, PathBuf)> { + ensure!( + !repository + .chars() + .any(|c| c.is_control() || matches!(c, '\\' | '?' | '#' | '@' | ':' | '%')), + "Unsafe GitHub skill source" + ); + let parts: Vec<_> = repository.split('/').collect(); + ensure!(parts.len() >= 2, "GitHub source requires owner/repo"); + let owner = parts[0]; + let repo = parts[1]; + ensure!( + !owner.is_empty() + && owner.len() <= 39 + && owner + .bytes() + .all(|c| c.is_ascii_alphanumeric() || c == b'-') + && !owner.starts_with('-') + && !owner.ends_with('-') + && !owner.contains("--"), + "Invalid GitHub owner" + ); + ensure!( + !repo.is_empty() + && repo.len() <= 100 + && repo != "." + && repo != ".." + && repo + .bytes() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_' | b'.')), + "Invalid GitHub repository" + ); + ensure!( + parts[2..] + .iter() + .all(|part| !part.is_empty() && *part != "." && *part != ".."), + "Unsafe GitHub subdirectory" + ); + Ok(( + format!("https://github.com/{owner}/{repo}.git"), + parts[2..].iter().collect(), + )) +} + +fn clone_repository(url: &str, destination: &Path) -> Result<()> { + let output = std::process::Command::new("git") + .args([ + "-c", + "core.hooksPath=/dev/null", + "clone", + "--depth", + "1", + "--no-local", + "--no-recurse-submodules", + "--template=", + "--", + ]) + .arg(url) + .arg(destination) + .env("GIT_TERMINAL_PROMPT", "0") + .env_remove("GIT_ASKPASS") + .env_remove("SSH_ASKPASS") + .env_remove("SSH_ASKPASS_REQUIRE") + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_COUNT", "0") + .env_remove("GIT_CONFIG_PARAMETERS") + .env_remove("GIT_CONFIG") + .env_remove("GIT_DIR") + .env_remove("GIT_WORK_TREE") + .env_remove("GIT_COMMON_DIR") + .env_remove("GIT_INDEX_FILE") + .env_remove("GIT_OBJECT_DIRECTORY") + .env_remove("GIT_ALTERNATE_OBJECT_DIRECTORIES") + .env_remove("GIT_IMPLICIT_WORK_TREE") + .env_remove("GIT_GRAFT_FILE") + .env_remove("GIT_NO_REPLACE_OBJECTS") + .env_remove("GIT_REPLACE_REF_BASE") + .env_remove("GIT_PREFIX") + .env_remove("GIT_SHALLOW_FILE") + .output() + .context("Could not run git clone")?; + ensure!( + output.status.success(), + "git clone failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ); + Ok(()) +} + +fn check_fetched_links(root: &Path, directory: &Path) -> Result<()> { + for entry in fs::read_dir(directory)? { + let entry = entry?; + let kind = entry.file_type()?; + let path = entry.path(); + if kind.is_symlink() { + let target = path + .canonicalize() + .with_context(|| format!("Could not resolve fetched symlink {}", path.display()))?; + ensure!( + target.starts_with(root), + "Symlink {} escapes fetched repository", + path.display() + ); + } else if kind.is_dir() { + check_fetched_links(root, &path)?; + } + } + Ok(()) +} + +fn discover(path: &Path) -> Result> { + let metadata = fs::metadata(path) + .with_context(|| format!("Could not inspect skill source {}", path.display()))?; + if metadata.is_file() { + ensure!( + path.file_name().is_some_and(|name| name == "SKILL.md"), + "Skill file must be named SKILL.md" + ); + return Ok(vec![path.to_owned()]); + } + ensure!( + metadata.is_dir(), + "Skill source must be a file or directory" + ); + if path.join("SKILL.md").try_exists()? { + return Ok(vec![path.join("SKILL.md")]); + } + let mut paths = Vec::new(); + for directory in [path.to_owned(), path.join("skills")] { + if !directory.is_dir() { + continue; + } + for entry in fs::read_dir(&directory)? { + let child = entry?.path(); + if child.is_dir() && child.join("SKILL.md").try_exists()? { + paths.push(child.join("SKILL.md")); + } + } + } + paths.sort(); + ensure!(!paths.is_empty(), "No skills found in {}", path.display()); + Ok(paths) +} + +fn read_skill(path: &Path) -> Result { + #[derive(Deserialize)] + struct Metadata { + name: String, + description: String, + } + + let instructions = fs::read_to_string(path) + .with_context(|| format!("Could not read skill {}", path.display()))?; + let mut lines = instructions.lines(); + ensure!( + lines.next() == Some("---"), + "Skill requires YAML frontmatter" + ); + let mut frontmatter = Vec::new(); + loop { + let line = lines.next().context("Unclosed skill frontmatter")?; + if line == "---" { + break; + } + frontmatter.push(line); + } + let metadata: Metadata = yaml_serde::from_str(&frontmatter.join("\n"))?; + ensure!( + !metadata.name.trim().is_empty(), + "Skill name must not be empty" + ); + ensure!( + !metadata.description.trim().is_empty(), + "Skill description must not be empty" + ); + ensure!( + lines.any(|line| !line.trim().is_empty()), + "Skill body must not be empty" + ); + Ok(Skill { + name: metadata.name, + instructions, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + fn write_skill(root: &Path, relative: &str, name: &str) { + let path = root.join(relative); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write( + path, + format!( + "---\nname: {name}\ndescription: A useful skill\n---\nFollow these instructions.\n" + ), + ) + .unwrap(); + } + + #[test] + fn discovers_collection_children_in_lexical_path_order() { + let base = tempfile::tempdir().unwrap(); + write_skill(base.path(), "collection/z/SKILL.md", "first-name"); + write_skill(base.path(), "collection/a/SKILL.md", "last-name"); + write_skill(base.path(), "collection/deeper/nested/SKILL.md", "ignored"); + let skills = load(&["file://collection".into()], base.path()).unwrap(); + assert_eq!( + skills + .iter() + .map(|skill| skill.name.as_str()) + .collect::>(), + ["last-name", "first-name"] + ); + } + + #[test] + fn loads_a_skill_directory_from_an_absolute_path() { + let base = tempfile::tempdir().unwrap(); + write_skill(base.path(), "SKILL.md", "direct"); + let skills = load( + &[format!("file://{}", base.path().display())], + Path::new("unused"), + ) + .unwrap(); + assert_eq!(skills[0].name, "direct"); + } + + #[test] + fn discovers_the_conventional_repository_skills_directory() { + let base = tempfile::tempdir().unwrap(); + write_skill(base.path(), "repo/skills/guide/SKILL.md", "guide"); + let skills = load(&["file://repo".into()], base.path()).unwrap(); + assert_eq!(skills[0].name, "guide"); + } + + #[test] + fn rejects_empty_unsupported_and_missing_sources() { + let base = tempfile::tempdir().unwrap(); + assert!(load(&[], base.path()).unwrap().is_empty()); + for source in [ + "", + "file://", + "http://example.com", + "guide", + "file://missing", + "file://.", + ] { + assert!(load(&[source.into()], base.path()).is_err(), "{source}"); + } + fs::write(base.path().join("notes.md"), "Not a skill").unwrap(); + assert!(load(&["file://notes.md".into()], base.path()).is_err()); + } + + #[test] + fn rejects_duplicate_skill_names_across_sources() { + let base = tempfile::tempdir().unwrap(); + write_skill(base.path(), "one/SKILL.md", "same"); + write_skill(base.path(), "two/SKILL.md", "same"); + let error = load(&["file://one".into(), "file://two".into()], base.path()).unwrap_err(); + assert!(error.to_string().contains("Duplicate skill name: same")); + } + + #[test] + fn rejects_invalid_frontmatter_and_empty_bodies() { + let base = tempfile::tempdir().unwrap(); + let path = base.path().join("SKILL.md"); + for contents in [ + "No frontmatter", + "---\nname: guide\n", + "---\nname: [\n---\nBody", + "---\nname: guide\n---\nBody", + "---\ndescription: useful\n---\nBody", + "---\nname: ' '\ndescription: useful\n---\nBody", + "---\nname: guide\ndescription: ''\n---\nBody", + "---\nname: guide\ndescription: useful\n---\n \n", + ] { + fs::write(&path, contents).unwrap(); + assert!( + load(&["file://SKILL.md".into()], base.path()).is_err(), + "{contents}" + ); + } + } + + #[test] + fn preserves_underlying_skill_read_errors() { + let base = tempfile::tempdir().unwrap(); + let error = load(&["file://missing/SKILL.md".into()], base.path()).unwrap_err(); + assert_eq!( + error.downcast_ref::().unwrap().kind(), + std::io::ErrorKind::NotFound + ); + } + + #[test] + fn resolves_github_repositories_and_subdirectories_without_network() { + for (source, relative) in [ + ("github://owner/repo", "skills/guide/SKILL.md"), + ("github://owner/repo/guides", "guides/guide/SKILL.md"), + ("github://owner/repo/guides/SKILL.md", "guides/SKILL.md"), + ] { + let mut fetched = None; + let skills = + load_with_fetch(&[source.into()], Path::new("unused"), |url, destination| { + assert_eq!(url, "https://github.com/owner/repo.git"); + fetched = Some(destination.to_owned()); + write_skill(destination, relative, "guide"); + Ok(()) + }) + .unwrap(); + assert_eq!(skills[0].name, "guide"); + assert!( + skills[0] + .instructions + .contains("Follow these instructions.") + ); + assert!( + !fetched.unwrap().exists(), + "Temporary checkout must be discarded" + ); + } + } + + #[test] + fn rejects_unsafe_github_sources_before_fetching() { + for source in [ + "github://", + "github://owner", + "github:///repo", + "github://owner/", + "github://user@host/repo", + "github://user:password@host/repo", + "github://-owner/repo", + "github://owner-/repo", + "github://ow--ner/repo", + "github://owner/..", + "github://owner/repo/../escape", + "github://owner/repo/./guide", + "github://owner/repo//absolute", + "github://owner/repo/guide/", + "github://owner/repo\\escape", + "github://owner/repo?ref=main", + "github://owner/repo#main", + "github://owner/repo/path?ref=main", + "github://owner/repo/path#main", + "github://owner/repo/\npath", + "github://owner/repo/\u{7f}path", + "github://owner/repo/%2e%2e", + "github://owner/repo/C:/escape", + ] { + assert!( + load_with_fetch(&[source.into()], Path::new("."), |_, _| panic!( + "Fetched unsafe source: {source}" + )) + .is_err(), + "{source}" + ); + } + } + + #[test] + fn propagates_fetch_failures_and_discards_partial_checkouts() { + let mut fetched = None; + let error = load_with_fetch( + &["github://owner/repo".into()], + Path::new("."), + |_, destination| { + write_skill(destination, "SKILL.md", "partial"); + fetched = Some(destination.to_owned()); + Err(std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "offline").into()) + }, + ) + .unwrap_err(); + assert_eq!( + error.downcast_ref::().unwrap().kind(), + std::io::ErrorKind::ConnectionRefused + ); + assert!(!fetched.unwrap().exists()); + } + + #[test] + fn rejects_empty_fetched_repositories_and_missing_subdirectories() { + for source in ["github://owner/repo", "github://owner/repo/missing"] { + assert!( + load_with_fetch(&[source.into()], Path::new("."), |_, destination| { + fs::create_dir_all(destination)?; + Ok(()) + }) + .is_err() + ); + } + } + + #[test] + fn rejects_duplicate_names_within_a_fetched_collection() { + let error = load_with_fetch( + &["github://owner/repo".into()], + Path::new("."), + |_, destination| { + write_skill(destination, "a/SKILL.md", "same"); + write_skill(destination, "b/SKILL.md", "same"); + Ok(()) + }, + ) + .unwrap_err(); + assert!(error.to_string().contains("Duplicate skill name: same")); + } + + #[cfg(unix)] + #[test] + fn rejects_symlink_escapes_in_fetched_files_directories_and_resources() { + use std::os::unix::fs::symlink; + let outside = tempfile::tempdir().unwrap(); + write_skill(outside.path(), "SKILL.md", "outside"); + for (source, link, target) in [ + ( + "github://owner/repo", + "guide/SKILL.md", + outside.path().join("SKILL.md"), + ), + ( + "github://owner/repo/guide", + "guide", + outside.path().to_owned(), + ), + ("github://owner/repo", "resource", outside.path().to_owned()), + ( + "github://owner/repo/.git", + ".git", + outside.path().to_owned(), + ), + ] { + let error = load_with_fetch(&[source.into()], Path::new("."), |_, destination| { + write_skill(destination, "SKILL.md", "inside"); + let link = destination.join(link); + fs::create_dir_all(link.parent().unwrap())?; + symlink(&target, link)?; + Ok(()) + }) + .unwrap_err(); + assert!(format!("{error:#}").contains("escapes fetched repository")); + } + } + + #[cfg(unix)] + #[test] + fn accepts_fetched_symlinks_that_stay_in_the_repository() { + let skills = load_with_fetch( + &["github://owner/repo/alias".into()], + Path::new("."), + |_, destination| { + write_skill(destination, "guide/SKILL.md", "inside"); + std::os::unix::fs::symlink("guide", destination.join("alias"))?; + Ok(()) + }, + ) + .unwrap(); + assert_eq!(skills[0].name, "inside"); + } + + #[test] + fn clone_helper_shallow_clones_a_disposable_local_repository() { + use std::process::Command; + if let Some(source) = std::env::var_os("SKILLS_TEST_CLONE_SOURCE") { + let destination = std::env::var_os("SKILLS_TEST_CLONE_DESTINATION").unwrap(); + clone_repository(source.to_str().unwrap(), Path::new(&destination)).unwrap(); + return; + } + let source = tempfile::tempdir().unwrap(); + let destination = tempfile::tempdir().unwrap(); + let git = |args: &[&str]| { + let output = Command::new("git") + .arg("-C") + .arg(source.path()) + .args(args) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_COUNT", "0") + .env_remove("GIT_CONFIG_PARAMETERS") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap().trim().to_owned() + }; + git(&["init", "--template="]); + write_skill(source.path(), "skills/guide/SKILL.md", "guide"); + git(&["add", "."]); + git(&[ + "-c", + "user.name=Skill Test", + "-c", + "user.email=skills@example.invalid", + "commit", + "-m", + "first", + "--no-gpg-sign", + ]); + let first = git(&["rev-parse", "HEAD"]); + fs::write( + source.path().join(".gitmodules"), + "[submodule \"unavailable\"]\npath = unavailable\nurl = file:///not-a-repository\n", + ) + .unwrap(); + git(&["add", ".gitmodules"]); + git(&[ + "update-index", + "--add", + "--cacheinfo", + &format!("160000,{first},unavailable"), + ]); + git(&[ + "-c", + "user.name=Skill Test", + "-c", + "user.email=skills@example.invalid", + "commit", + "-m", + "second", + "--no-gpg-sign", + ]); + + fs::write(source.path().join("staged.txt"), "caller staging\n").unwrap(); + git(&["add", "staged.txt"]); + let index = source.path().join(".git/index"); + let index_before = fs::read(&index).unwrap(); + let staging_before = git(&["diff", "--cached", "--binary"]); + assert!(staging_before.contains("caller staging")); + + let checkout = destination.path().join("checkout"); + let output = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "skills::tests::clone_helper_shallow_clones_a_disposable_local_repository", + "--nocapture", + ]) + .env("SKILLS_TEST_CLONE_SOURCE", source.path()) + .env("SKILLS_TEST_CLONE_DESTINATION", &checkout) + .env("GIT_INDEX_FILE", &index) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(fs::read(&index).unwrap(), index_before); + assert_eq!(git(&["diff", "--cached", "--binary"]), staging_before); + assert!(!checkout.join("staged.txt").exists()); + assert!(checkout.join(".git/shallow").is_file()); + assert!(!checkout.join("unavailable/.git").exists()); + let skills = load(&[format!("file://{}", checkout.display())], source.path()).unwrap(); + assert_eq!(skills[0].name, "guide"); + } + + #[cfg(unix)] + #[test] + fn clone_helper_never_runs_inherited_askpass_on_http_401() { + use std::{ + io::{Read, Write}, + net::TcpListener, + os::unix::fs::PermissionsExt, + process::{Command, Stdio}, + thread, + time::{Duration, Instant}, + }; + + if let Ok(url) = std::env::var("SKILLS_TEST_AUTH_URL") { + let destination = std::env::var_os("SKILLS_TEST_CLONE_DESTINATION").unwrap(); + assert!(clone_repository(&url, Path::new(&destination)).is_err()); + return; + } + + let directory = tempfile::tempdir().unwrap(); + let helper = directory.path().join("askpass"); + fs::write( + &helper, + "#!/bin/sh\nprintf invoked > \"$SKILLS_TEST_ASKPASS_MARKER\"\nexit 1\n", + ) + .unwrap(); + fs::set_permissions(&helper, fs::Permissions::from_mode(0o700)).unwrap(); + let mut invoked = Vec::new(); + for variable in ["GIT_ASKPASS", "SSH_ASKPASS"] { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + listener.set_nonblocking(true).unwrap(); + let server = thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(3); + let mut requests = 0; + while Instant::now() < deadline { + match listener.accept() { + Ok((mut stream, _)) => { + stream + .set_read_timeout(Some(Duration::from_secs(1))) + .unwrap(); + stream + .set_write_timeout(Some(Duration::from_secs(1))) + .unwrap(); + let mut request = [0; 4096]; + if stream.read(&mut request).unwrap_or(0) > 0 { + requests += 1; + let _ = stream.write_all( + b"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"skills-test\"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ); + } + } + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(10)); + } + Err(error) => panic!("{error}"), + } + } + requests + }); + let marker = directory.path().join(variable); + let mut child = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "skills::tests::clone_helper_never_runs_inherited_askpass_on_http_401", + "--nocapture", + ]) + .env( + "SKILLS_TEST_AUTH_URL", + format!("http://{address}/repository.git"), + ) + .env( + "SKILLS_TEST_CLONE_DESTINATION", + directory.path().join("checkout"), + ) + .env("SKILLS_TEST_ASKPASS_MARKER", &marker) + .env_remove("GIT_ASKPASS") + .env_remove("SSH_ASKPASS") + .env(variable, &helper) + .env("SSH_ASKPASS_REQUIRE", "force") + .env("NO_PROXY", "127.0.0.1") + .env("no_proxy", "127.0.0.1") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(10); + while child.try_wait().unwrap().is_none() && Instant::now() < deadline { + thread::sleep(Duration::from_millis(10)); + } + let timed_out = child.try_wait().unwrap().is_none(); + if timed_out { + child.kill().unwrap(); + } + let output = child.wait_with_output().unwrap(); + assert!(server.join().unwrap() > 0, "No HTTP request for {variable}"); + assert!(!timed_out, "Clone hung with {variable}"); + assert!( + output.status.success(), + "{variable}: {}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + if marker.exists() { + invoked.push(variable); + } + } + assert!(invoked.is_empty(), "Inherited askpass invoked: {invoked:?}"); + } + + #[test] + fn clone_helper_reports_git_failures() { + let directory = tempfile::tempdir().unwrap(); + let error = clone_repository( + directory.path().join("missing").to_str().unwrap(), + &directory.path().join("checkout"), + ) + .unwrap_err(); + assert!(error.to_string().contains("git clone failed")); + } + + #[test] + fn loads_relative_skill_files_against_the_definition_directory() { + let base = tempfile::tempdir().unwrap(); + write_skill(base.path(), "guide/SKILL.md", "guide"); + + let skills = load(&["file://guide/SKILL.md".into()], base.path()).unwrap(); + + assert_eq!(skills[0].name, "guide"); + assert_eq!( + skills[0].instructions, + "---\nname: guide\ndescription: A useful skill\n---\nFollow these instructions.\n" + ); + } +} diff --git a/src/tools.rs b/src/tools.rs index 7020f26..4f5f3dd 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -5,6 +5,25 @@ use rig_agent::tool::server::{ToolServer, ToolServerHandle}; use rig_tools::{List, Read, Search, workspace::Root}; pub fn load(workspace: &Path) -> Result { + select(workspace, &[]) +} + +pub fn select(workspace: &Path, names: &[String]) -> Result { + let registered = ["read", "list", "search"]; + let mut selected = [names.is_empty(); 3]; + for name in names { + if name.eq_ignore_ascii_case("all") { + selected.fill(true); + } else if let Some(index) = registered + .iter() + .position(|registered| name.eq_ignore_ascii_case(registered)) + { + selected[index] = true; + } else { + anyhow::bail!("Unknown tool: {name}"); + } + } + let base = workspace .canonicalize() .with_context(|| format!("Cannot resolve workspace {}", workspace.display()))?; @@ -19,14 +38,20 @@ pub fn load(workspace: &Path) -> Result { ..Root::default() }; - Ok(ToolServer::new() - .tool(Read { + let mut server = ToolServer::new(); + if selected[0] { + server = server.tool(Read { root: root.clone(), ..Read::default() - }) - .tool(List { root: root.clone() }) - .tool(Search { root }) - .run()) + }); + } + if selected[1] { + server = server.tool(List { root: root.clone() }); + } + if selected[2] { + server = server.tool(Search { root }); + } + Ok(server.run()) } #[cfg(test)] @@ -46,6 +71,58 @@ mod tests { ); } + #[test] + fn selects_a_subset_in_registered_order() { + let workspace = tempfile::tempdir().unwrap(); + let tools = select(workspace.path(), &["search".into(), "read".into()]) + .unwrap() + .toolset(); + + assert_eq!(tools.names().collect::>(), ["read", "search"]); + } + + #[test] + fn empty_selection_and_all_preserve_every_registered_tool() { + let workspace = tempfile::tempdir().unwrap(); + for names in [ + vec![], + vec!["ALL".into()], + vec!["search".into(), "aLl".into()], + ] { + let tools = select(workspace.path(), &names).unwrap().toolset(); + assert_eq!( + tools.names().collect::>(), + ["read", "list", "search"] + ); + } + } + + #[test] + fn selection_is_case_insensitive_and_deduplicated() { + let workspace = tempfile::tempdir().unwrap(); + let tools = select( + workspace.path(), + &["LiSt".into(), "READ".into(), "list".into(), "Read".into()], + ) + .unwrap() + .toolset(); + + assert_eq!(tools.names().collect::>(), ["read", "list"]); + } + + #[test] + fn rejects_unknown_names_even_when_mixed_with_all() { + let workspace = tempfile::tempdir().unwrap(); + for names in [ + vec!["unknown".into()], + vec!["ALL".into(), "unknown".into()], + vec!["unknown".into(), "ALL".into()], + ] { + let error = select(workspace.path(), &names).err().unwrap(); + assert_eq!(error.to_string(), "Unknown tool: unknown"); + } + } + #[test] fn rejects_a_missing_workspace() { let workspace = tempfile::tempdir().unwrap(); @@ -64,22 +141,25 @@ mod tests { let workspace = parent.path().join("workspace"); std::fs::create_dir(&workspace).unwrap(); std::fs::write(parent.path().join("outside.txt"), "private\n").unwrap(); - let tools = load(&workspace).unwrap().toolset(); - for (name, args) in [ ("read", json!({"path": "../outside.txt"})), ("list", json!({"path": ".."})), ("search", json!({"path": "..", "pattern": "private"})), ] { - let result = tools - .get(name) - .unwrap() - .execute(args.to_string(), &mut ToolContext::default()) - .await; - assert!( - result.is_error_kind(ToolErrorKind::PermissionDenied), - "{name}: {result:?}" - ); + for tools in [ + load(&workspace).unwrap().toolset(), + select(&workspace, &[name.into()]).unwrap().toolset(), + ] { + let result = tools + .get(name) + .unwrap() + .execute(args.to_string(), &mut ToolContext::default()) + .await; + assert!( + result.is_error_kind(ToolErrorKind::PermissionDenied), + "{name}: {result:?}" + ); + } } } } diff --git a/tests/agent_runtime.rs b/tests/agent_runtime.rs new file mode 100644 index 0000000..4f0c87c --- /dev/null +++ b/tests/agent_runtime.rs @@ -0,0 +1,161 @@ +use std::{ + fs, + io::{BufRead, BufReader, Read, Write}, + net::TcpListener, + process::Command, + thread, + time::{Duration, Instant}, +}; + +use serde_json::{Value, json}; + +fn request_from_cli(overrides: &[&str]) -> Value { + let directory = tempfile::tempdir().unwrap(); + let home = directory.path().join("home"); + let workspace = directory.path().join("workspace"); + let definitions = directory.path().join("definitions"); + fs::create_dir_all(home.join(".pi/agent")).unwrap(); + fs::create_dir_all(workspace.join("guide")).unwrap(); + fs::create_dir_all(definitions.join("guide")).unwrap(); + fs::write(definitions.join("instructions.md"), "YAML instructions.").unwrap(); + fs::write(workspace.join("override.md"), "CLI instructions.").unwrap(); + fs::write( + definitions.join("guide/SKILL.md"), + "---\nname: yaml-skill\ndescription: Test YAML loading\n---\nYAML skill instructions.\n", + ) + .unwrap(); + fs::write( + workspace.join("guide/SKILL.md"), + "---\nname: cli-skill\ndescription: Test CLI loading\n---\nCLI skill instructions.\n", + ) + .unwrap(); + let definition = definitions.join("agent.yaml"); + fs::write(&definition, "name: yaml-agent\nmodel: mock/model\ntools: [Read]\nagentfile: instructions.md\nskills: [file://guide]\n").unwrap(); + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + fs::write( + home.join(".pi/agent/models.json"), + json!({ + "providers": {"mock": { + "baseUrl": format!("http://{}/v1", listener.local_addr().unwrap()), + "api": "openai-completions", "apiKey": "test-key", "models": [{"id": "model"}] + }} + }) + .to_string(), + ) + .unwrap(); + listener.set_nonblocking(true).unwrap(); + let server = thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(60); + let (mut socket, _) = loop { + match listener.accept() { + Ok(connection) => break connection, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + assert!(Instant::now() < deadline, "CLI never contacted the model"); + thread::sleep(Duration::from_millis(10)); + } + Err(error) => panic!("Could not accept model request: {error}"), + } + }; + socket + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut reader = BufReader::new(&socket); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + assert_eq!(line, "POST /v1/chat/completions HTTP/1.1\r\n"); + let mut length = 0; + loop { + line.clear(); + assert_ne!(reader.read_line(&mut line).unwrap(), 0); + if line == "\r\n" { + break; + } + if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") { + length = value.trim().parse().unwrap(); + } + } + let mut body = vec![0; length]; + reader.read_exact(&mut body).unwrap(); + let request: Value = serde_json::from_slice(&body).unwrap(); + let response = json!({ + "id": "chat-1", "object": "chat.completion", "created": 0, "model": "model", + "choices": [{"index": 0, "finish_reason": "stop", + "message": {"role": "assistant", "content": "Ready"}}] + }) + .to_string(); + write!(socket, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", response.len(), response).unwrap(); + request + }); + let output = Command::new(env!("CARGO_BIN_EXE_killall-agent")) + .current_dir(&workspace) + .env("HOME", &home) + .env("NO_PROXY", "127.0.0.1,localhost") + .env("no_proxy", "127.0.0.1,localhost") + .arg("--agent") + .arg(definition) + .args(["--prompt", "Inspect this project"]) + .args(overrides) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(String::from_utf8(output.stdout).unwrap().trim(), "Ready"); + server.join().unwrap() +} + +#[test] +#[ignore = "fetches a public GitHub repository"] +fn github_skill_instructions_reach_the_actual_model_request() { + let request = request_from_cli(&[ + "--skills", + "github://killallgit/killall-skills/skills/parse-dont-validate", + ]); + + let instructions = request["messages"][0]["content"][0]["text"] + .as_str() + .unwrap(); + assert!(instructions.contains("# Skill: parse-dont-validate")); + assert!(!instructions.contains("YAML skill instructions.")); +} + +#[test] +fn yaml_resources_are_present_in_the_actual_model_request() { + let request = request_from_cli(&[]); + + let instructions = request["messages"][0]["content"][0]["text"] + .as_str() + .unwrap(); + assert!(instructions.contains("yaml-agent")); + assert!(instructions.contains("YAML instructions.")); + assert!(instructions.contains("YAML skill instructions.")); + assert_eq!(request["tools"].as_array().unwrap().len(), 1); + assert_eq!(request["tools"][0]["function"]["name"], "read"); +} + +#[test] +fn cli_resource_overrides_replace_yaml_resources_in_the_actual_model_request() { + let request = request_from_cli(&[ + "--name", + "cli-agent", + "--tools", + "Search", + "--agentfile", + "override.md", + "--skills", + "file://guide", + ]); + + let instructions = request["messages"][0]["content"][0]["text"] + .as_str() + .unwrap(); + assert!(instructions.contains("cli-agent")); + assert!(instructions.contains("CLI instructions.")); + assert!(instructions.contains("CLI skill instructions.")); + assert!(!instructions.contains("YAML")); + assert_eq!(request["tools"].as_array().unwrap().len(), 1); + assert_eq!(request["tools"][0]["function"]["name"], "search"); +} diff --git a/tests/runtime.rs b/tests/runtime.rs new file mode 100644 index 0000000..9d08ee3 --- /dev/null +++ b/tests/runtime.rs @@ -0,0 +1,81 @@ +use std::fs; + +use killall_agent::{definition, runtime}; +use rig_agent::AgentBuilder; +use rig_core::test_utils::{MockCompletionModel, MockTurn}; + +#[tokio::test] +async fn definition_resources_reach_the_model_without_changing_the_workspace() { + let directory = tempfile::tempdir().unwrap(); + let definitions = directory.path().join("definitions"); + let workspace = directory.path().join("workspace"); + fs::create_dir_all(definitions.join("skills/explain")).unwrap(); + fs::create_dir(&workspace).unwrap(); + fs::write( + definitions.join("instructions.md"), + "Explain the reasoning first.", + ) + .unwrap(); + fs::write( + definitions.join("skills/explain/SKILL.md"), + "---\nname: explain\ndescription: Explain unfamiliar code\n---\nUse a concrete example.\n", + ) + .unwrap(); + let path = definitions.join("agent.yaml"); + fs::write( + &path, + "name: code-reader\nmodel: test/model\ntools: [Read]\nagentfile: instructions.md\nskills: [file://skills]\n", + ) + .unwrap(); + let definition = definition::load(&path).unwrap(); + let resources = runtime::load(&definition, &definitions, &workspace).unwrap(); + let model = MockCompletionModel::from_turns([MockTurn::text("Ready")]); + let agent = AgentBuilder::new(model.clone()) + .tool_server_handle(resources.tools) + .preamble(resources.instructions) + .build(); + + agent.prompt("Explain this code").await.unwrap(); + + let requests = model.requests(); + let request = &requests[0]; + assert_eq!( + request + .tools + .iter() + .map(|tool| tool.name.as_str()) + .collect::>(), + ["read"] + ); + let instructions = request.system_instructions().unwrap(); + assert!(instructions.contains("code-reader")); + assert!(instructions.contains("Explain the reasoning first.")); + assert!(instructions.contains("Use a concrete example.")); + assert!(instructions.contains("read-only")); + assert!( + instructions.find("Explain the reasoning first.").unwrap() + < instructions.find("Use a concrete example.").unwrap() + ); + assert!(workspace.read_dir().unwrap().next().is_none()); +} + +#[test] +fn missing_agent_instructions_report_the_underlying_io_error() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("agent.yaml"); + fs::write( + &path, + "name: reader\nmodel: test/model\nagentfile: missing.md\n", + ) + .unwrap(); + let definition = definition::load(&path).unwrap(); + + let error = runtime::load(&definition, directory.path(), directory.path()) + .err() + .unwrap(); + + assert_eq!( + error.downcast_ref::().unwrap().kind(), + std::io::ErrorKind::NotFound + ); +} diff --git a/tests/tools.rs b/tests/tools.rs index d0deff1..4796f25 100644 --- a/tests/tools.rs +++ b/tests/tools.rs @@ -1,17 +1,20 @@ -use std::path::Path; - use killall_agent::tools; -use rig_agent::AgentBuilder; +use rig_agent::{AgentBuilder, tool::server::ToolServerHandle}; use rig_core::test_utils::{MockCompletionModel, MockTurn}; use serde_json::{Value, json}; -async fn run_tool(workspace: &Path, name: &str, args: Value) -> String { +async fn run_tool( + server: ToolServerHandle, + name: &str, + args: Value, + expected_tools: &[&str], +) -> String { let model = MockCompletionModel::from_turns([ MockTurn::tool_call("tool-call", name, args), MockTurn::text("Inspection complete"), ]); let agent = AgentBuilder::new(model.clone()) - .tool_server_handle(tools::load(workspace).unwrap()) + .tool_server_handle(server) .default_max_turns(2) .build(); @@ -26,7 +29,7 @@ async fn run_tool(workspace: &Path, name: &str, args: Value) -> String { .iter() .map(|tool| tool.name.as_str()) .collect::>(), - ["read", "list", "search"] + expected_tools ); let results = requests[1] .chat_history @@ -51,7 +54,13 @@ async fn read_returns_workspace_file_contents_to_the_model() { let workspace = tempfile::tempdir().unwrap(); std::fs::write(workspace.path().join("sample.txt"), "workspace content\n").unwrap(); - let output = run_tool(workspace.path(), "read", json!({"path": "sample.txt"})).await; + let output = run_tool( + tools::load(workspace.path()).unwrap(), + "read", + json!({"path": "sample.txt"}), + &["read", "list", "search"], + ) + .await; assert!(output.contains("workspace content"), "{output}"); } @@ -61,7 +70,13 @@ async fn list_returns_workspace_entries_to_the_model() { let workspace = tempfile::tempdir().unwrap(); std::fs::write(workspace.path().join("sample.txt"), "content\n").unwrap(); - let output = run_tool(workspace.path(), "list", json!({"path": "."})).await; + let output = run_tool( + tools::load(workspace.path()).unwrap(), + "list", + json!({"path": "."}), + &["read", "list", "search"], + ) + .await; assert!(output.contains("sample.txt"), "{output}"); } @@ -73,9 +88,10 @@ async fn search_returns_workspace_matches_to_the_model() { std::fs::write(workspace.path().join("unrelated.txt"), "no match here\n").unwrap(); let output = run_tool( - workspace.path(), + tools::load(workspace.path()).unwrap(), "search", json!({"pattern": "needle", "path": "."}), + &["read", "list", "search"], ) .await; @@ -83,3 +99,77 @@ async fn search_returns_workspace_matches_to_the_model() { assert!(output.contains("distinctive needle"), "{output}"); assert!(!output.contains("unrelated.txt"), "{output}"); } + +#[tokio::test] +async fn selected_tools_are_the_only_tools_exposed_to_the_model() { + let workspace = tempfile::tempdir().unwrap(); + std::fs::write(workspace.path().join("sample.txt"), "workspace content\n").unwrap(); + + for (name, args, expected) in [ + ("read", json!({"path": "sample.txt"}), "workspace content"), + ("list", json!({"path": "."}), "sample.txt"), + ( + "search", + json!({"pattern": "content", "path": "."}), + "workspace content", + ), + ] { + let output = run_tool( + tools::select(workspace.path(), &[name.to_uppercase()]).unwrap(), + name, + args, + &[name], + ) + .await; + + assert!(output.contains(expected), "{name}: {output}"); + } +} + +#[tokio::test] +async fn selected_tools_report_workspace_escape_errors_to_the_model() { + let parent = tempfile::tempdir().unwrap(); + let workspace = parent.path().join("workspace"); + std::fs::create_dir(&workspace).unwrap(); + std::fs::write(parent.path().join("outside.txt"), "private content\n").unwrap(); + + for (name, args) in [ + ("read", json!({"path": "../outside.txt"})), + ("list", json!({"path": ".."})), + ("search", json!({"pattern": "private", "path": ".."})), + ] { + let model = MockCompletionModel::from_turns([ + MockTurn::tool_call("escape", name, args), + MockTurn::text("Access refused"), + ]); + let agent = AgentBuilder::new(model.clone()) + .tool_server_handle(tools::select(&workspace, &[name.into()]).unwrap()) + .default_max_turns(2) + .build(); + + assert_eq!( + agent + .prompt("Inspect the parent directory") + .await + .unwrap() + .to_string(), + "Access refused" + ); + let requests = model.requests(); + let results = requests[1] + .chat_history + .iter() + .flat_map(|message| message.results()) + .collect::>(); + assert_eq!(results.len(), 1); + assert!(results[0].is_error, "{name}: {:?}", results[0]); + assert!( + results[0] + .content + .iter() + .all(|content| !content.to_text("image").contains("private content")), + "{name}: {:?}", + results[0] + ); + } +}