diff --git a/AGENTS.md b/AGENTS.md index 11f825a..0a4505f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,7 +17,7 @@ Anything else gets a qualified lowercase name, such as Rust's built-in test harn ## The contract's rules - `crates/runvil-plugin-sys/src/lib.rs` is the single source of the contract. `crates/runvil-plugin-sys/include/runvil_plugin.h` is generated from it by `cargo xtask header` and never edited by hand; its crate docs, up to `## Invariants`, become the header's opening comment. -- A status code, verb, result kind, file type, file error kind, tool flag, or field keeps its number and position in every version. A reserved verb number is never reused for anything else. +- A status code, verb, result kind, file type, file error kind, or field keeps its number and position in every version. A reserved verb number is never reused for anything else. - The `runvil-plugin-sys` version is the contract's version, `RV_API_MAJOR`.`RV_API_MINOR`; a unit test checks it. Changing the contract means changing both. - While the major version is 0, each version is its own contract, and the SDK accepts only a Host that reports exactly its version. From 1.0, a minor version only adds, at the end of a struct, or as a new verb with an arguments struct of its own. - `RvHost` holds only what is true on every call. Each function a Plugin may call back belongs to one verb and sits in that verb's arguments struct, beside the `ctx` it takes first, under that verb's own lifetime and thread rules. `wake` is the one exception: it sits in the `RvWaker` of a tool call, beside the waker's own `ctx`, which it takes, and the Plugin may call it on any thread until `RV_PLUGIN_UNLOAD` returns. @@ -25,14 +25,14 @@ Anything else gets a qualified lowercase name, such as Rust's built-in test harn - A step that returns `RV_PENDING` parks its call. The Host sends the next step after the Plugin wakes the call, or when the answer to the step's file request is ready, and it sends no step while that answer is outstanding. `wake` only notes the wake and returns nothing, so a Plugin may call it while it holds a lock. - The SDK polls a call's future with a waker over the Host's `RvWaker`. That waker takes no lock and never lets go of the Host's, because the Host keeps it valid until the unload. A future that returns `Pending` without arranging a wake, and without a file request, parks for good. The SDK itself wakes a call only in `next_step`, and when the Host refuses a file request, whose failure no answer would bring. - The contract stays minimal. A verb, a field, or a function joins only when a Plugin that exists needs it, and each one says who calls it, on which thread, how long what it passes stays valid, and who frees what. -- A render shapes what a model is shown and keeps nothing. `RV_PACK_RENDER` lends a Pack instance the tools a section offered from it and the model that will read them, and takes back the tools the model is shown through `add_tool`. A tool added under an offered tool's name keeps that tool's parameters, so one catalog name always means one parameter schema, and a tool with other parameters is a model-facing tool under a name of its own, which no script can name. A Plugin that does not render answers `RV_ERR_UNSUPPORTED`, and the model is shown the offered tools as they are without any answer being read. The SDK's default `Pack::render` is not that answer: it lists the offered tools through `add_tool`, so the Host checks them like any other list. -- JSON crosses the contract as text. Neither crate here parses it, so neither needs a JSON library. +- A render shapes what a model is shown and keeps nothing. `RV_PACK_RENDER` lends a Pack instance the tools a section offered from it and the model that will read them, and takes back the tools the model is shown through `add_tool`. A tool added under an offered tool's name keeps that tool's `input_schema`, so one catalog name always means one input schema, and a tool with another `input_schema` is a model-facing tool under a name of its own, which no script can name. A Plugin that does not render answers `RV_ERR_UNSUPPORTED`, and the model is shown the offered tools as they are without any answer being read. The SDK's default `Pack::render` is not that answer: it lists the offered tools through `add_tool`, so the Host checks them like any other list. +- JSON crosses the C contract as UTF-8 text (`RvStr`), including `ToolInfo` JSON in `RvToolInfo`. `runvil-plugin-sys` parses nothing and has zero dependencies; `runvil-plugin-sdk` serializes and deserializes `ToolInfo` with `serde_json`. - The Host's resources can hold a key. The SDK copies their text on a call's first step into one private type whose `Debug` prints none of it, and no message here quotes it. - A tool reaches its run's files only through the file functions of its step, so the run's policy applies to every operation. A file function only takes a request, and the call's next step receives the answer. The answer belongs to the Host and is valid for that step alone, so the SDK copies it before it polls the tool's future. - Every file function has that one form, a request in one step and its answer in the next, whether it reads a file or changes one, so that the Harness can perform each file operation of a tool as an effect and record it. The file methods of the SDK return futures. -- `runvil-plugin-sys` has no dependencies and no `unsafe`. `runvil-plugin-sdk` depends on `runvil-plugin-sys` alone. Neither ever depends on an Engine or Harness crate. +- `runvil-plugin-sys` has no dependencies and no `unsafe`. `runvil-plugin-sdk` depends on `runvil-plugin-sys`, `serde`, and `serde_json`, and `crates/runvil-plugin-sdk/src/tool_info.rs` stays synced byte for byte with `gateway-types`'s `tool.rs` via `cargo xtask sync-tool-info`. Neither crate ever depends on an Engine or Harness crate. - A Plugin shares its process with the Host, so nothing here installs process-global state, such as a panic hook (`clippy.toml` bans `std::panic::set_hook`), and no panic ever unwinds across the C boundary. -- `testing` in the SDK checks a Plugin's calls the way the Harness's loader does: the same order of checks, the same bounds, the same rules on names, versions, and tool infos, and the same words for each misuse. It parks a call as the loader does too: a step answers the wakes that came before it began, the next step is due after a wake or as soon as a file answer is ready, and what a waker points at is kept until the Plugin is unloaded. It checks a render as the Engine's merge does, with one difference: it compares the parameters of a catalog tool as text, because this crate has no JSON library, so it is stricter than the Engine. When the loader's checks change, this changes with them. +- `testing` in the SDK checks a Plugin's calls the way the Harness's loader does: the same order of checks, the same bounds, the same rules on names, versions, and tool infos, and the same words for each misuse. It parks a call as the loader does too: a step answers the wakes that came before it began, the next step is due after a wake or as soon as a file answer is ready, and what a waker points at is kept until the Plugin is unloaded. It checks a render as the Engine's merge does, comparing a catalog tool's `input_schema` as a JSON `Value`. When the loader's checks change, this changes with them. ## Engineering diff --git a/Cargo.lock b/Cargo.lock index 33024e8..5bf84fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -113,6 +113,7 @@ name = "hello-plugin" version = "0.1.0" dependencies = [ "runvil-plugin-sdk", + "serde_json", ] [[package]] @@ -187,14 +188,16 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "runvil-plugin-sdk" -version = "0.8.0" +version = "0.9.0" dependencies = [ "runvil-plugin-sys", + "serde", + "serde_json", ] [[package]] name = "runvil-plugin-sys" -version = "0.8.0" +version = "0.9.0" [[package]] name = "rustix" diff --git a/Cargo.toml b/Cargo.toml index 610408f..75a1a1f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,8 @@ repository = "https://github.com/cppalliance/runvil-plugin-api" [workspace.dependencies] runvil-plugin-sys = { path = "crates/runvil-plugin-sys" } runvil-plugin-sdk = { path = "crates/runvil-plugin-sdk" } +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["float_roundtrip"] } # Generates `runvil_plugin.h` for `cargo xtask header`. default-features off # drops the `clap` command line, which the xtask does not use. cbindgen = { version = "0.29", default-features = false } diff --git a/README.md b/README.md index d87d524..ea0628d 100644 --- a/README.md +++ b/README.md @@ -35,10 +35,11 @@ edition = "2024" crate-type = ["cdylib"] [dependencies] -runvil-plugin-sdk = { git = "https://github.com/cppalliance/runvil-plugin-api", tag = "api-v0.8.0" } +runvil-plugin-sdk = { git = "https://github.com/cppalliance/runvil-plugin-api", tag = "api-v0.9.0" } +serde_json = "1" [dev-dependencies] -runvil-plugin-sdk = { git = "https://github.com/cppalliance/runvil-plugin-api", tag = "api-v0.8.0", features = ["test-support"] } +runvil-plugin-sdk = { git = "https://github.com/cppalliance/runvil-plugin-api", tag = "api-v0.9.0", features = ["test-support"] } ``` `src/lib.rs`: @@ -74,7 +75,7 @@ impl Pack for Greeter { vec![ToolInfo::new( "greet", "Returns a greeting.", - r#"{"type":"object","properties":{}}"#, + serde_json::json!({"type": "object", "properties": {}}), )] } @@ -89,45 +90,44 @@ export_plugin!(Acme); `cargo build --release` writes `acme_plugin.dll` (Windows), `libacme_plugin.so` (Linux), or `libacme_plugin.dylib` (macOS) to `target/release`. That one file goes in the Host's Plugin directory. `examples/hello-plugin` is a complete Plugin with tests. - The Plugin's name and version, and the name and description of each Pack, are checked when the Plugin is compiled: one the Harness would reject fails the build, with a message naming the rule. -- The Pack's name is a vendor and a Pack id joined by `/`. A prompt reaches the tool above as `hello/greet`, the Pack id and the tool's name. A model calls it by its wire name, which is `hello_greet` unless `ToolInfo::wire_name` sets another. -- Arguments and parameter schemas cross as JSON text, so the SDK needs no JSON library. A Plugin parses `call.arguments()` with one of its own. +- The Pack's name is a vendor and a Pack id joined by `/`. A prompt reaches the tool above as `hello/greet`, the Pack id and the tool's name. A model calls it by its wire name, which is `hello_greet` unless `ToolInfo::with_wire_name` sets another. +- `ToolInfo` holds the tool's `input_schema` (and optional `output_schema`) as `serde_json::Value`, along with optional title, MCP hints, and execution flags, and crosses the C ABI as compact JSON text inside `RvToolInfo`. Tool call arguments cross as JSON text, which a Plugin parses from `call.arguments()`. - `call.caller()` says whether a model round (`Caller::Model`) or a section's Lua script (`Caller::Script`) asked for the call. `call.section()` names the section that made the call, `call.entry()` is the section entry (`sys.id`) when the Host names one, and `call.model()` is the JSON text describing the model of the round that asked for the call, or `None` on a script call. - `call.resources()` is what the Host offers every Plugin, such as the address and the key of a service: the JSON text of an object keyed by resource name, as it was when the call started, and `{}` when the Host offers nothing. A Plugin parses it the same way. It can hold a key, so no `Debug` in the SDK prints it, and a Plugin puts none of it in an output or a failure. - A tool call is a future the Host polls once per step. A `Pending` parks the call, and the Host sends the next step when the future's waker is woken. So a call may wait on a waker like any Rust future: on a timer, a channel, or a task on a runtime the Plugin owns. A future that returns `Pending` without arranging a wake, and without a file request, parks for good. A call that does a long job awaits `next_step()` every so often, which ends the step and wakes the call for the next one, so that no step works for long and the Host can abandon the call between two steps. - A tool reaches the files of its run through its `ToolCall`. `stat`, `list`, `read`, and `read_range` read them, and `write`, `append`, `mkdir`, `remove`, `rename`, and `copy` change them. Each returns a future, as in `call.read(path).await`. Awaiting it ends the step with a request to the Host, and a later step goes on with the answer, so the run's policy applies to every operation. An operation that fails resolves to a `FileError` with a kind and the Host's words for what went wrong, and the call goes on, so the tool decides what the model reads. An answer comes only with a step, so a file method is awaited inside the future that `Pack::call` returns. A file future gets its answer only when a step polls it, so it does not work inside a set that polls a child only after that child's waker fired, such as `FuturesUnordered`. -- A tool that changes files says so with `ToolInfo::changes_files()`. Of the calls one reply of a model asks for, the Host runs a call of such a tool by itself, so two changes of one reply happen in the order the reply lists them. +- A tool that changes files says so with `ToolInfo::with_changes_files(true)`. Of the calls one reply of a model asks for, the Host runs a call of such a tool by itself, so two changes of one reply happen in the order the reply lists them. - A panic in `load`, `new_pack`, or `render` reaches the Host as a refusal, and a panic in a tool call ends that call as a failure. None unwinds into the Host. ### Catalog tools and model-facing tools -A tool a Pack lists when its instance is made, with `tools`, is a **catalog tool**. A prompt's Lua can call it by its id, such as `fs/edit`, a section offers it to a model with `tools.offer("fs/edit")` or offers the whole Pack with `tools.offer("fs")`, and its parameters are the same for the whole run, so a prompt author can read them in the Host's docs. +A tool a Pack lists when its instance is made, with `tools`, is a **catalog tool**. A prompt's Lua can call it by its id, such as `fs/edit`, a section offers it to a model with `tools.offer("fs/edit")` or offers the whole Pack with `tools.offer("fs")`, and its input schema is the same for the whole run, so a prompt author can read it in the Host's docs. Models are trained on particular tool shapes. A Claude model expects a string-replace tool, and an OpenAI model expects a tool that takes a diff. A section is one heading of a prompt, a section entry is one run of it, and its tools come in two sets: the ones every round of the section sends, and the ones the model finds through two discovery tools. A Pack shows each model the shape it was trained on with `Pack::render`, which the Host calls when a section entry's first model round is about to advertise its tools. `render` gets the section entry, the model as JSON text, and the catalog tools the section offered, and returns the tools the model is shown. The Host keeps that answer for the whole section entry. - A tool the Pack leaves out of the answer is not shown to the model. -- A tool the Pack lists under the `name` of an offered tool is that catalog tool. It may take another `wire_name` and `description`, and its `parameters` stay as offered. So one catalog name always means one parameter schema, and Lua can still call the tool by its id. -- A tool the Pack lists under a name that no tool of its catalog has is a **model-facing tool**. Only a model calls it, and no script can name it. It is how a model sees other parameters than the catalog's: the Pack lists it under a name of its own, and `Pack::call` answers its calls by that name. A catalog tool the section did not offer in this set may not be listed under its own name. +- A tool the Pack lists under the `name` of an offered tool is that catalog tool. It may take another `wire_name`, `description`, or metadata, and its `input_schema` stays equal to the offered schema. So one catalog name always means one input schema, and Lua can still call the tool by its id. +- A tool the Pack lists under a name that no tool of its catalog has is a **model-facing tool**. Only a model calls it, and no script can name it. It is how a model sees another `input_schema` than the catalog's: the Pack lists it under a name of its own, and `Pack::call` answers its calls by that name. A catalog tool the section did not offer in this set may not be listed under its own name. -For example, a Pack `acme/fs` lists the catalog tool `edit`, which takes `path`, `old`, and `new`. For a Claude model it renders `edit` out and lists a model-facing tool `str_replace` with the wire name `str_replace_based_edit_tool` and the parameters that model was trained on. For an OpenAI model it lists `apply_patch`, with one parameter that holds a diff. Every other model sees `edit` as it is, which is the default. A model-facing tool that changes files says so with `ToolInfo::changes_files()`, because the Host does not copy that flag from the catalog. +For example, a Pack `acme/fs` lists the catalog tool `edit`, which takes `path`, `old`, and `new`. For a Claude model it renders `edit` out and lists a model-facing tool `str_replace` with the wire name `str_replace_based_edit_tool` and the parameters that model was trained on. For an OpenAI model it lists `apply_patch`, with one parameter that holds a diff. Every other model sees `edit` as it is, which is the default. A model-facing tool that changes files says so with `ToolInfo::with_changes_files(true)`, because the Host does not copy that flag from the catalog. ```rust fn render(&self, cx: &RenderContext<'_>, offered: Vec) -> Result, Refusal> { - // `serde_json` is the Plugin's own JSON library; the SDK has none. let model = serde_json::from_str::(cx.model).unwrap_or_default(); if !model["name"].as_str().unwrap_or_default().contains("claude") { return Ok(offered); } let mut shown: Vec = offered.into_iter().filter(|tool| tool.name != "edit").collect(); shown.push( - ToolInfo::new("str_replace", "Replace one exact string in a file.", STR_REPLACE_SCHEMA) - .wire_name("str_replace_based_edit_tool") - .changes_files(), + ToolInfo::new("str_replace", "Replace one exact string in a file.", str_replace_schema()) + .with_wire_name("str_replace_based_edit_tool") + .with_changes_files(true), ); Ok(shown) } ``` -`STR_REPLACE_SCHEMA` stands for the JSON text of that tool's parameters. A prompt names catalog ids only, and its prose describes a tool by what it does and not by the name a model sees. A prompt that offers a Pack trusts that Pack's render to choose the model-facing tools, so a Plugin that needs a prompt to offer reading without editing inserts two Packs. +`str_replace_schema()` returns the `serde_json::Value` object for that tool's input schema. A prompt names catalog ids only, and its prose describes a tool by what it does and not by the name a model sees. A prompt that offers a Pack trusts that Pack's render to choose the model-facing tools, so a Plugin that needs a prompt to offer reading without editing inserts two Packs. ### Testing @@ -171,7 +171,7 @@ let shown = pack.render("entry-1", r#"{"name":"claude-x"}"#, pack.tools()).unwra assert_eq!(shown[0].wire_name.as_deref(), Some("str_replace_based_edit_tool")); ``` -It checks each listed tool as the Harness does, and then the render as a whole: a catalog tool must keep its offered `parameters`, a tool of the instance the section did not offer in this set may not be listed, and no two tools may show one wire name. A broken rule is a `Failure::Rejected` whose text names the tool. The fake Host compares `parameters` as text, which is stricter than the Harness, which compares the JSON they hold. A render that lists the offered `ToolInfo` with another wire name or description passes both. A model-facing tool that a render listed is then called with `PackRun::call` under the name it was listed under, as a model calls it. +It checks each listed tool as the Harness does, and then the render as a whole: a catalog tool must keep its offered `input_schema` (compared as JSON values, matching the Harness), a tool of the instance the section did not offer in this set may not be listed, and no two tools may show one wire name. A broken rule is a `Failure::Rejected` whose text names the tool. A render that lists the offered `ToolInfo` with another wire name, description, or metadata passes. A model-facing tool that a render listed is then called with `PackRun::call` under the name it was listed under, as a model calls it. ### Linked and library builds of one Plugin @@ -183,7 +183,7 @@ Include `runvil_plugin.h` and define `RvStatus runvil_plugin(RvCall *call)`. The ## Versions -The contract's version is `RV_API_MAJOR`.`RV_API_MINOR`, and `runvil-plugin-sys` has the same version number. While the major version is 0, each version is its own contract, so a Plugin built for 0.8 loads only in a Host that speaks exactly 0.8. From 1.0, minor versions only add, and a Plugin built for 1.n loads in any Host that speaks 1.n or later. +The contract's version is `RV_API_MAJOR`.`RV_API_MINOR`, and `runvil-plugin-sys` has the same version number. While the major version is 0, each version is its own contract, so a Plugin built for 0.9 loads only in a Host that speaks exactly 0.9. From 1.0, minor versions only add, and a Plugin built for 1.n loads in any Host that speaks 1.n or later. Cargo allows one package per `links` value in a build, and `runvil-plugin-sys` sets `links = "runvil_plugin"`, so a Host can never link two versions of the contract into one binary. @@ -198,6 +198,7 @@ Cargo allows one package per `links` value in a build, and `runvil-plugin-sys` s |---|---| | Regenerate the header after editing `crates/runvil-plugin-sys/src/lib.rs` | `cargo xtask header` | | Check the header is current | `cargo xtask header --check` (also part of `cargo test`) | +| Sync `tool_info.rs` from sibling `gateway-client` | `cargo xtask sync-tool-info` (`--check` to verify) | | Test, including the C and C++ layout check | `cargo test --workspace --all-features` | | Lint | `cargo clippy --workspace --all-targets --all-features` | diff --git a/crates/build-xtask/src/main.rs b/crates/build-xtask/src/main.rs index 2c7add1..377f20b 100644 --- a/crates/build-xtask/src/main.rs +++ b/crates/build-xtask/src/main.rs @@ -1,13 +1,22 @@ -//! `build-xtask` - automation for this repository. `cargo xtask header` -//! writes `runvil_plugin.h` from `runvil-plugin-sys`, and `--check` fails -//! when the committed header differs from what it would write. +//! `build-xtask` - automation for this repository. +//! +//! - `cargo xtask header` writes `runvil_plugin.h` from `runvil-plugin-sys`, +//! and `--check` fails when the committed header differs from what it would +//! write. +//! - `cargo xtask sync-tool-info` copies `tool.rs` from a sibling +//! `gateway-client` checkout into `crates/runvil-plugin-sdk/src/tool_info.rs`, +//! and `--check` fails when the two files differ. //! //! ## Invariants //! //! - The header's only source is `crates/runvil-plugin-sys/src/lib.rs`; //! `cargo test -p build-xtask` fails when the committed header is stale. +//! - When a sibling `gateway-client` checkout is present on disk, +//! `cargo test -p build-xtask` fails if `tool_info.rs` drifts from +//! `gateway-client/crates/gateway-types/src/tool.rs`. mod header; +mod sync_tool_info; use std::path::Path; use std::process::ExitCode; @@ -20,11 +29,12 @@ fn main() -> ExitCode { }; match args.get(1).map(String::as_str) { Some("header") => header::run(root, &args[2..]), + Some("sync-tool-info") => sync_tool_info::run(root, &args[2..]), _ => usage(), } } fn usage() -> ExitCode { - eprintln!("usage: cargo xtask header [--check]"); + eprintln!("usage: cargo xtask [--check]"); ExitCode::from(2) } diff --git a/crates/build-xtask/src/sync_tool_info.rs b/crates/build-xtask/src/sync_tool_info.rs new file mode 100644 index 0000000..920d959 --- /dev/null +++ b/crates/build-xtask/src/sync_tool_info.rs @@ -0,0 +1,103 @@ +//! `cargo xtask sync-tool-info [--check]`: copies +//! `../gateway-client/crates/gateway-types/src/tool.rs` byte for byte into +//! `crates/runvil-plugin-sdk/src/tool_info.rs`, or with `--check` verifies +//! that the two files match byte for byte. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +/// Relative path from the parent workspace directory to the canonical source. +const UPSTREAM_SOURCE: &str = "gateway-client/crates/gateway-types/src/tool.rs"; +/// Relative path from this repository's root to the synced SDK copy. +const LOCAL_DEST: &str = "crates/runvil-plugin-sdk/src/tool_info.rs"; + +/// Copies `tool.rs` into `tool_info.rs`, or with `--check` verifies they match. +pub(crate) fn run(root: &Path, args: &[String]) -> ExitCode { + let check = match args { + [] => false, + [flag] if flag == "--check" => true, + _ => { + eprintln!("usage: cargo xtask sync-tool-info [--check]"); + return ExitCode::from(2); + } + }; + let Some(source_path) = upstream_path(root) else { + eprintln!( + "error: cannot locate parent directory of {}", + root.display() + ); + return ExitCode::FAILURE; + }; + let source = match fs::read(&source_path) { + Ok(bytes) => bytes, + Err(error) => { + eprintln!("error: cannot read {}: {error}", source_path.display()); + return ExitCode::FAILURE; + } + }; + let dest_path = root.join(LOCAL_DEST); + if check { + return match fs::read(&dest_path) { + Ok(committed) if committed == source => { + println!("{LOCAL_DEST} matches {UPSTREAM_SOURCE}"); + ExitCode::SUCCESS + } + Ok(_) => { + eprintln!( + "error: {LOCAL_DEST} differs from ../{UPSTREAM_SOURCE}: run `cargo xtask sync-tool-info`" + ); + ExitCode::FAILURE + } + Err(error) => { + eprintln!("error: cannot read {LOCAL_DEST}: {error}"); + ExitCode::FAILURE + } + }; + } + match fs::write(&dest_path, source) { + Ok(()) => { + println!("wrote {LOCAL_DEST}"); + ExitCode::SUCCESS + } + Err(error) => { + eprintln!("error: cannot write {LOCAL_DEST}: {error}"); + ExitCode::FAILURE + } + } +} + +/// Resolves `../gateway-client/crates/gateway-types/src/tool.rs` from `root`. +fn upstream_path(root: &Path) -> Option { + root.parent().map(|parent| parent.join(UPSTREAM_SOURCE)) +} + +#[cfg(test)] +mod tests { + use std::fs; + use std::path::Path; + + use super::{LOCAL_DEST, UPSTREAM_SOURCE, upstream_path}; + + #[test] + fn tool_info_matches_sibling_gateway_types_when_present() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .ancestors() + .nth(2) + .expect("workspace root exists"); + let dest_path = root.join(LOCAL_DEST); + assert!(dest_path.is_file(), "{LOCAL_DEST} must exist"); + let Some(source_path) = upstream_path(root) else { + return; + }; + if !source_path.is_file() { + return; + } + let source = fs::read(&source_path).expect("sibling tool.rs is readable"); + let committed = fs::read(&dest_path).expect("local tool_info.rs is readable"); + assert_eq!( + committed, source, + "{LOCAL_DEST} drifted from ../{UPSTREAM_SOURCE}: run `cargo xtask sync-tool-info`" + ); + } +} diff --git a/crates/runvil-plugin-sdk/Cargo.toml b/crates/runvil-plugin-sdk/Cargo.toml index f277e12..e0e01c0 100644 --- a/crates/runvil-plugin-sdk/Cargo.toml +++ b/crates/runvil-plugin-sdk/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "runvil-plugin-sdk" -version = "0.8.0" +version = "0.9.0" description = "Write a runvil Plugin in safe Rust, over runvil-plugin-sys" edition.workspace = true # The floor a Plugin author's toolchain needs; CI's msrv job builds it. @@ -11,6 +11,8 @@ publish = false [dependencies] runvil-plugin-sys.workspace = true +serde.workspace = true +serde_json.workspace = true [features] # `testing`, a fake Host for a Plugin crate's own tests; Plugin crates diff --git a/crates/runvil-plugin-sdk/src/entry/file.rs b/crates/runvil-plugin-sdk/src/entry/file.rs index ccbccf8..9a9b72f 100644 --- a/crates/runvil-plugin-sdk/src/entry/file.rs +++ b/crates/runvil-plugin-sdk/src/entry/file.rs @@ -215,7 +215,9 @@ mod tests { Stat, ToolCall, ToolError, ToolErrorKind, ToolInfo, ToolOutput, next_step, }; - const SCHEMA: &str = r#"{"type":"object","properties":{}}"#; + fn schema() -> serde_json::Value { + serde_json::json!({"type": "object", "properties": {}}) + } /// The tools that read, each named for what it does with the path in /// its arguments. @@ -270,9 +272,9 @@ mod tests { impl Pack for Tools { fn tools(&self) -> Vec { - let reads = READS.map(|name| ToolInfo::new(name, "A tool.", SCHEMA)); - let changes = - CHANGES.map(|name| ToolInfo::new(name, "A tool.", SCHEMA).changes_files()); + let reads = READS.map(|name| ToolInfo::new(name, "A tool.", schema())); + let changes = CHANGES + .map(|name| ToolInfo::new(name, "A tool.", schema()).with_changes_files(true)); reads.into_iter().chain(changes).collect() } diff --git a/crates/runvil-plugin-sdk/src/entry/pack.rs b/crates/runvil-plugin-sdk/src/entry/pack.rs index acb3bf2..6062c31 100644 --- a/crates/runvil-plugin-sdk/src/entry/pack.rs +++ b/crates/runvil-plugin-sdk/src/entry/pack.rs @@ -5,12 +5,11 @@ use std::ffi::c_void; use std::mem::size_of; use std::panic::{self, AssertUnwindSafe}; -use std::ptr; use std::slice; use runvil_plugin_sys::{ - RV_ERR_MISUSE, RV_ERR_UNSUPPORTED, RV_OK, RV_TOOL_CHANGES_FILES, RvCall, RvPackNewArgs, - RvPackRenderArgs, RvStatus, RvStr, RvToolInfo, + RV_ERR_MISUSE, RV_ERR_UNSUPPORTED, RV_OK, RvCall, RvPackNewArgs, RvPackRenderArgs, RvStatus, + RvToolInfo, }; use super::{args, contain, panic_message, read_str, refuse, rv_str, size_field}; @@ -79,28 +78,24 @@ pub(super) unsafe fn new(call: *mut RvCall) -> RvStatus { /// The function a call's arguments carry for adding one tool. type AddTool = unsafe extern "C" fn(*mut c_void, *const RvToolInfo) -> RvStatus; -/// Adds each of `tools` through `add_tool`, stopping at the first status -/// that is not `RV_OK`. +/// Serializes each of `tools` as JSON and passes it through `add_tool`, +/// stopping at the first status that is not `RV_OK`. /// /// # Safety /// `add_tool` and `ctx` come from the arguments struct of the /// `RV_PACK_NEW` or `RV_PACK_RENDER` call open on this thread. unsafe fn add_tools(add_tool: AddTool, ctx: *mut c_void, tools: &[ToolInfo]) -> RvStatus { for tool in tools { + let Ok(json) = serde_json::to_string(tool) else { + return RV_ERR_MISUSE; + }; let info = RvToolInfo { size: size_field::(), - flags: if tool.changes_files { - RV_TOOL_CHANGES_FILES - } else { - 0 - }, - name: rv_str(&tool.name), - wire_name: tool.wire_name.as_deref().map_or(EMPTY, rv_str), - description: rv_str(&tool.description), - parameters: rv_str(&tool.parameters), + reserved: 0, + json: rv_str(&json), }; // SAFETY: the caller passes the open call's function and `ctx`, and - // `info` and its strings outlive the call. + // `info` and `json` outlive the call. let status = unsafe { add_tool(ctx, &raw const info) }; if status != RV_OK { return status; @@ -109,12 +104,6 @@ unsafe fn add_tools(add_tool: AddTool, ctx: *mut c_void, tools: &[ToolInfo]) -> RV_OK } -/// The empty string, which lets the Host derive a tool's wire name. -const EMPTY: RvStr = RvStr { - ptr: ptr::null(), - len: 0, -}; - /// Answers `RV_PACK_RENDER`: copies what the Host lends, calls /// [`Pack::render`] with it, and adds each tool the Pack lists. A refusal, /// or a panic in the render, declines through the Host's `refuse`. The @@ -192,30 +181,19 @@ unsafe fn copy_offered(args: &RvPackRenderArgs) -> Result, RvStatu /// A copy of one offered tool. /// /// # Safety -/// Each string in `info` is valid for its length, for the call. +/// `info.json` is valid for its length, for the call. unsafe fn copy_tool(info: &RvToolInfo) -> Result { if (info.size as usize) < size_of::() { return Err(RV_ERR_UNSUPPORTED); } - // SAFETY: the caller vouches for the strings. - let strings = unsafe { - ( - read_str(info.name), - read_str(info.wire_name), - read_str(info.description), - read_str(info.parameters), - ) - }; - let (Some(name), Some(wire_name), Some(description), Some(parameters)) = strings else { + if info.reserved != 0 { + return Err(RV_ERR_MISUSE); + } + // SAFETY: the caller vouches for the JSON string. + let Some(json) = (unsafe { read_str(info.json) }) else { return Err(RV_ERR_MISUSE); }; - Ok(ToolInfo { - name: name.to_owned(), - wire_name: (!wire_name.is_empty()).then(|| wire_name.to_owned()), - description: description.to_owned(), - parameters: parameters.to_owned(), - changes_files: info.flags & RV_TOOL_CHANGES_FILES != 0, - }) + serde_json::from_str::(json).map_err(|_| RV_ERR_MISUSE) } /// Answers `RV_PACK_DELETE`: drops the instance `RV_PACK_NEW` set, @@ -260,11 +238,11 @@ mod tests { use runvil_plugin_sys::{ RV_ERR_MISUSE, RV_ERR_REFUSED, RV_ERR_UNSUPPORTED, RV_OK, RV_PACK_DELETE, RV_PACK_NEW, - RV_PACK_RENDER, RV_TOOL_CHANGES_FILES, RvCall, RvPackRenderArgs, RvStatus, RvStr, - RvToolInfo, + RV_PACK_RENDER, RvCall, RvPackRenderArgs, RvStatus, RvStr, RvToolInfo, }; + use serde_json::{Value, json}; - use super::{EMPTY, PackRun}; + use super::PackRun; use crate::entry::{entry, read_str, rv_str, size_field}; use crate::testing::{self, Failure}; use crate::{ @@ -279,7 +257,9 @@ mod tests { /// makes them. static BAD_TOOL_LIVE: AtomicIsize = AtomicIsize::new(0); - const SCHEMA: &str = r#"{"type":"object","properties":{}}"#; + fn schema() -> Value { + json!({"type": "object", "properties": {}}) + } /// The call of a Pack whose tools are never called. fn uncalled<'a>() -> BoxFuture<'a, Result> { @@ -326,8 +306,8 @@ mod tests { impl Pack for Counted { fn tools(&self) -> Vec { vec![ - ToolInfo::new("first", "The first tool.", SCHEMA).wire_name("First"), - ToolInfo::new("second", "The second tool.", SCHEMA).changes_files(), + ToolInfo::new("first", "The first tool.", schema()).with_wire_name("First"), + ToolInfo::new("second", "The second tool.", schema()).with_changes_files(true), ] } @@ -346,7 +326,7 @@ mod tests { impl Pack for BadTool { fn tools(&self) -> Vec { - vec![ToolInfo::new("Not A Segment", "A tool.", SCHEMA)] + vec![ToolInfo::new("Not A Segment", "A tool.", schema())] } fn call<'a>(&'a self, _call: ToolCall<'a>) -> BoxFuture<'a, Result> { @@ -381,8 +361,8 @@ mod tests { assert_eq!( pack.tools(), [ - ToolInfo::new("first", "The first tool.", SCHEMA).wire_name("First"), - ToolInfo::new("second", "The second tool.", SCHEMA).changes_files(), + ToolInfo::new("first", "The first tool.", schema()).with_wire_name("First"), + ToolInfo::new("second", "The second tool.", schema()).with_changes_files(true), ] ); assert!(!pack.tools()[0].changes_files, "no flag unless it is set"); @@ -451,20 +431,17 @@ mod tests { /// one at `fail_at`. unsafe extern "C" fn record_tool(ctx: *mut c_void, info: *const RvToolInfo) -> RvStatus { // SAFETY: the test passes a `Recorder` as `ctx`, and the entry point - // passes a readable `RvToolInfo` with valid strings. + // passes a readable `RvToolInfo` with valid JSON text. let (recorder, info) = unsafe { (&mut *ctx.cast::(), &*info) }; - // SAFETY: the entry point's strings are valid for the call. - let text = |s: RvStr| unsafe { read_str(s) }.unwrap().to_owned(); + if info.reserved != 0 { + return RV_ERR_MISUSE; + } + // SAFETY: the entry point's JSON string is valid for the call. + let json = unsafe { read_str(info.json) }.unwrap(); if recorder.fail_at == Some(recorder.added.len()) { return RV_ERR_MISUSE; } - recorder.added.push(ToolInfo { - name: text(info.name), - wire_name: Some(text(info.wire_name)).filter(|name| !name.is_empty()), - description: text(info.description), - parameters: text(info.parameters), - changes_files: info.flags & RV_TOOL_CHANGES_FILES != 0, - }); + recorder.added.push(serde_json::from_str(json).unwrap()); RV_OK } @@ -522,12 +499,12 @@ mod tests { let mut shown: Vec = offered .into_iter() .filter(|tool| tool.name != "second") - .map(|tool| tool.wire_name("Look")) + .map(|tool| tool.with_wire_name("Look")) .collect(); shown.push(ToolInfo::new( "lite", format!("seen by {} in {}", cx.model, cx.entry), - SCHEMA, + schema(), )); Ok(shown) } @@ -544,8 +521,8 @@ mod tests { /// The two tools a section offered, in the Host's own form. fn offered() -> Vec { vec![ - ToolInfo::new("first", "The first tool.", SCHEMA).wire_name("First"), - ToolInfo::new("second", "The second tool.", SCHEMA).changes_files(), + ToolInfo::new("first", "The first tool.", schema()).with_wire_name("First"), + ToolInfo::new("second", "The second tool.", schema()).with_changes_files(true), ] } @@ -558,19 +535,16 @@ mod tests { edit: impl FnOnce(&mut RvPackRenderArgs, &mut [RvToolInfo]), ) -> (RvStatus, Recorder) { let tools = offered(); - let mut values: Vec = tools + let jsons: Vec = tools + .iter() + .map(|tool| serde_json::to_string(tool).unwrap()) + .collect(); + let mut values: Vec = jsons .iter() - .map(|tool| RvToolInfo { + .map(|json| RvToolInfo { size: size_field::(), - flags: if tool.changes_files { - RV_TOOL_CHANGES_FILES - } else { - 0 - }, - name: rv_str(&tool.name), - wire_name: tool.wire_name.as_deref().map_or(EMPTY, rv_str), - description: rv_str(&tool.description), - parameters: rv_str(&tool.parameters), + reserved: 0, + json: rv_str(json), }) .collect(); let mut recorder = Recorder { @@ -625,8 +599,8 @@ mod tests { assert_eq!( recorder.added, [ - ToolInfo::new("first", "The first tool.", SCHEMA).wire_name("Look"), - ToolInfo::new("lite", format!("seen by {MODEL} in {ENTRY}"), SCHEMA), + ToolInfo::new("first", "The first tool.", schema()).with_wire_name("Look"), + ToolInfo::new("lite", format!("seen by {MODEL} in {ENTRY}"), schema()), ] ); } @@ -678,7 +652,7 @@ mod tests { #[test] fn a_render_the_host_breaks_is_a_misuse_or_unsupported() { - let cases: [(&str, Edit, RvStatus); 7] = [ + let cases: [(&str, Edit, RvStatus); 9] = [ ( "offered tools with a NULL pointer", |args, _| args.offered = ptr::null(), @@ -720,15 +694,25 @@ mod tests { RV_ERR_UNSUPPORTED, ), ( - "an offered tool whose name has a NULL pointer", + "an offered tool with a nonzero reserved field", + |_, tools| tools[0].reserved = 1, + RV_ERR_MISUSE, + ), + ( + "an offered tool whose json has a NULL pointer", |_, tools| { - tools[0].name = RvStr { + tools[0].json = RvStr { ptr: ptr::null(), len: 5, }; }, RV_ERR_MISUSE, ), + ( + "an offered tool whose json is invalid JSON", + |_, tools| tools[0].json = rv_str("{not json"), + RV_ERR_MISUSE, + ), ]; for (what, edit, expected) in cases { let (status, recorder) = render_with(Renders::Default, None, edit); diff --git a/crates/runvil-plugin-sdk/src/entry/tool.rs b/crates/runvil-plugin-sdk/src/entry/tool.rs index 5818355..cf10c2d 100644 --- a/crates/runvil-plugin-sdk/src/entry/tool.rs +++ b/crates/runvil-plugin-sdk/src/entry/tool.rs @@ -356,7 +356,9 @@ mod tests { /// has ended. static KEPT: Mutex> = Mutex::new(None); - const SCHEMA: &str = r#"{"type":"object","properties":{}}"#; + fn schema() -> serde_json::Value { + serde_json::json!({"type": "object", "properties": {}}) + } /// Resources that hold a key, which no `Debug` may print. const RESOURCES: &str = r#"{"acme/search":{"api_key":"hunter2"}}"#; @@ -476,7 +478,7 @@ mod tests { "idle", ] .into_iter() - .map(|name| ToolInfo::new(name, "A tool.", SCHEMA)) + .map(|name| ToolInfo::new(name, "A tool.", schema())) .collect() } diff --git a/crates/runvil-plugin-sdk/src/lib.rs b/crates/runvil-plugin-sdk/src/lib.rs index d39a289..9c9ef8d 100644 --- a/crates/runvil-plugin-sdk/src/lib.rs +++ b/crates/runvil-plugin-sdk/src/lib.rs @@ -34,7 +34,7 @@ //! vec![ToolInfo::new( //! "greet", //! "Returns a greeting.", -//! r#"{"type":"object","properties":{}}"#, +//! serde_json::json!({"type": "object", "properties": {}}), //! )] //! } //! @@ -81,30 +81,30 @@ //! later step goes on with the answer. The run's policy applies to every //! request, and one that fails resolves to a [`FileError`] that leaves //! the call running. A tool that changes files says so with -//! [`ToolInfo::changes_files`], and the Host then runs each of its calls -//! by itself among the calls one reply of a model asks for. +//! [`ToolInfo::with_changes_files`], and the Host then runs each of its +//! calls by itself among the calls one reply of a model asks for. //! //! A Pack may shape what a model is shown with [`Pack::render`]. The Host //! calls it when a section entry's first model round is about to //! advertise its tools, with the section entry, the model as JSON text, //! and the catalog tools the section offered from the Pack. The answer //! lists the tools the model sees. A tool listed under the name of an -//! offered tool is that catalog tool: it may take another wire name and -//! description, and its parameters stay as offered, so one catalog name -//! always means one parameter schema. A tool listed under a name that no -//! tool of the instance's catalog has is a model-facing tool, which only a -//! model calls and which a Pack answers by its own name. A catalog tool -//! the section did not offer in this set may not be listed. A Pack that -//! does not override `render` shows the offered tools as they are. +//! offered tool is that catalog tool: it may take another wire name, +//! description, or metadata, and its input schema stays equal to the +//! offered schema, so one catalog name always means one input schema. A +//! tool listed under a name that no tool of the instance's catalog has is +//! a model-facing tool, which only a model calls and which a Pack answers +//! by its own name. A catalog tool the section did not offer in this set +//! may not be listed. A Pack that does not override `render` shows the +//! offered tools as they are. //! //! The `test-support` feature adds `testing`, a fake Host for a Plugin //! crate's own tests. //! //! ## Invariants //! -//! - Depends on `runvil-plugin-sys` alone, which it re-exports as [`sys`]. -//! JSON crosses as text, which a Plugin parses with a library of its -//! own. +//! - Depends on `runvil-plugin-sys`, `serde`, and `serde_json`, and +//! re-exports `runvil-plugin-sys` as [`sys`]. //! - The crate's `unsafe` sits in [`entry`] and its child modules, the //! code [`export_plugin!`] expands to, and `testing`. A Plugin written //! against it needs none. @@ -144,14 +144,14 @@ mod pack; #[cfg(any(test, feature = "test-support"))] pub mod testing; mod tool; +mod tool_info; pub use entry::entry; pub use file::{DirEntry, FileError, FileErrorKind, FileFuture, FileType, Stat}; pub use pack::{BoxFuture, Pack, PackInfo, RenderContext}; pub use runvil_plugin_sys as sys; -pub use tool::{ - Caller, NextStep, ToolCall, ToolError, ToolErrorKind, ToolInfo, ToolOutput, next_step, -}; +pub use tool::{Caller, NextStep, ToolCall, ToolError, ToolErrorKind, ToolOutput, next_step}; +pub use tool_info::ToolInfo; /// A Plugin: the instance the Host holds while the Plugin is loaded, and /// the maker of each run's Pack instances. diff --git a/crates/runvil-plugin-sdk/src/pack.rs b/crates/runvil-plugin-sdk/src/pack.rs index 5249653..3fd7ee4 100644 --- a/crates/runvil-plugin-sdk/src/pack.rs +++ b/crates/runvil-plugin-sdk/src/pack.rs @@ -4,8 +4,8 @@ use std::future::Future; use std::pin::Pin; -use crate::Refusal; -use crate::tool::{ToolCall, ToolError, ToolInfo, ToolOutput}; +use crate::tool::{ToolCall, ToolError, ToolOutput}; +use crate::{Refusal, ToolInfo}; /// A boxed future that is `Send`, which [`Pack::call`] returns. An /// implementation wraps its body in `Box::pin(async move { ... })`. @@ -119,17 +119,17 @@ pub trait Pack: Send + Sync + 'static { /// /// - A tool left out of the answer is not shown. /// - A tool listed under the `name` of an offered tool is that catalog - /// tool. It may take another `wire_name` and `description`, and its - /// `parameters` stay the offered text, so one catalog name always - /// means one parameter schema. Lua can call it by its id, whatever - /// the model is shown. + /// tool. It may take another `wire_name`, `description`, or metadata, + /// and its `input_schema` stays equal to the offered schema, so one + /// catalog name always means one input schema. Lua can call it by its + /// id, whatever the model is shown. /// - A tool listed under a name that no tool of this instance's catalog /// has is a model-facing tool: only a model calls it, and no script - /// can name it. It is how a model is shown other parameters than the - /// catalog's, under a name of its own, and [`Pack::call`] answers its - /// calls by that name. It takes the flags it is given, so a + /// can name it. It is how a model is shown another `input_schema` than + /// the catalog's, under a name of its own, and [`Pack::call`] answers + /// its calls by that name. It takes the flags it is given, so a /// model-facing tool that changes files says so with - /// [`ToolInfo::changes_files`]. + /// [`ToolInfo::with_changes_files`]. /// - A catalog tool the section did not offer in this set may not be /// listed, under its own name or any other that the catalog has: the /// Host fails the round that asked for the render. @@ -168,10 +168,8 @@ pub struct RenderContext<'a> { /// The JSON text of an object that describes the model of the entry's /// first round: `server`, `name`, `description`, `context` (the window /// in tokens), `thinking` (`"never"`, `"always"`, or `"switchable"`), - /// and `provider` when the Host's catalog names one. The SDK needs no - /// JSON library, so a Pack parses it with one of its own. A later - /// version adds a fact as a new key, so a Pack ignores a key it does - /// not know. + /// and `provider` when the Host's catalog names one. A later version + /// adds a fact as a new key, so a Pack ignores a key it does not know. pub model: &'a str, } diff --git a/crates/runvil-plugin-sdk/src/testing.rs b/crates/runvil-plugin-sdk/src/testing.rs index c94fda9..0c31200 100644 --- a/crates/runvil-plugin-sdk/src/testing.rs +++ b/crates/runvil-plugin-sdk/src/testing.rs @@ -41,11 +41,11 @@ //! `RV_PACK_RENDER` with the tools a section offered and returns the tools //! the model is shown. It checks each tool as `RV_PACK_NEW` checks one, and //! then the render as a whole: a catalog tool keeps its offered -//! parameters, compared as text, which is stricter than the Harness; a -//! tool of the instance that the section did not offer is not listed; and -//! no two tools show one wire name. A broken rule is a -//! [`Failure::Rejected`] that names the tool. A model-facing tool that the -//! render listed is called with [`PackRun::call`] under that name. +//! `input_schema`, compared as JSON; a tool of the instance that the +//! section did not offer is not listed; and no two tools show one wire +//! name. A broken rule is a [`Failure::Rejected`] that names the tool. A +//! model-facing tool that the render listed is called with [`PackRun::call`] +//! under that name. //! //! Every call is lent a caller, a section, an entry, a model, and the //! Host's resources. By default a call is from [`Caller::Model`], in the diff --git a/crates/runvil-plugin-sdk/src/testing/fixture.rs b/crates/runvil-plugin-sdk/src/testing/fixture.rs index 2e10225..176311a 100644 --- a/crates/runvil-plugin-sdk/src/testing/fixture.rs +++ b/crates/runvil-plugin-sdk/src/testing/fixture.rs @@ -9,12 +9,14 @@ use std::ptr; use runvil_plugin_sys::{ RV_ERR_UNSUPPORTED, RV_OK, RV_PACK_DELETE, RV_PACK_NEW, RV_PENDING, RV_PLUGIN_LOAD, - RV_PLUGIN_UNLOAD, RV_RESULT_UNTRUSTED, RV_TOOL_CALL, RV_TOOL_CANCEL, RV_TOOL_CHANGES_FILES, - RvCall, RvLoadArgs, RvPackInfo, RvPackNewArgs, RvPluginInfo, RvStatus, RvStr, RvToolCallArgs, - RvToolInfo, RvToolResult, RvWaker, + RV_PLUGIN_UNLOAD, RV_RESULT_UNTRUSTED, RV_TOOL_CALL, RV_TOOL_CANCEL, RvCall, RvLoadArgs, + RvPackInfo, RvPackNewArgs, RvPluginInfo, RvStatus, RvStr, RvToolCallArgs, RvToolInfo, + RvToolResult, RvWaker, }; +use serde_json::json; use super::{Failure, Loaded, load_entry}; +use crate::ToolInfo; use crate::entry::{rv_str, size_field}; thread_local! { @@ -67,20 +69,30 @@ pub(super) enum Breach { PackFunctionInLoad, /// Adds a tool through a `ctx` that is not its call's. PackCtx, + /// Adds a tool whose `RvToolInfo` has a nonzero `reserved`. + ToolReserved, + /// Adds a tool whose `json` is not valid `ToolInfo` JSON. + ToolBadJson, + /// Adds a tool whose name exceeds 64 bytes. + ToolNameTooLong, /// Adds a tool whose name is not one segment. ToolName, /// Adds one tool twice. ToolTwice, /// Adds a tool whose wire name has a `/`. WireName, + /// Adds a tool whose wire name is `Some("")`. + WireNameEmpty, /// Adds a tool whose wire name starts with a digit instead of an ASCII letter. WireNameLeadingDigit, + /// Adds a tool whose wire name exceeds 64 bytes. + WireNameTooLong, /// Adds a tool with an empty description. NoDescription, - /// Adds a tool whose parameters are a JSON array. - Parameters, - /// Adds a tool whose flags set a bit the contract does not name. - ToolFlags, + /// Adds a tool whose input schema is a JSON array. + InputSchema, + /// Adds a tool whose output schema is a JSON array. + OutputSchema, /// Calls `describe_plugin` during `RV_PACK_NEW`. LoadFunctionInPackNew, /// Declines to make its Pack instance. @@ -230,7 +242,8 @@ unsafe fn load_verb(call: *mut RvCall, args: &RvLoadArgs, breach: Breach) -> RvS (args.insert_pack)(args.ctx, &raw const pack); } if breach == Breach::PackFunctionInLoad { - let tool = tool_info(breach); + let json = first_tool_json(breach); + let tool = rv_tool(&json, false); super::pack::add_tool(args.ctx, &raw const tool); } (*call).plugin = dangling(); @@ -238,50 +251,78 @@ unsafe fn load_verb(call: *mut RvCall, args: &RvLoadArgs, breach: Breach) -> RvS RV_OK } -/// The fixture's first tool. -fn tool_info(breach: Breach) -> RvToolInfo { +/// Builds an [`RvToolInfo`] borrowing `json`. +fn rv_tool(json: &str, bad_reserved: bool) -> RvToolInfo { RvToolInfo { size: size_field::(), - flags: if breach == Breach::ToolFlags { 2 } else { 0 }, - name: text_unless(breach, Breach::ToolName, "tool", "Not A Segment"), - wire_name: match breach { - Breach::WireName => rv_str("web/fetch"), - Breach::WireNameLeadingDigit => rv_str("0_fetch"), - _ => rv_str("Tool"), - }, - description: text_unless(breach, Breach::NoDescription, "A fixture tool.", ""), - parameters: text_unless(breach, Breach::Parameters, "{}", "[]"), + reserved: u32::from(bad_reserved), + json: rv_str(json), } } +/// The JSON string for the fixture's first tool under `breach`. +fn first_tool_json(breach: Breach) -> String { + if breach == Breach::ToolBadJson { + return "{not json".to_owned(); + } + let name = match breach { + Breach::ToolNameTooLong => "a".repeat(65), + Breach::ToolName => "Not A Segment".to_owned(), + _ => "tool".to_owned(), + }; + let description = if breach == Breach::NoDescription { + "" + } else { + "A fixture tool." + }; + let input_schema = if breach == Breach::InputSchema { + json!([]) + } else { + json!({}) + }; + let wire_name = match breach { + Breach::WireName => "web/fetch".to_owned(), + Breach::WireNameEmpty => String::new(), + Breach::WireNameLeadingDigit => "0_fetch".to_owned(), + Breach::WireNameTooLong => "a".repeat(65), + _ => "Tool".to_owned(), + }; + let mut tool = ToolInfo::new(name, description, input_schema).with_wire_name(wire_name); + if breach == Breach::OutputSchema { + tool = tool.with_output_schema(json!([])); + } + serde_json::to_string(&tool).unwrap() +} + /// Answers `RV_PACK_NEW`. /// /// # Safety /// `call` and `args` are the fake Host's open call. unsafe fn pack_new(call: *mut RvCall, args: &RvPackNewArgs, breach: Breach) -> RvStatus { let ctx = ctx_unless(breach, Breach::PackCtx, args.ctx); - let first = tool_info(breach); - let other = RvToolInfo { - flags: RV_TOOL_CHANGES_FILES, - name: rv_str("other"), - wire_name: rv_str(""), - description: rv_str("Another fixture tool."), - ..tool_info(Breach::None) - }; - let asks = RvToolInfo { - name: rv_str("asks"), - wire_name: rv_str(""), - description: rv_str("A fixture tool that reads a file."), - ..tool_info(Breach::None) - }; - let parks = RvToolInfo { - name: rv_str("parks"), - wire_name: rv_str(""), - description: rv_str("A fixture tool that wakes nothing."), - ..tool_info(Breach::None) - }; - // SAFETY: the open call's own functions, and structs that outlive each - // call. + let first_json = first_tool_json(breach); + let other_json = serde_json::to_string( + &ToolInfo::new("other", "Another fixture tool.", json!({})).with_changes_files(true), + ) + .unwrap(); + let asks_json = serde_json::to_string(&ToolInfo::new( + "asks", + "A fixture tool that reads a file.", + json!({}), + )) + .unwrap(); + let parks_json = serde_json::to_string(&ToolInfo::new( + "parks", + "A fixture tool that wakes nothing.", + json!({}), + )) + .unwrap(); + let first = rv_tool(&first_json, breach == Breach::ToolReserved); + let other = rv_tool(&other_json, false); + let asks = rv_tool(&asks_json, false); + let parks = rv_tool(&parks_json, false); + // SAFETY: the open call's own functions, and structs and JSON strings + // that outlive each call. unsafe { match breach { Breach::RefusePack => return (args.refuse)(args.ctx, rv_str("no instance today")), diff --git a/crates/runvil-plugin-sdk/src/testing/json.rs b/crates/runvil-plugin-sdk/src/testing/json.rs index c0ee76f..9676e2e 100644 --- a/crates/runvil-plugin-sdk/src/testing/json.rs +++ b/crates/runvil-plugin-sdk/src/testing/json.rs @@ -1,6 +1,5 @@ -//! Whether a text is the JSON of an object, which is the rule a tool's -//! parameters follow. The Harness parses them with a JSON library; this -//! crate depends on none, so the fake Host checks the grammar itself. +//! Whether a text is the JSON of an object, which is the rule a model +//! description follows in `RV_PACK_RENDER` and `RV_TOOL_CALL`. /// The deepest nesting of arrays and objects a text may hold. The /// Harness's parser refuses the 128th level. diff --git a/crates/runvil-plugin-sdk/src/testing/pack.rs b/crates/runvil-plugin-sdk/src/testing/pack.rs index b821804..76072e7 100644 --- a/crates/runvil-plugin-sdk/src/testing/pack.rs +++ b/crates/runvil-plugin-sdk/src/testing/pack.rs @@ -6,19 +6,15 @@ use std::ffi::c_void; use runvil_plugin_sys::{ - RV_MAX_NAME, RV_MAX_TOOL_TEXT, RV_OK, RV_TOOL_CHANGES_FILES, RvStatus, RvStr, RvToolInfo, + RV_MAX_NAME, RV_MAX_TOOL_JSON, RV_MAX_TOOL_TEXT, RV_OK, RvStatus, RvStr, RvToolInfo, }; -use super::json; use super::session::{self, Family, Field, PACK_NEW, Shape, answer, field, shape}; use crate::ToolInfo; use crate::names::{is_valid_name, is_valid_wire_name}; const TOOL_INFO: Shape = shape!("add_tool", "info", "RvToolInfo"); -const TOOL_NAME: Field = field!("the tool's name", 64, RV_MAX_NAME); -const WIRE_NAME: Field = field!("the tool's wire name", 64, RV_MAX_NAME); -const DESCRIPTION: Field = field!("the tool's description", 65536, RV_MAX_TOOL_TEXT); -const PARAMETERS: Field = field!("the tool's parameter schema", 65536, RV_MAX_TOOL_TEXT); +const TOOL_JSON: Field = field!("the tool's JSON", 262_144, RV_MAX_TOOL_JSON); /// Records the Plugin's refusal to make a Pack instance. pub(super) unsafe extern "C" fn refuse(ctx: *mut c_void, reason: RvStr) -> RvStatus { @@ -45,8 +41,8 @@ pub(super) unsafe extern "C" fn add_tool(ctx: *mut c_void, info: *const RvToolIn /// `RV_PACK_RENDER`. `twice` names a repeated name. /// /// # Safety -/// `info` must be NULL or point at a readable `RvToolInfo` whose strings -/// are valid for their lengths, for the duration of the call. +/// `info` must be NULL or point at a readable `RvToolInfo` whose `json` +/// string is valid for its length, for the duration of the call. pub(super) unsafe fn add( ctx: *mut c_void, family: &Family, @@ -56,43 +52,60 @@ pub(super) unsafe fn add( answer(ctx, family, |session| { // SAFETY: the caller makes `info` readable if it is not NULL. let info = unsafe { TOOL_INFO.read(info) }?; - if info.flags & !RV_TOOL_CHANGES_FILES != 0 { - return Err("the tool's flags set a bit that is not one of the RV_TOOL constants"); + if info.reserved != 0 { + return Err("the info's reserved field is not zero"); } - // SAFETY: the caller makes each string valid for its length. - let name = unsafe { TOOL_NAME.read(info.name) }?; - if !is_valid_name(&name) { - return Err("the tool's name is not one name segment, such as `fetch`"); - } - if session.tools.iter().any(|tool| tool.name == name) { - return Err(twice); + // SAFETY: the caller makes `info.json` valid for its length. + let raw_json = unsafe { TOOL_JSON.read(info.json) }?; + let tool = serde_json::from_str::(&raw_json) + .map_err(|_| "the tool's info is not valid ToolInfo JSON")?; + validate_tool(&tool, &session.tools, twice)?; + session.tools.push(tool); + Ok(RV_OK) + }) +} + +/// Validates a parsed [`ToolInfo`] against the contract's field rules and +/// checks that `existing` holds no tool with the same `name`. +fn validate_tool( + tool: &ToolInfo, + existing: &[ToolInfo], + twice: &'static str, +) -> Result<(), &'static str> { + if tool.name.len() > RV_MAX_NAME { + return Err("the tool's name is longer than 64 bytes"); + } + if !is_valid_name(&tool.name) { + return Err("the tool's name is not one name segment, such as `fetch`"); + } + if existing.iter().any(|held| held.name == tool.name) { + return Err(twice); + } + if let Some(wire) = &tool.wire_name { + if wire.len() > RV_MAX_NAME { + return Err("the tool's wire name is longer than 64 bytes"); } - // SAFETY: as above. - let wire_name = unsafe { WIRE_NAME.read(info.wire_name) }?; - if !wire_name.is_empty() && !is_valid_wire_name(&wire_name) { + if !is_valid_wire_name(wire) { return Err( "the tool's wire name must start with an ASCII letter and hold only ASCII letters, digits, `_`, and `-`", ); } - // SAFETY: as above. - let description = unsafe { DESCRIPTION.read(info.description) }?; - if description.is_empty() { - return Err("the tool's description is empty"); - } - // SAFETY: as above. - let parameters = unsafe { PARAMETERS.read(info.parameters) }?; - if !json::is_object(¶meters) { - return Err("the tool's parameter schema is not the JSON text of an object"); + } + if tool.description.len() > RV_MAX_TOOL_TEXT { + return Err("the tool's description is longer than 65536 bytes"); + } + if tool.description.is_empty() { + return Err("the tool's description is empty"); + } + if !tool.input_schema.is_object() { + return Err("the tool's input schema is not a JSON object"); + } + if let Some(schema) = &tool.output_schema { + if !schema.is_object() { + return Err("the tool's output schema is not a JSON object"); } - session.tools.push(ToolInfo { - name, - wire_name: (!wire_name.is_empty()).then_some(wire_name), - description, - parameters, - changes_files: info.flags & RV_TOOL_CHANGES_FILES != 0, - }); - Ok(RV_OK) - }) + } + Ok(()) } #[cfg(test)] @@ -101,6 +114,7 @@ mod tests { //! one of them at a time. use runvil_plugin_sys::RV_ERR_UNSUPPORTED; + use serde_json::json; use crate::ToolInfo; use crate::testing::Failure; @@ -113,10 +127,10 @@ mod tests { assert_eq!( pack.tools(), [ - ToolInfo::new("tool", "A fixture tool.", "{}").wire_name("Tool"), - ToolInfo::new("other", "Another fixture tool.", "{}").changes_files(), - ToolInfo::new("asks", "A fixture tool that reads a file.", "{}"), - ToolInfo::new("parks", "A fixture tool that wakes nothing.", "{}"), + ToolInfo::new("tool", "A fixture tool.", json!({})).with_wire_name("Tool"), + ToolInfo::new("other", "Another fixture tool.", json!({})).with_changes_files(true), + ToolInfo::new("asks", "A fixture tool that reads a file.", json!({})), + ToolInfo::new("parks", "A fixture tool that wakes nothing.", json!({})), ] ); assert_eq!(DELETES.get(), 0); @@ -131,6 +145,18 @@ mod tests { Breach::PackCtx, "a Pack function was handed a ctx other than the open RV_PACK_NEW call's", ), + ( + Breach::ToolReserved, + "the info's reserved field is not zero", + ), + ( + Breach::ToolBadJson, + "the tool's info is not valid ToolInfo JSON", + ), + ( + Breach::ToolNameTooLong, + "the tool's name is longer than 64 bytes", + ), ( Breach::ToolName, "the tool's name is not one name segment, such as `fetch`", @@ -143,18 +169,26 @@ mod tests { Breach::WireName, "the tool's wire name must start with an ASCII letter and hold only ASCII letters, digits, `_`, and `-`", ), + ( + Breach::WireNameEmpty, + "the tool's wire name must start with an ASCII letter and hold only ASCII letters, digits, `_`, and `-`", + ), ( Breach::WireNameLeadingDigit, "the tool's wire name must start with an ASCII letter and hold only ASCII letters, digits, `_`, and `-`", ), + ( + Breach::WireNameTooLong, + "the tool's wire name is longer than 64 bytes", + ), (Breach::NoDescription, "the tool's description is empty"), ( - Breach::Parameters, - "the tool's parameter schema is not the JSON text of an object", + Breach::InputSchema, + "the tool's input schema is not a JSON object", ), ( - Breach::ToolFlags, - "the tool's flags set a bit that is not one of the RV_TOOL constants", + Breach::OutputSchema, + "the tool's output schema is not a JSON object", ), ( Breach::LoadFunctionInPackNew, diff --git a/crates/runvil-plugin-sdk/src/testing/render.rs b/crates/runvil-plugin-sdk/src/testing/render.rs index ff586b1..5da5a37 100644 --- a/crates/runvil-plugin-sdk/src/testing/render.rs +++ b/crates/runvil-plugin-sdk/src/testing/render.rs @@ -7,7 +7,7 @@ use std::ffi::c_void; use std::{mem, ptr}; use runvil_plugin_sys::{ - RV_ERR_UNSUPPORTED, RV_PACK_RENDER, RV_TOOL_CHANGES_FILES, RvPackRenderArgs, RvStatus, RvStr, + RV_ERR_UNSUPPORTED, RV_MAX_TOOL_JSON, RV_PACK_RENDER, RvPackRenderArgs, RvStatus, RvStr, RvToolInfo, }; @@ -18,12 +18,6 @@ use super::{Failure, PackRun}; use crate::ToolInfo; use crate::entry::{rv_str, size_field}; -/// The empty string, which lets the Host derive a tool's wire name. -const EMPTY: RvStr = RvStr { - ptr: ptr::null(), - len: 0, -}; - /// Records the Plugin's refusal to render. /// /// # Safety @@ -63,10 +57,9 @@ impl PackRun<'_> { /// `RV_PACK_NEW` is, and then the render is checked as a whole: /// /// - A tool listed under the name of an offered tool keeps the offered - /// `parameters`. This fake Host compares the two texts byte for - /// byte, which is stricter than the Harness, which compares the JSON - /// they hold. A render that lists the offered `ToolInfo` with another - /// wire name or description passes both. + /// `input_schema`, compared as JSON values, as the Harness compares + /// them. A render that lists the offered `ToolInfo` with another + /// wire name, description, or metadata passes. /// - A tool listed under the name of a tool of this instance that the /// section did not offer fails. /// - Any other name is a model-facing tool, and passes. A test may then @@ -100,7 +93,26 @@ impl PackRun<'_> { tool.name ); } - let infos: Vec = offered.iter().map(raw_info).collect(); + let mut jsons = Vec::with_capacity(offered.len()); + for tool in offered { + let Ok(json) = serde_json::to_string(tool) else { + panic!("offered ToolInfo failed to serialize: {}", tool.name); + }; + assert!( + json.len() <= RV_MAX_TOOL_JSON, + "offered ToolInfo JSON exceeds {RV_MAX_TOOL_JSON} bytes: {}", + tool.name + ); + jsons.push(json); + } + let infos: Vec = jsons + .iter() + .map(|json| RvToolInfo { + size: size_field::(), + reserved: 0, + json: rv_str(json), + }) + .collect(); let mut call = self.new_call(RV_PACK_RENDER); let (status, mut session) = session::open(Verb::PackRender, |ctx| { let args = RvPackRenderArgs { @@ -120,8 +132,8 @@ impl PackRun<'_> { }; call.args = (&raw const args).cast(); // SAFETY: `load_entry`'s caller guaranteed `entry` follows the - // contract, and `call`, `args`, and the tools `args` names are - // live structs that nothing else uses. + // contract, and `call`, `args`, `infos`, and `jsons` are live + // values that nothing else uses. unsafe { (self.loaded.entry)(&raw mut call) } }); if status == RV_ERR_UNSUPPORTED && session.refusal.is_none() && session.misuse.is_none() { @@ -141,7 +153,7 @@ impl PackRun<'_> { let mut shown: Vec<(String, &str)> = Vec::new(); for tool in listed { if let Some(held) = offered.iter().find(|held| held.name == tool.name) { - if held.parameters != tool.parameters { + if held.input_schema != tool.input_schema { return Err(Failure::Rejected(format!( "the render listed the catalog tool {} with other parameters than the \ section offered; a catalog tool keeps its parameters, so list other \ @@ -177,22 +189,6 @@ impl PackRun<'_> { } } -/// `tool` in the form the contract lends an offered tool. -fn raw_info(tool: &ToolInfo) -> RvToolInfo { - RvToolInfo { - size: size_field::(), - flags: if tool.changes_files { - RV_TOOL_CHANGES_FILES - } else { - 0 - }, - name: rv_str(&tool.name), - wire_name: tool.wire_name.as_deref().map_or(EMPTY, rv_str), - description: rv_str(&tool.description), - parameters: rv_str(&tool.parameters), - } -} - #[cfg(test)] mod tests { //! A render through the SDK's entry point and the fake Host: a Pack @@ -200,6 +196,7 @@ mod tests { //! refuses, and one for each rule a render can break. use runvil_plugin_sys::{RV_ERR_UNSUPPORTED, RV_PACK_RENDER, RvCall, RvStatus}; + use serde_json::{Value, json}; use crate::entry::entry; use crate::testing::{self, Failure}; @@ -208,16 +205,22 @@ mod tests { ToolOutput, }; - const SCHEMA: &str = r#"{"type":"object","properties":{}}"#; - const OTHER_SCHEMA: &str = r#"{"type":"object","properties":{"path":{"type":"string"}}}"#; const ENTRY: &str = "entry-1"; const MODEL: &str = r#"{"name":"m","thinking":"never"}"#; + fn schema() -> Value { + json!({"type": "object", "properties": {}}) + } + + fn other_schema() -> Value { + json!({"type": "object", "properties": {"path": {"type": "string"}}}) + } + /// The tools every Pack of [`Renderer`] adds: a read and a change. fn catalog() -> Vec { vec![ - ToolInfo::new("first", "The first tool.", SCHEMA).wire_name("First"), - ToolInfo::new("second", "The second tool.", SCHEMA).changes_files(), + ToolInfo::new("first", "The first tool.", schema()).with_wire_name("First"), + ToolInfo::new("second", "The second tool.", schema()).with_changes_files(true), ] } @@ -249,7 +252,7 @@ mod tests { /// Lists two tools whose default wire names differ only where one /// name has a `.` and the other a `_`. Dotted, - /// Lists `first` with its parameters spaced out, the same JSON. + /// Lists `first` with its schema parsed from differently spaced JSON. Respaced, } @@ -336,49 +339,48 @@ mod tests { let mut shown: Vec = offered .into_iter() .filter(|tool| tool.name != "second") - .map(|tool| tool.wire_name("Look")) + .map(|tool| tool.with_wire_name("Look")) .collect(); shown.push( ToolInfo::new( "lite", format!("{} saw {}", cx.entry, cx.model), - OTHER_SCHEMA, + other_schema(), ) - .changes_files(), + .with_changes_files(true), ); Ok(shown) } Mode::Refuses => Err(Refusal::new("no tools for this model")), Mode::Panics => panic!("boom"), Mode::ChangesParameters => Ok(first() - .map(|mut tool| { - tool.parameters = OTHER_SCHEMA.to_owned(); - tool - }) + .map(|tool| tool.with_input_schema(other_schema())) .into_iter() .collect()), Mode::ListsUnoffered => Ok(vec![catalog().remove(1)]), Mode::Repeats => Ok(first().into_iter().chain(first()).collect()), Mode::SharesWireName => Ok(vec![ - ToolInfo::new("one", "One.", SCHEMA).wire_name("Same"), - ToolInfo::new("two", "Two.", SCHEMA).wire_name("Same"), + ToolInfo::new("one", "One.", schema()).with_wire_name("Same"), + ToolInfo::new("two", "Two.", schema()).with_wire_name("Same"), ]), Mode::ClashesWithDefault => Ok(vec![ - ToolInfo::new("copy", "A copy.", SCHEMA).wire_name("clashes_other"), - ToolInfo::new("other", "Another.", SCHEMA), + ToolInfo::new("copy", "A copy.", schema()).with_wire_name("clashes_other"), + ToolInfo::new("other", "Another.", schema()), ]), - Mode::BadName => Ok(vec![ToolInfo::new("Not A Segment", "A tool.", SCHEMA)]), + Mode::BadName => Ok(vec![ToolInfo::new("Not A Segment", "A tool.", schema())]), Mode::Dotted => Ok(vec![ - ToolInfo::new("a.b", "Dotted.", SCHEMA), - ToolInfo::new("a_b", "Underscored.", SCHEMA), + ToolInfo::new("a.b", "Dotted.", schema()), + ToolInfo::new("a_b", "Underscored.", schema()), ]), - Mode::Respaced => Ok(first() - .map(|mut tool| { - tool.parameters = SCHEMA.replace(':', ": "); - tool - }) - .into_iter() - .collect()), + Mode::Respaced => { + let reparsed: Value = + serde_json::from_str(r#"{ "properties" : { } , "type" : "object" }"#) + .unwrap(); + Ok(first() + .map(|tool| tool.with_input_schema(reparsed)) + .into_iter() + .collect()) + } } } } @@ -408,7 +410,7 @@ mod tests { assert_eq!( render("acme/inherits", &backwards), Ok(backwards), - "the default keeps every tool, its order, and its text" + "the default keeps every tool, its order, and its schema" ); assert_eq!(render("acme/inherits", &[]), Ok(Vec::new())); } @@ -438,8 +440,9 @@ mod tests { assert_eq!( shown, [ - ToolInfo::new("first", "The first tool.", SCHEMA).wire_name("Look"), - ToolInfo::new("lite", format!("{ENTRY} saw {MODEL}"), OTHER_SCHEMA).changes_files(), + ToolInfo::new("first", "The first tool.", schema()).with_wire_name("Look"), + ToolInfo::new("lite", format!("{ENTRY} saw {MODEL}"), other_schema()) + .with_changes_files(true), ] ); } @@ -534,13 +537,10 @@ mod tests { } #[test] - fn parameters_that_differ_only_in_spacing_fail_because_the_text_is_compared() { - let Err(Failure::Rejected(reason)) = render("acme/spaced", &catalog()) else { - panic!("the render should be rejected"); - }; - assert!( - reason.contains("the catalog tool first with other parameters"), - "{reason}" + fn parameters_that_differ_only_in_spacing_pass_because_json_values_are_compared() { + assert_eq!( + render("acme/spaced", &catalog()), + Ok(catalog()[..1].to_vec()) ); } @@ -588,7 +588,11 @@ mod tests { fn offering_a_tool_the_instance_never_added_is_the_tests_own_fault() { let loaded = testing::load::().unwrap(); let run = loaded.new_pack("acme/plain").unwrap(); - let _shown = run.render(ENTRY, MODEL, &[ToolInfo::new("ghost", "A ghost.", SCHEMA)]); + let _shown = run.render( + ENTRY, + MODEL, + &[ToolInfo::new("ghost", "A ghost.", schema())], + ); } #[test] diff --git a/crates/runvil-plugin-sdk/src/tool.rs b/crates/runvil-plugin-sdk/src/tool.rs index 97ae4cf..1ecaed3 100644 --- a/crates/runvil-plugin-sdk/src/tool.rs +++ b/crates/runvil-plugin-sdk/src/tool.rs @@ -1,6 +1,6 @@ -//! A tool as data, [`ToolInfo`]; what one call of it is lent, -//! [`ToolCall`] and [`Caller`]; how the call ends, [`ToolOutput`] or -//! [`ToolError`]; and [`next_step`], which splits a long call into steps. +//! What one tool call is lent, [`ToolCall`] and [`Caller`]; how the call +//! ends, [`ToolOutput`] or [`ToolError`]; and [`next_step`], which splits +//! a long call into steps. use std::fmt; use std::future::Future; @@ -10,70 +10,6 @@ use std::task::{Context, Poll}; use crate::file::{Answer, Request, Requests}; use crate::{DirEntry, FileFuture, Stat}; -/// A tool described as data, which a [`Pack`](crate::Pack) lists in -/// [`Pack::tools`](crate::Pack::tools). -#[derive(Clone, Debug, PartialEq, Eq)] -#[non_exhaustive] -pub struct ToolInfo { - /// The tool's name within its Pack: 1 to 64 bytes of lowercase ASCII - /// letters, digits, `-`, `_`, and `.`, such as `fetch`. The Host puts - /// the Pack id before it to form the tool's id, as in `url/fetch`. - pub name: String, - /// The name a model calls the tool by: 1 to 64 bytes starting with an - /// ASCII letter, followed by ASCII letters, digits, `_`, and `-`. `None` - /// lets the Host derive it from the tool's id, as `url_fetch` from - /// `url/fetch`. - pub wire_name: Option, - /// What the tool does, for a model to read: non-empty, at most 65536 - /// bytes. - pub description: String, - /// The tool's parameters: the JSON text of a JSON Schema whose value - /// is an object, at most 65536 bytes. - pub parameters: String, - /// Whether a call of the tool changes files of its run. Of the calls - /// that one reply of a model asks for, the Host runs a call of such a - /// tool by itself, after the calls the reply lists before it, so two - /// changes of one reply happen in the order the reply lists them. - pub changes_files: bool, -} - -impl ToolInfo { - /// A tool named `name`, with the description a model reads and the - /// JSON text of its parameter schema, under the wire name the Host - /// derives. It says that its calls change no file. - #[must_use] - pub fn new( - name: impl Into, - description: impl Into, - parameters: impl Into, - ) -> ToolInfo { - ToolInfo { - name: name.into(), - wire_name: None, - description: description.into(), - parameters: parameters.into(), - changes_files: false, - } - } - - /// Sets the name a model calls the tool by. - #[must_use] - pub fn wire_name(mut self, wire_name: impl Into) -> ToolInfo { - self.wire_name = Some(wire_name.into()); - self - } - - /// Says that a call of the tool changes files of its run. A tool - /// that awaits [`ToolCall::write`], [`ToolCall::append`], - /// [`ToolCall::mkdir`], [`ToolCall::remove`], [`ToolCall::rename`], or - /// [`ToolCall::copy`] says so. - #[must_use] - pub fn changes_files(mut self) -> ToolInfo { - self.changes_files = true; - self - } -} - /// Who asked for a [`ToolCall`]. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] @@ -104,7 +40,8 @@ pub enum Caller { /// [`mkdir`](ToolCall::mkdir), [`remove`](ToolCall::remove), /// [`rename`](ToolCall::rename), and [`copy`](ToolCall::copy) change the /// run's files. A tool that awaits one of them says so in its -/// [`ToolInfo`], with [`ToolInfo::changes_files`]. +/// [`ToolInfo`](crate::ToolInfo), with +/// [`ToolInfo::with_changes_files`](crate::ToolInfo::with_changes_files). /// /// A path names a file of the run, with `/` between its segments, is at /// most 4096 bytes long, and is taken from the run's root whether or not @@ -120,8 +57,8 @@ impl<'a> ToolCall<'a> { ToolCall { state } } - /// The name of the called tool, as [`ToolInfo::name`] gave it. A Pack - /// with several tools matches on it to pick one. + /// The name of the called tool, as [`ToolInfo::name`](crate::ToolInfo::name) + /// gave it. A Pack with several tools matches on it to pick one. #[must_use] pub fn tool(&self) -> &'a str { &self.state.tool @@ -517,9 +454,7 @@ mod tests { use std::sync::atomic::{AtomicUsize, Ordering}; use std::task::{Context, Poll, Wake, Waker}; - use super::{ - CallState, Caller, ToolCall, ToolError, ToolErrorKind, ToolInfo, ToolOutput, next_step, - }; + use super::{CallState, Caller, ToolCall, ToolError, ToolErrorKind, ToolOutput, next_step}; use crate::file::Request; use crate::{FileError, FileErrorKind}; @@ -536,23 +471,6 @@ mod tests { } } - #[test] - fn a_tool_info_keeps_what_it_was_built_from_and_has_no_wire_name_until_one_is_set() { - let info = ToolInfo::new("fetch", "Fetches a page.", r#"{"type":"object"}"#); - assert_eq!(info.name, "fetch"); - assert_eq!(info.description, "Fetches a page."); - assert_eq!(info.parameters, r#"{"type":"object"}"#); - assert_eq!(info.wire_name, None); - assert_eq!(info.wire_name("Fetch").wire_name.as_deref(), Some("Fetch")); - } - - #[test] - fn a_tool_info_says_its_calls_change_files_only_once_it_is_told_so() { - let info = ToolInfo::new("save", "Saves a page.", r#"{"type":"object"}"#); - assert!(!info.changes_files); - assert!(info.changes_files().changes_files); - } - #[test] fn a_tool_call_lends_the_tool_name_the_arguments_and_the_resources() { let state = CallState::new("fetch", r#"{"url":"x"}"#, RESOURCES).with_origin( diff --git a/crates/runvil-plugin-sdk/src/tool_info.rs b/crates/runvil-plugin-sdk/src/tool_info.rs new file mode 100644 index 0000000..b7efb44 --- /dev/null +++ b/crates/runvil-plugin-sdk/src/tool_info.rs @@ -0,0 +1,508 @@ +//! Unified tool, prompt, and function metadata: [`ToolInfo`]. +//! +//! A [`ToolInfo`] describes one callable tool across catalog registration, +//! model-specific rendering, wire serialization, and prompt contract +//! inspection. Optional fields serialize only when `Some`, and execution flags +//! serialize only when `true`, keeping default JSON representations compact. + +use std::borrow::Cow; +use std::ops::Not; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// Metadata describing one callable tool, prompt contract, or function schema. +/// +/// Build a minimal definition with [`ToolInfo::new`] and chain the `with_*` +/// builders to attach pack membership, wire naming, display metadata, output +/// schemas, advisory hints, or execution flags: +/// +/// ```text +/// let tool = ToolInfo::new("fetch", "Fetch a URL.", schema) +/// .with_pack("web") +/// .with_read_only_hint(Some(true)); +/// ``` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[expect( + clippy::struct_excessive_bools, + reason = "the five execution flags are independent properties of one tool" +)] +pub struct ToolInfo { + /// The tool's name within its pack, or its standalone identifier. + pub name: String, + /// The pack identifier when the tool belongs to a pack, such as `"web"` + /// for `"web/fetch"`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pack: Option, + /// An explicit function name advertised to a model on the wire, overriding + /// the derived default. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wire_name: Option, + /// A short human-facing display title. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + /// Prose shown to the model or caller describing what the tool does. + pub description: String, + /// The JSON Schema object describing the tool's input parameters. + pub input_schema: Value, + /// An optional JSON Schema object describing the tool's structured output. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output_schema: Option, + /// Advisory hint stating whether the tool leaves its environment unchanged. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub read_only_hint: Option, + /// Advisory hint stating whether the tool may perform destructive changes. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub destructive_hint: Option, + /// Advisory hint stating whether repeated identical calls have one effect. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub idempotent_hint: Option, + /// Advisory hint stating whether the tool reaches external systems. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub open_world_hint: Option, + /// Whether script callers decode the tool's output text as structured JSON. + #[serde(default, skip_serializing_if = "Not::not")] + pub structured_output: bool, + /// Whether calls to this tool keep running past a cooperative stop signal. + #[serde(default, skip_serializing_if = "Not::not")] + pub survives_stop: bool, + /// Whether the tool inspects or discloses deferred tool definitions. + #[serde(default, skip_serializing_if = "Not::not")] + pub describes_tools: bool, + /// Whether only a model round may invoke the tool. + #[serde(default, skip_serializing_if = "Not::not")] + pub model_only_call: bool, + /// Whether a call to the tool modifies files in the run's workspace. + #[serde(default, skip_serializing_if = "Not::not")] + pub changes_files: bool, +} + +impl ToolInfo { + /// Builds a [`ToolInfo`] from its required `name`, `description`, and + /// `input_schema`, setting every optional field to `None` and every + /// execution flag to `false`. + #[must_use] + pub fn new( + name: impl Into, + description: impl Into, + input_schema: Value, + ) -> ToolInfo { + ToolInfo { + name: name.into(), + pack: None, + wire_name: None, + title: None, + description: description.into(), + input_schema, + output_schema: None, + read_only_hint: None, + destructive_hint: None, + idempotent_hint: None, + open_world_hint: None, + structured_output: false, + survives_stop: false, + describes_tools: false, + model_only_call: false, + changes_files: false, + } + } + + /// Sets the pack identifier for this tool. + #[must_use] + pub fn with_pack(mut self, pack: impl Into) -> Self { + self.pack = Some(pack.into()); + self + } + + /// Sets the explicit function name advertised to the model on the wire. + #[must_use] + pub fn with_wire_name(mut self, wire_name: impl Into) -> Self { + self.wire_name = Some(wire_name.into()); + self + } + + /// Sets the human-facing display title. + #[must_use] + pub fn with_title(mut self, title: impl Into) -> Self { + self.title = Some(title.into()); + self + } + + /// Replaces the tool's description. + #[must_use] + pub fn with_description(mut self, description: impl Into) -> Self { + self.description = description.into(); + self + } + + /// Replaces the tool's input parameter JSON Schema. + #[must_use] + pub fn with_input_schema(mut self, input_schema: Value) -> Self { + self.input_schema = input_schema; + self + } + + /// Sets the JSON Schema describing the tool's structured output. + #[must_use] + pub fn with_output_schema(mut self, output_schema: Value) -> Self { + self.output_schema = Some(output_schema); + self + } + + /// Sets the advisory read-only hint. + #[must_use] + pub fn with_read_only_hint(mut self, hint: Option) -> Self { + self.read_only_hint = hint; + self + } + + /// Sets the advisory destructive hint. + #[must_use] + pub fn with_destructive_hint(mut self, hint: Option) -> Self { + self.destructive_hint = hint; + self + } + + /// Sets the advisory idempotent hint. + #[must_use] + pub fn with_idempotent_hint(mut self, hint: Option) -> Self { + self.idempotent_hint = hint; + self + } + + /// Sets the advisory open-world hint. + #[must_use] + pub fn with_open_world_hint(mut self, hint: Option) -> Self { + self.open_world_hint = hint; + self + } + + /// Sets whether script callers decode the tool's output as structured JSON. + #[must_use] + pub fn with_structured_output(mut self, structured: bool) -> Self { + self.structured_output = structured; + self + } + + /// Sets whether calls to this tool keep running past a cooperative stop. + #[must_use] + pub fn with_survives_stop(mut self, survives: bool) -> Self { + self.survives_stop = survives; + self + } + + /// Sets whether the tool inspects or discloses deferred tool definitions. + #[must_use] + pub fn with_describes_tools(mut self, describes: bool) -> Self { + self.describes_tools = describes; + self + } + + /// Sets whether only a model round may invoke the tool. + #[must_use] + pub fn with_model_only_call(mut self, model_only: bool) -> Self { + self.model_only_call = model_only; + self + } + + /// Sets whether calls to this tool modify files in the run's workspace. + #[must_use] + pub fn with_changes_files(mut self, changes: bool) -> Self { + self.changes_files = changes; + self + } + + /// Returns the tool's name within its pack, or its standalone identifier. + #[must_use] + pub fn name(&self) -> &str { + &self.name + } + + /// Returns the pack identifier when the tool belongs to a pack. + #[must_use] + pub fn pack(&self) -> Option<&str> { + self.pack.as_deref() + } + + /// Returns the explicit wire name when one was set. + #[must_use] + pub fn wire_name(&self) -> Option<&str> { + self.wire_name.as_deref() + } + + /// Returns the human-facing display title when one was set. + #[must_use] + pub fn title(&self) -> Option<&str> { + self.title.as_deref() + } + + /// Returns the prose description of what the tool does. + #[must_use] + pub fn description(&self) -> &str { + &self.description + } + + /// Returns the JSON Schema for the tool's input parameters. + #[must_use] + pub fn input_schema(&self) -> &Value { + &self.input_schema + } + + /// Returns the JSON Schema for the tool's structured output, when set. + #[must_use] + pub fn output_schema(&self) -> Option<&Value> { + self.output_schema.as_ref() + } + + /// Returns the advisory read-only hint, when set. + #[must_use] + pub fn read_only_hint(&self) -> Option { + self.read_only_hint + } + + /// Returns the advisory destructive hint, when set. + #[must_use] + pub fn destructive_hint(&self) -> Option { + self.destructive_hint + } + + /// Returns the advisory idempotent hint, when set. + #[must_use] + pub fn idempotent_hint(&self) -> Option { + self.idempotent_hint + } + + /// Returns the advisory open-world hint, when set. + #[must_use] + pub fn open_world_hint(&self) -> Option { + self.open_world_hint + } + + /// Returns whether script callers decode the output text as structured JSON. + #[must_use] + pub fn structured_output(&self) -> bool { + self.structured_output + } + + /// Returns whether calls keep running past a cooperative stop signal. + #[must_use] + pub fn survives_stop(&self) -> bool { + self.survives_stop + } + + /// Returns whether the tool inspects or discloses deferred tool definitions. + #[must_use] + pub fn describes_tools(&self) -> bool { + self.describes_tools + } + + /// Returns whether only a model round may invoke the tool. + #[must_use] + pub fn model_only_call(&self) -> bool { + self.model_only_call + } + + /// Returns whether calls to this tool modify files in the run's workspace. + #[must_use] + pub fn changes_files(&self) -> bool { + self.changes_files + } + + /// Returns `"/"` when [`ToolInfo::pack`] is `Some`, or borrows + /// [`ToolInfo::name`] when ungrouped. + #[must_use] + pub fn qualified_name(&self) -> Cow<'_, str> { + match self.pack.as_deref() { + Some(pack) => Cow::Owned(format!("{pack}/{}", self.name)), + None => Cow::Borrowed(&self.name), + } + } + + /// Returns [`ToolInfo::wire_name`] when set, otherwise derives a wire name + /// from [`ToolInfo::pack`] (when `Some`) and [`ToolInfo::name`] by joining + /// `"_"` and replacing every `'/'` and `'.'` with `'_'`. + /// + /// When [`ToolInfo::pack`] is `None`, such as before a host attaches pack + /// membership, derivation uses [`ToolInfo::name`] alone. + #[must_use] + pub fn effective_wire_name(&self) -> Cow<'_, str> { + if let Some(wire) = self.wire_name.as_deref() { + Cow::Borrowed(wire) + } else if let Some(pack) = self.pack.as_deref() { + Cow::Owned(format!("{pack}_{}", self.name).replace(['/', '.'], "_")) + } else if self.name.contains(['/', '.']) { + Cow::Owned(self.name.replace(['/', '.'], "_")) + } else { + Cow::Borrowed(&self.name) + } + } +} + +#[cfg(test)] +mod tests { + use std::borrow::Cow; + + use serde_json::{Value, json}; + + use super::ToolInfo; + + fn object_schema() -> Value { + json!({ + "type": "object", + "properties": { + "url": { "type": "string" } + }, + "required": ["url"] + }) + } + + #[test] + fn new_sets_required_fields_and_defaults_optional_fields_and_flags() { + let schema = object_schema(); + let tool = ToolInfo::new("fetch", "Fetch a page.", schema.clone()); + + assert_eq!(tool.name(), "fetch"); + assert_eq!(tool.pack(), None); + assert_eq!(tool.wire_name(), None); + assert_eq!(tool.title(), None); + assert_eq!(tool.description(), "Fetch a page."); + assert_eq!(tool.input_schema(), &schema); + assert_eq!(tool.output_schema(), None); + assert_eq!(tool.read_only_hint(), None); + assert_eq!(tool.destructive_hint(), None); + assert_eq!(tool.idempotent_hint(), None); + assert_eq!(tool.open_world_hint(), None); + assert!(!tool.structured_output()); + assert!(!tool.survives_stop()); + assert!(!tool.describes_tools()); + assert!(!tool.model_only_call()); + assert!(!tool.changes_files()); + } + + #[test] + fn builders_and_getters_round_trip_every_field() { + let input = json!({ "type": "object" }); + let updated_input = object_schema(); + let output = json!({ "type": "object", "properties": { "ok": { "type": "boolean" } } }); + + let tool = ToolInfo::new("edit", "Initial.", input) + .with_pack("fs") + .with_wire_name("FsEdit") + .with_title("Edit File") + .with_description("Edit a file.") + .with_input_schema(updated_input.clone()) + .with_output_schema(output.clone()) + .with_read_only_hint(Some(false)) + .with_destructive_hint(Some(true)) + .with_idempotent_hint(Some(false)) + .with_open_world_hint(Some(true)) + .with_structured_output(true) + .with_survives_stop(true) + .with_describes_tools(true) + .with_model_only_call(true) + .with_changes_files(true); + + assert_eq!(tool.name(), "edit"); + assert_eq!(tool.pack(), Some("fs")); + assert_eq!(tool.wire_name(), Some("FsEdit")); + assert_eq!(tool.title(), Some("Edit File")); + assert_eq!(tool.description(), "Edit a file."); + assert_eq!(tool.input_schema(), &updated_input); + assert_eq!(tool.output_schema(), Some(&output)); + assert_eq!(tool.read_only_hint(), Some(false)); + assert_eq!(tool.destructive_hint(), Some(true)); + assert_eq!(tool.idempotent_hint(), Some(false)); + assert_eq!(tool.open_world_hint(), Some(true)); + assert!(tool.structured_output()); + assert!(tool.survives_stop()); + assert!(tool.describes_tools()); + assert!(tool.model_only_call()); + assert!(tool.changes_files()); + } + + #[test] + fn default_tool_info_serializes_compactly_and_round_trips() { + let tool = ToolInfo::new("ping", "Check health.", json!({ "type": "object" })); + let value = serde_json::to_value(&tool).expect("default ToolInfo serializes"); + assert_eq!( + value, + json!({ + "name": "ping", + "description": "Check health.", + "input_schema": { "type": "object" } + }) + ); + + let encoded = serde_json::to_string(&tool).expect("default ToolInfo encodes"); + let decoded: ToolInfo = + serde_json::from_str(&encoded).expect("compact ToolInfo deserializes"); + assert_eq!(decoded, tool); + } + + #[test] + fn populated_tool_info_round_trips_all_fields_through_json() { + let tool = ToolInfo::new("write", "Write text.", object_schema()) + .with_pack("std") + .with_wire_name("StdWrite") + .with_title("Write") + .with_output_schema(json!({ "type": "object" })) + .with_read_only_hint(Some(false)) + .with_destructive_hint(Some(true)) + .with_idempotent_hint(Some(true)) + .with_open_world_hint(Some(false)) + .with_structured_output(true) + .with_survives_stop(true) + .with_describes_tools(true) + .with_model_only_call(true) + .with_changes_files(true); + + let value = serde_json::to_value(&tool).expect("populated ToolInfo serializes"); + assert_eq!(value["read_only_hint"], json!(false)); + assert_eq!(value["open_world_hint"], json!(false)); + assert_eq!(value["changes_files"], json!(true)); + + let encoded = serde_json::to_string(&tool).expect("populated ToolInfo encodes"); + let decoded: ToolInfo = + serde_json::from_str(&encoded).expect("populated ToolInfo deserializes"); + assert_eq!(decoded, tool); + } + + #[test] + fn qualified_name_joins_pack_and_name_or_borrows_bare_name() { + let standalone = ToolInfo::new("search", "Search.", json!({ "type": "object" })); + assert!(matches!( + standalone.qualified_name(), + Cow::Borrowed("search") + )); + + let packed = ToolInfo::new("fetch", "Fetch.", json!({ "type": "object" })).with_pack("web"); + assert_eq!(packed.qualified_name(), "web/fetch"); + + let multi_segment = ToolInfo::new("tools/inspect", "Inspect.", json!({ "type": "object" })) + .with_pack("fixtures"); + assert_eq!(multi_segment.qualified_name(), "fixtures/tools/inspect"); + } + + #[test] + fn effective_wire_name_prefers_explicit_then_pack_then_sanitized_name() { + let bare = ToolInfo::new("search", "Search.", json!({ "type": "object" })); + assert!(matches!( + bare.effective_wire_name(), + Cow::Borrowed("search") + )); + + let dotted_bare = + ToolInfo::new("tools/inspect.v1", "Inspect.", json!({ "type": "object" })); + assert_eq!(dotted_bare.effective_wire_name(), "tools_inspect_v1"); + + let packed = ToolInfo::new("tools/inspect.v1", "Inspect.", json!({ "type": "object" })) + .with_pack("acme.dev"); + assert_eq!(packed.effective_wire_name(), "acme_dev_tools_inspect_v1"); + + let explicit = packed.with_wire_name("InspectTool"); + assert!(matches!( + explicit.effective_wire_name(), + Cow::Borrowed("InspectTool") + )); + } +} diff --git a/crates/runvil-plugin-sys/Cargo.toml b/crates/runvil-plugin-sys/Cargo.toml index e7e3602..57420f3 100644 --- a/crates/runvil-plugin-sys/Cargo.toml +++ b/crates/runvil-plugin-sys/Cargo.toml @@ -2,7 +2,7 @@ name = "runvil-plugin-sys" # The contract's version: `RV_API_MAJOR`.`RV_API_MINOR`, which a unit test # checks. -version = "0.8.0" +version = "0.9.0" description = "The C contract of a runvil Plugin, runvil_plugin.h, and its raw Rust mirror" edition.workspace = true # The floor a Plugin author's toolchain needs; CI's msrv job builds it. diff --git a/crates/runvil-plugin-sys/include/runvil_plugin.h b/crates/runvil-plugin-sys/include/runvil_plugin.h index bf0bb43..beca400 100644 --- a/crates/runvil-plugin-sys/include/runvil_plugin.h +++ b/crates/runvil-plugin-sys/include/runvil_plugin.h @@ -83,7 +83,7 @@ * * - A tool a Pack lists in `RV_PACK_NEW` is a catalog tool: the Host's * scripts call it by its id, a prompt offers it by that id, and its - * parameters are the same for the whole run. A tool that only a render + * input schema is the same for the whole run. A tool that only a render * lists is a model-facing tool: only a model calls it, and no script * can name it. * - When a section entry's first model round is about to advertise its @@ -103,26 +103,27 @@ * Plugin ignores a key it does not know. * - `offered` points at `offered_len` `RvToolInfo` values, one for each * tool the section offered from this Pack in this set, in the order - * they were offered. Each `name` is the tool's name within its Pack. - * `wire_name` is empty when the Host derives the name. `description` - * and `parameters` are the catalog's, and `parameters` is the Host's - * own text of the schema, so its spacing and key order can differ from - * the text the Plugin gave `RV_PACK_NEW`. `flags` are the catalog's. + * they were offered. Each `json` holds the JSON text of that tool's + * `ToolInfo` object, with `name` set to the tool's name within its + * Pack, `description` and `input_schema` set to the catalog's, and + * optional fields and execution flags included when set. Because the + * Host writes its own JSON text, spacing and key order can differ from + * the text the Plugin gave `RV_PACK_NEW`. * - The Plugin answers by calling `add_tool` once for each tool the model * is shown, in the order it is shown, and returning `RV_OK`. A tool * the Plugin leaves out is one the model is not shown. Each tool it * adds is checked as `RV_PACK_NEW` checks a tool. * - A tool added under the `name` of an offered tool is that catalog - * tool. It may change its `wire_name` and `description`, and its - * `parameters` must be those the Host lent, so a catalog tool's name - * always means one parameter schema. A tool added under any other name - * is a model-facing tool, with the `flags` the Plugin gives it, such - * as `RV_TOOL_CHANGES_FILES`. A model-facing tool is the way to show - * a model other parameters than the catalog's: the Plugin lists it - * under a name of its own and answers its calls by that name. A name - * that is a catalog tool of the run which the section did not offer in - * this set is not free for a model-facing tool: the Host fails the - * round that asked for the render. + * tool. It may change its `wire_name`, `description`, and other + * metadata, and its `input_schema` must equal the JSON object the Host + * lent, so a catalog tool's name always means one input schema. A tool + * added under any other name is a model-facing tool, with the flags the + * Plugin gives it, such as `changes_files`. A model-facing tool is the + * way to show a model another input schema than the catalog's: the + * Plugin lists it under a name of its own and answers its calls by that + * name. A name that is a catalog tool of the run which the section did + * not offer in this set is not free for a model-facing tool: the Host + * fails the round that asked for the render. * - A Plugin that does not render answers `RV_ERR_UNSUPPORTED`, and the * Host shows the model the offered tools as they are. A Plugin that * cannot render declines with `refuse`, which returns @@ -188,13 +189,13 @@ * an object with one key for each resource the Host provides, such as * `runvil/web-search`, and `{}` when it provides none. What a resource * holds is between the Host and the Plugins that read it. - * - A tool whose calls change files sets `RV_TOOL_CHANGES_FILES` in the - * `flags` of its `RvToolInfo`. Of the calls that one reply of a model + * - A tool whose calls change files sets `"changes_files": true` in the + * `json` of its `RvToolInfo`. Of the calls that one reply of a model * asks for, the Host runs a call of such a tool by itself: the call * starts when every call the reply lists before it has ended, and the * calls the reply lists after it start when it has ended. So two * changes of one reply happen in the order the reply lists them. The - * calls of tools without the flag may run at the same time. + * calls of tools without `changes_files` may run at the same time. * * # Files * @@ -347,9 +348,9 @@ * that has a `size` field, which shows whether the field is there, such * as a function at the end of a verb's arguments struct; a verb with an * arguments struct of its own; or a number for a result kind, a file - * type, a file error kind, or a tool flag. A struct with no `size` - * field never changes. A Plugin built for 1.n loads in a Host that - * reports major version 1 and a minor version of at least n. + * type, or a file error kind. A struct with no `size` field never + * changes. A Plugin built for 1.n loads in a Host that reports major + * version 1 and a minor version of at least n. */ #ifndef RUNVIL_PLUGIN_H @@ -385,7 +386,7 @@ typedef struct RvCall RvCall; /** * The contract's minor version, which `RvHost` reports. */ -#define RV_API_MINOR 8 +#define RV_API_MINOR 9 /** * The most bytes in a name segment, a version, or a wire name. @@ -403,10 +404,15 @@ typedef struct RvCall RvCall; #define RV_MAX_PATH 4096 /** - * The most bytes in a tool's description, and in its parameters. + * The most bytes in a tool's description. */ #define RV_MAX_TOOL_TEXT 65536 +/** + * The most bytes in the JSON text of an `RvToolInfo`. + */ +#define RV_MAX_TOOL_JSON 262144 + /** * The most bytes in the text of a tool call's result. */ @@ -448,13 +454,6 @@ typedef uint32_t RvFileType; */ typedef uint32_t RvFileErrorKind; -/** - * What a tool does beyond answering its calls, in the `flags` of an - * `RvToolInfo`: one bit for each `RV_TOOL_` constant. A fixed-width - * integer, as `RvVerb` is. - */ -typedef uint32_t RvToolFlags; - /** * Who asked for a tool call, in an `RvToolCallArgs`. A fixed-width * integer, as `RvVerb` is. @@ -640,7 +639,22 @@ struct RvPackInfo { }; /** - * What a Pack instance tells `add_tool` about one of its tools. + * What a Pack instance tells `add_tool` about one of its tools, and what + * `offered` lends `RV_PACK_RENDER`. + * + * `json` is the UTF-8 JSON text (at most `RV_MAX_TOOL_JSON` bytes) of an + * object with: + * - required `name` (string, 1 to `RV_MAX_NAME` bytes, one name segment), + * `description` (non-empty string, at most `RV_MAX_TOOL_TEXT` bytes), and + * `input_schema` (JSON object); + * - optional `pack` (string), `wire_name` (string, 1 to `RV_MAX_NAME` bytes + * matching `[A-Za-z][A-Za-z0-9_-]{0,63}`), `title` (string), + * `output_schema` (JSON object), and boolean hints `read_only_hint`, + * `destructive_hint`, `idempotent_hint`, and `open_world_hint` (each omitted + * or `null` when unset); + * - optional boolean execution flags `structured_output`, `survives_stop`, + * `describes_tools`, `model_only_call`, and `changes_files` (each defaulting + * to `false` when omitted). */ struct RvToolInfo { /** @@ -648,31 +662,14 @@ struct RvToolInfo { */ uint32_t size; /** - * Zero, or `RV_TOOL_CHANGES_FILES`. A set bit that is no `RV_TOOL_` - * constant is a misuse. - */ - RvToolFlags flags; - /** - * The tool's name within its Pack: one name segment, such as `fetch`. + * Must be zero. */ - struct RvStr name; - /** - * The name a model calls the tool by: 1 to `RV_MAX_NAME` bytes - * starting with an ASCII letter, followed by ASCII letters, digits, `_`, - * and `-`. Empty lets the Host derive it from the tool's id, as - * `url_fetch` from `url/fetch`. - */ - struct RvStr wire_name; - /** - * What the tool does, for a model to read: non-empty, at most - * `RV_MAX_TOOL_TEXT` bytes. - */ - struct RvStr description; + uint32_t reserved; /** - * The tool's parameters: the JSON text of a JSON Schema whose value is - * an object, at most `RV_MAX_TOOL_TEXT` bytes. + * The JSON text of the tool's `ToolInfo` object, at most + * `RV_MAX_TOOL_JSON` bytes. */ - struct RvStr parameters; + struct RvStr json; }; /** @@ -1215,11 +1212,6 @@ struct RvCall { */ #define RV_FILE_ERROR_NOT_EMPTY 8 -/** - * A call of the tool changes files of its run. Bit 0. - */ -#define RV_TOOL_CHANGES_FILES 1 - /** * A model round asked for the call. */ diff --git a/crates/runvil-plugin-sys/src/lib.rs b/crates/runvil-plugin-sys/src/lib.rs index f6fa5c7..a870d51 100644 --- a/crates/runvil-plugin-sys/src/lib.rs +++ b/crates/runvil-plugin-sys/src/lib.rs @@ -78,7 +78,7 @@ //! //! - A tool a Pack lists in [`RV_PACK_NEW`] is a catalog tool: the Host's //! scripts call it by its id, a prompt offers it by that id, and its -//! parameters are the same for the whole run. A tool that only a render +//! input schema is the same for the whole run. A tool that only a render //! lists is a model-facing tool: only a model calls it, and no script //! can name it. //! - When a section entry's first model round is about to advertise its @@ -98,26 +98,27 @@ //! Plugin ignores a key it does not know. //! - `offered` points at `offered_len` [`RvToolInfo`] values, one for each //! tool the section offered from this Pack in this set, in the order -//! they were offered. Each `name` is the tool's name within its Pack. -//! `wire_name` is empty when the Host derives the name. `description` -//! and `parameters` are the catalog's, and `parameters` is the Host's -//! own text of the schema, so its spacing and key order can differ from -//! the text the Plugin gave [`RV_PACK_NEW`]. `flags` are the catalog's. +//! they were offered. Each `json` holds the JSON text of that tool's +//! `ToolInfo` object, with `name` set to the tool's name within its +//! Pack, `description` and `input_schema` set to the catalog's, and +//! optional fields and execution flags included when set. Because the +//! Host writes its own JSON text, spacing and key order can differ from +//! the text the Plugin gave [`RV_PACK_NEW`]. //! - The Plugin answers by calling `add_tool` once for each tool the model //! is shown, in the order it is shown, and returning [`RV_OK`]. A tool //! the Plugin leaves out is one the model is not shown. Each tool it //! adds is checked as [`RV_PACK_NEW`] checks a tool. //! - A tool added under the `name` of an offered tool is that catalog -//! tool. It may change its `wire_name` and `description`, and its -//! `parameters` must be those the Host lent, so a catalog tool's name -//! always means one parameter schema. A tool added under any other name -//! is a model-facing tool, with the `flags` the Plugin gives it, such -//! as [`RV_TOOL_CHANGES_FILES`]. A model-facing tool is the way to show -//! a model other parameters than the catalog's: the Plugin lists it -//! under a name of its own and answers its calls by that name. A name -//! that is a catalog tool of the run which the section did not offer in -//! this set is not free for a model-facing tool: the Host fails the -//! round that asked for the render. +//! tool. It may change its `wire_name`, `description`, and other +//! metadata, and its `input_schema` must equal the JSON object the Host +//! lent, so a catalog tool's name always means one input schema. A tool +//! added under any other name is a model-facing tool, with the flags the +//! Plugin gives it, such as `changes_files`. A model-facing tool is the +//! way to show a model another input schema than the catalog's: the +//! Plugin lists it under a name of its own and answers its calls by that +//! name. A name that is a catalog tool of the run which the section did +//! not offer in this set is not free for a model-facing tool: the Host +//! fails the round that asked for the render. //! - A Plugin that does not render answers [`RV_ERR_UNSUPPORTED`], and the //! Host shows the model the offered tools as they are. A Plugin that //! cannot render declines with `refuse`, which returns @@ -183,13 +184,13 @@ //! an object with one key for each resource the Host provides, such as //! `runvil/web-search`, and `{}` when it provides none. What a resource //! holds is between the Host and the Plugins that read it. -//! - A tool whose calls change files sets [`RV_TOOL_CHANGES_FILES`] in the -//! `flags` of its [`RvToolInfo`]. Of the calls that one reply of a model +//! - A tool whose calls change files sets `"changes_files": true` in the +//! `json` of its [`RvToolInfo`]. Of the calls that one reply of a model //! asks for, the Host runs a call of such a tool by itself: the call //! starts when every call the reply lists before it has ended, and the //! calls the reply lists after it start when it has ended. So two //! changes of one reply happen in the order the reply lists them. The -//! calls of tools without the flag may run at the same time. +//! calls of tools without `changes_files` may run at the same time. //! //! # Files //! @@ -342,9 +343,9 @@ //! that has a `size` field, which shows whether the field is there, such //! as a function at the end of a verb's arguments struct; a verb with an //! arguments struct of its own; or a number for a result kind, a file -//! type, a file error kind, or a tool flag. A struct with no `size` -//! field never changes. A Plugin built for 1.n loads in a Host that -//! reports major version 1 and a minor version of at least n. +//! type, or a file error kind. A struct with no `size` field never +//! changes. A Plugin built for 1.n loads in a Host that reports major +//! version 1 and a minor version of at least n. //! //! ## Invariants //! @@ -357,9 +358,8 @@ //! - No dependencies and no `unsafe`: this crate only declares. //! - `include/runvil_plugin.h` is generated from this file and never //! edited by hand; `cargo test -p build-xtask` fails when it is stale. -//! - Status codes, verbs, result kinds, file types, file error kinds, and -//! tool flags keep their numbers in every version; the unit tests pin -//! them. +//! - Status codes, verbs, result kinds, file types, and file error kinds +//! keep their numbers in every version; the unit tests pin them. #![cfg_attr(not(test), no_std)] @@ -469,13 +469,6 @@ pub const RV_FILE_ERROR_ALREADY_EXISTS: RvFileErrorKind = 7; /// needs an empty one. pub const RV_FILE_ERROR_NOT_EMPTY: RvFileErrorKind = 8; -/// What a tool does beyond answering its calls, in the `flags` of an -/// [`RvToolInfo`]: one bit for each `RV_TOOL_` constant. A fixed-width -/// integer, as [`RvVerb`] is. -pub type RvToolFlags = u32; -/// A call of the tool changes files of its run. Bit 0. -pub const RV_TOOL_CHANGES_FILES: RvToolFlags = 1; - /// Who asked for a tool call, in an [`RvToolCallArgs`]. A fixed-width /// integer, as [`RvVerb`] is. pub type RvCaller = u32; @@ -487,7 +480,7 @@ pub const RV_CALLER_SCRIPT: RvCaller = 1; /// The contract's major version, which [`RvHost`] reports. pub const RV_API_MAJOR: u32 = 0; /// The contract's minor version, which [`RvHost`] reports. -pub const RV_API_MINOR: u32 = 8; +pub const RV_API_MINOR: u32 = 9; /// The most bytes in a name segment, a version, or a wire name. pub const RV_MAX_NAME: usize = 64; @@ -495,8 +488,10 @@ pub const RV_MAX_NAME: usize = 64; pub const RV_MAX_LINE: usize = 1024; /// The most bytes in a path a file function takes. pub const RV_MAX_PATH: usize = 4096; -/// The most bytes in a tool's description, and in its parameters. +/// The most bytes in a tool's description. pub const RV_MAX_TOOL_TEXT: usize = 65536; +/// The most bytes in the JSON text of an [`RvToolInfo`]. +pub const RV_MAX_TOOL_JSON: usize = 262_144; /// The most bytes in the text of a tool call's result. pub const RV_MAX_RESULT: usize = 16_777_216; /// The most bytes `file_write` or `file_append` takes in one request. @@ -624,28 +619,32 @@ pub struct RvPackInfo { pub description: RvStr, } -/// What a Pack instance tells `add_tool` about one of its tools. +/// What a Pack instance tells `add_tool` about one of its tools, and what +/// `offered` lends [`RV_PACK_RENDER`]. +/// +/// `json` is the UTF-8 JSON text (at most [`RV_MAX_TOOL_JSON`] bytes) of an +/// object with: +/// - required `name` (string, 1 to [`RV_MAX_NAME`] bytes, one name segment), +/// `description` (non-empty string, at most [`RV_MAX_TOOL_TEXT`] bytes), and +/// `input_schema` (JSON object); +/// - optional `pack` (string), `wire_name` (string, 1 to [`RV_MAX_NAME`] bytes +/// matching `[A-Za-z][A-Za-z0-9_-]{0,63}`), `title` (string), +/// `output_schema` (JSON object), and boolean hints `read_only_hint`, +/// `destructive_hint`, `idempotent_hint`, and `open_world_hint` (each omitted +/// or `null` when unset); +/// - optional boolean execution flags `structured_output`, `survives_stop`, +/// `describes_tools`, `model_only_call`, and `changes_files` (each defaulting +/// to `false` when omitted). #[repr(C)] #[derive(Debug)] pub struct RvToolInfo { /// The size of this struct in bytes: `sizeof(RvToolInfo)`. pub size: u32, - /// Zero, or [`RV_TOOL_CHANGES_FILES`]. A set bit that is no `RV_TOOL_` - /// constant is a misuse. - pub flags: RvToolFlags, - /// The tool's name within its Pack: one name segment, such as `fetch`. - pub name: RvStr, - /// The name a model calls the tool by: 1 to [`RV_MAX_NAME`] bytes - /// starting with an ASCII letter, followed by ASCII letters, digits, `_`, - /// and `-`. Empty lets the Host derive it from the tool's id, as - /// `url_fetch` from `url/fetch`. - pub wire_name: RvStr, - /// What the tool does, for a model to read: non-empty, at most - /// [`RV_MAX_TOOL_TEXT`] bytes. - pub description: RvStr, - /// The tool's parameters: the JSON text of a JSON Schema whose value is - /// an object, at most [`RV_MAX_TOOL_TEXT`] bytes. - pub parameters: RvStr, + /// Must be zero. + pub reserved: u32, + /// The JSON text of the tool's `ToolInfo` object, at most + /// [`RV_MAX_TOOL_JSON`] bytes. + pub json: RvStr, } /// How a tool call ended, which a step tells `finish`. @@ -919,10 +918,10 @@ mod tests { RV_FILE_ERROR_NOT_A_DIRECTORY, RV_FILE_ERROR_NOT_EMPTY, RV_FILE_ERROR_NOT_FOUND, RV_FILE_ERROR_OTHER, RV_FILE_TYPE_DIRECTORY, RV_FILE_TYPE_FILE, RV_FILE_TYPE_OTHER, RV_FILE_TYPE_SYMLINK, RV_MAX_LINE, RV_MAX_NAME, RV_MAX_PATH, RV_MAX_RESULT, - RV_MAX_TOOL_TEXT, RV_MAX_WRITE, RV_OK, RV_PACK_DELETE, RV_PACK_NEW, RV_PACK_RENDER, - RV_PENDING, RV_PLUGIN_LOAD, RV_PLUGIN_UNLOAD, RV_RESULT_BACKEND, + RV_MAX_TOOL_JSON, RV_MAX_TOOL_TEXT, RV_MAX_WRITE, RV_OK, RV_PACK_DELETE, RV_PACK_NEW, + RV_PACK_RENDER, RV_PENDING, RV_PLUGIN_LOAD, RV_PLUGIN_UNLOAD, RV_RESULT_BACKEND, RV_RESULT_INVALID_ARGUMENTS, RV_RESULT_OTHER, RV_RESULT_TRANSPORT, RV_RESULT_TRUSTED, - RV_RESULT_UNTRUSTED, RV_TOOL_CALL, RV_TOOL_CANCEL, RV_TOOL_CHANGES_FILES, + RV_RESULT_UNTRUSTED, RV_TOOL_CALL, RV_TOOL_CANCEL, }; #[cfg(target_pointer_width = "64")] use super::{ @@ -962,13 +961,10 @@ mod tests { #[test] #[cfg(target_pointer_width = "64")] fn the_tool_info_keeps_its_layout() { - assert_eq!(size_of::(), 72); + assert_eq!(size_of::(), 24); assert_eq!(offset_of!(RvToolInfo, size), 0); - assert_eq!(offset_of!(RvToolInfo, flags), 4); - assert_eq!(offset_of!(RvToolInfo, name), 8); - assert_eq!(offset_of!(RvToolInfo, wire_name), 24); - assert_eq!(offset_of!(RvToolInfo, description), 40); - assert_eq!(offset_of!(RvToolInfo, parameters), 56); + assert_eq!(offset_of!(RvToolInfo, reserved), 4); + assert_eq!(offset_of!(RvToolInfo, json), 8); } #[test] @@ -1131,15 +1127,11 @@ mod tests { assert_eq!(RV_MAX_LINE, 1024); assert_eq!(RV_MAX_PATH, 4096); assert_eq!(RV_MAX_TOOL_TEXT, 65536); + assert_eq!(RV_MAX_TOOL_JSON, 262_144); assert_eq!(RV_MAX_RESULT, 16_777_216); assert_eq!(RV_MAX_WRITE, 16_777_216); } - #[test] - fn the_tool_flags_keep_their_bits() { - assert_eq!(RV_TOOL_CHANGES_FILES, 1); - } - #[test] fn the_callers_keep_their_numbers() { assert_eq!(RV_CALLER_MODEL, 0); diff --git a/examples/hello-plugin/Cargo.toml b/examples/hello-plugin/Cargo.toml index f134894..8d6d045 100644 --- a/examples/hello-plugin/Cargo.toml +++ b/examples/hello-plugin/Cargo.toml @@ -14,6 +14,7 @@ crate-type = ["cdylib", "rlib"] [dependencies] runvil-plugin-sdk.workspace = true +serde_json.workspace = true [dev-dependencies] runvil-plugin-sdk = { workspace = true, features = ["test-support"] } diff --git a/examples/hello-plugin/src/lib.rs b/examples/hello-plugin/src/lib.rs index bb3ee66..360e22c 100644 --- a/examples/hello-plugin/src/lib.rs +++ b/examples/hello-plugin/src/lib.rs @@ -7,7 +7,7 @@ //! //! ## Invariants //! -//! - Uses `runvil-plugin-sdk` alone and writes no `unsafe`. +//! - Uses `runvil-plugin-sdk` and `serde_json`, and writes no `unsafe`. use runvil_plugin_sdk::{ BoxFuture, Pack, PackInfo, Plugin, Refusal, ToolCall, ToolError, ToolInfo, ToolOutput, @@ -43,7 +43,7 @@ impl Pack for Greeter { vec![ToolInfo::new( "greet", "Returns a greeting.", - r#"{"type":"object","properties":{}}"#, + serde_json::json!({"type": "object", "properties": {}}), )] } @@ -87,7 +87,7 @@ mod tests { [ToolInfo::new( "greet", "Returns a greeting.", - r#"{"type":"object","properties":{}}"#, + serde_json::json!({"type": "object", "properties": {}}), )] ); assert_eq!( diff --git a/plan/2026-12-02-2-unified-tool-info.plan.md b/plan/2026-12-02-2-unified-tool-info.plan.md new file mode 100644 index 0000000..d831019 --- /dev/null +++ b/plan/2026-12-02-2-unified-tool-info.plan.md @@ -0,0 +1,153 @@ +--- +name: Unified ToolInfo +overview: Consolidate all tool, MCP function, and prompt callable metadata into a single plain pub struct ToolInfo in gateway-types (using explicit Arc at shared catalog/binding/chat sites), sync its source verbatim into runvil-plugin-sdk over a JSON RvToolInfo C ABI (v0.9.0), and roll it out in small testable commits across Waves 1-4 (pushing to origin, opening PRs, waiting on CI, and merging to upstream at each wave). +todos: + - id: wave1-gateway-client + content: "Wave 1a (gateway-client): 3 testable commits (plan copy, add gateway_types::ToolInfo, replace ToolSchema with concrete Arc); verify all CI gates, push to origin, open PR to upstream, wait for green CI/reviews, and merge to upstream (SHA G)" + status: in_progress + - id: wave1-plugin-api + content: "Wave 1b (runvil-plugin-api, parallel with 1a once tool.rs is written): 3 testable commits (plan copy, sync tool_info.rs + xtask check + serde deps, bump contract to 0.9.0 with 24-byte JSON RvToolInfo); verify 1.85 MSRV + c-layout, push to origin, open PR, merge to upstream (SHA P)" + status: pending + - id: wave2-three-plugins + content: "Wave 2a (runvil-plugin-std, bashkit, web in parallel): 2 testable commits per repo (plan copy, pin SDK 0.9.0 at SHA P + Value/with_* updates); verify, push to origin, open PRs, and merge to upstream (SHAs S, B, W)" + status: pending + - id: wave2-harness + content: "Wave 2b (runvil-harness, parallel with 2a): 4 testable commits (plan copy, pin G + adopt ToolInfo across engine/harness/mcp on 0.8 loader, embed Arc in Frontmatter & drop Annotations, pin contract 0.9.0 at P + JSON RvToolInfo in loader/test-plugin + decisions); verify, push to origin, open PR, merge to upstream (SHA H)" + status: pending + - id: wave3-workshop-and-runvil + content: "Wave 3 (runvil-workshop, then runvil): 3 testable commits in workshop (plan copy, pin H/P/S/B/W + WorkshopBroker::chat, flatten prompt.tool_info() into /prompts/contract + UI tests), PR & merge to upstream (SHA K); then pin Workshop SHA K in runvil, PR & merge to upstream" + status: pending +isProject: false +--- + +# Unify Tool, Prompt, and MCP Metadata into `gateway_types::ToolInfo` + +## Goal and Design Summary + +Replace the separate tool, prompt-annotation, MCP-listing, and wire-schema structs across the fleet with one plain `pub struct ToolInfo` defined in `gateway-types` and copied verbatim into `runvil-plugin-sdk`: + +- **Plain struct + explicit `Arc` for \(O(1)\) sharing (zero `serde/rc` needed)**: `ToolInfo` is a plain Rust struct with `pub` fields matching `ModelInfo`, `Message`, and `Error` in `gateway-types`. Single-owner boundaries (`Pack::tools() -> Vec`, `Pack::render(...) -> Result>`, `PackToolSets` in `EffectAnswer::Render`) move `ToolInfo` by value in \(O(1)\) so `Pack::render` mutates fields naturally and `EffectAnswer::Render` serializes without enabling `serde/rc`. Shared multi-owner lifetimes (`ToolCatalog`, `OfferedTool`, `ToolBinding`, `LuaToolHandle`, `Prompt`, `Effect::Chat`, `InferenceBroker::chat`) hold `Arc` explicitly so schemas and descriptions are never deep-copied across runs, Lua VMs, or model rounds. +- **100% self-describing flat struct (zero helper structs)**: `ToolInfo` holds `name`, `pack` (losslessly splitting 2+ segment `ToolId`s at the first `/`, e.g. `pack = Some("fixtures")`, `name = "tools/inspect"`), `wire_name` (plus `effective_wire_name` and `qualified_name` helpers), `title`, `description`, `input_schema`, optional `output_schema`, the 4 closed MCP hints (`read_only_hint`, `destructive_hint`, `idempotent_hint`, `open_world_hint`), and the 5 Engine execution flags (`structured_output`, `survives_stop`, `describes_tools`, `model_only_call`, `changes_files`). +- **Third-party safe & Engine-stage validated**: `ToolInfo::new` is infallible (preserving Engine tests that place unvalidated schemas into `ToolCatalog` and reject them at `scope` freeze), `output_schema: Option` is descriptive and optional, and `structured_output: bool` remains the explicit opt-in switch for Lua `tools.call` JSON decoding. +- **Standalone plugin repo**: `tool.rs` uses only `std`, `serde`, and `serde_json` (Rust 1.85 syntax, functions `<= 100` lines and `<= 7` args, no `#[non_exhaustive]`) and is copied into `runvil-plugin-sdk` and committed to Git, passing JSON text across `RvToolInfo` in C ABI v0.9.0. + +## Git, Commit, PR, and Upstream Merge Protocol + +Every downstream `Cargo.toml` pins `https://github.com/cppalliance/` (`upstream`) by exact commit SHA, while local `master` pushes to `git@github.com:vinniefalco/.git` (`origin`). Therefore each wave completes its `origin` push -> PR -> green CI -> `upstream` merge cycle before the next wave pins its merged `upstream` SHA: + +1. **Stay on `master`** (no topical branches; `origin` is the fork, `upstream` is `cppalliance/*`). Sync `master` with `upstream/master` before starting each repo. +2. **Plan copy commit first**: Commit 1 in every touched repo adds `plan/2026-12-02-2-unified-tool-info.plan.md` so every commit message follows `.cursor/rules/commit.mdc` (`Plan: /plan/2026-12-02-2-unified-tool-info.plan.md`). +3. **Every commit is independently green**: Before each `git commit`, run `cargo fmt`, `cargo clippy` (warnings denied), and the workspace test suite (+ `xtask` / `public-api` / MSRV checks where applicable) so `git bisect` passes at every single commit. +4. **PR & merge per wave**: Push `master` to `origin`, open a PR against `cppalliance/:master` via `gh pr create`, monitor GitHub Actions checks and review comments until green, address any findings in follow-up testable commits, merge the PR to `upstream` via `gh pr merge`, and `git fetch upstream && git merge --ff-only upstream/master` locally to capture the exact merged `upstream` SHA for the next wave. + +```mermaid +flowchart TD + GatewayTypes["gateway-types"] -->|"copy tool.rs"| PluginApi["plugin-api 0.9"] + GatewayTypes -->|"upstream SHA G"| Harness["runvil-harness"] + PluginApi -->|"upstream SHA P"| PluginStd["plugin-std"] + PluginApi -->|"upstream SHA P"| PluginBash["plugin-bashkit"] + PluginApi -->|"upstream SHA P"| PluginWeb["plugin-web"] + PluginApi -->|"upstream SHA P"| Harness + PluginStd -->|"upstream SHA S"| Workshop["runvil-workshop"] + PluginBash -->|"upstream SHA B"| Workshop + PluginWeb -->|"upstream SHA W"| Workshop + Harness -->|"upstream SHA H"| Workshop + Workshop -->|"upstream SHA K"| Runvil["runvil"] +``` + +## Wave 1: `gateway-client` and `runvil-plugin-api` (Parallel PRs once `tool.rs` is written) + +### Wave 1a: `gateway-client` (3 Testable Commits -> Merged Upstream SHA `G`) + +- **Commit 1**: Add `plan/2026-12-02-2-unified-tool-info.plan.md`. +- **Commit 2 (additive, keeps `ToolSchema` compiling)**: Add `[gateway-client/crates/gateway-types/src/tool.rs](c:/Users/Vinnie/cursor/gateway-client/crates/gateway-types/src/tool.rs)` + unit tests, re-export `ToolInfo` from `[gateway-client/crates/gateway-types/src/lib.rs](c:/Users/Vinnie/cursor/gateway-client/crates/gateway-types/src/lib.rs)` and `[gateway-client/crates/gateway-client/src/lib.rs](c:/Users/Vinnie/cursor/gateway-client/crates/gateway-client/src/lib.rs)`, and update both `public-api.txt` snapshots: + - Rust 1.85 syntax (no `let` chains), no `#[non_exhaustive]`, `<= 100` lines and `<= 7` args per function, `use std::fmt;`, text-only doc fences, and intra-doc links scoped strictly to `ToolInfo`: + +```rust +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[expect( + clippy::struct_excessive_bools, + reason = "the five execution flags are independent properties of one tool" +)] +pub struct ToolInfo { + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pack: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wire_name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + pub description: String, + pub input_schema: Value, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output_schema: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub read_only_hint: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub destructive_hint: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub idempotent_hint: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub open_world_hint: Option, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub structured_output: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub survives_stop: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub describes_tools: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub model_only_call: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub changes_files: bool, +} +``` + + - Provide infallible `ToolInfo::new(name, description, input_schema)`, `with_*` builders, `effective_wire_name(&self) -> Cow<'_, str>`, `qualified_name(&self) -> Cow<'_, str>`, and field getters. +- **Commit 3 (replace `ToolSchema` with concrete `Arc`)**: Update `[gateway-client/crates/gateway-types/src/request.rs](c:/Users/Vinnie/cursor/gateway-client/crates/gateway-types/src/request.rs)`, `request-tests.rs`, `[gateway-client/crates/gateway-types/src/broker.rs](c:/Users/Vinnie/cursor/gateway-client/crates/gateway-types/src/broker.rs)`, and `[gateway-client/crates/gateway-client/src/transport.rs](c:/Users/Vinnie/cursor/gateway-client/crates/gateway-client/src/transport.rs)`. Keep `tools` concrete (`Option<&[Arc]>` on `build_request_body` and `GatewayClient::complete`; `Vec>` on `InferenceBroker::chat`) so all 22 bare `None` / `Some(&[])` call sites infer cleanly without `E0282`. Validate `(tool.effective_wire_name(), &tool.input_schema)` via `validate_tool_schema` (retaining `ErrorCode::ToolSchemaInvalid = 509`), refresh both `public-api.txt` files, verify all CI gates (`+1.88`, `dylint`, `deny`, `nextest`), push to `origin`, open PR, and merge to `upstream` -> SHA `G`. + +### Wave 1b: `runvil-plugin-api` v0.9.0 (3 Testable Commits -> Merged Upstream SHA `P`) + +- **Commit 1**: Add `plan/2026-12-02-2-unified-tool-info.plan.md`. +- **Commit 2 (sync `tool_info.rs` + `xtask` check, keeping 0.8 ABI intact)**: Add `serde` and `serde_json` to `[runvil-plugin-api/Cargo.toml](c:/Users/Vinnie/cursor/runvil-plugin-api/Cargo.toml)` and `[runvil-plugin-api/crates/runvil-plugin-sdk/Cargo.toml](c:/Users/Vinnie/cursor/runvil-plugin-api/crates/runvil-plugin-sdk/Cargo.toml)` (`runvil-plugin-sys` stays `#![no_std]` with zero dependencies), copy `tool.rs` verbatim to `[runvil-plugin-api/crates/runvil-plugin-sdk/src/tool_info.rs](c:/Users/Vinnie/cursor/runvil-plugin-api/crates/runvil-plugin-sdk/src/tool_info.rs)`, and add `sync-tool-info` check in `[runvil-plugin-api/crates/build-xtask/src/main.rs](c:/Users/Vinnie/cursor/runvil-plugin-api/crates/build-xtask/src/main.rs)`. Verify `+1.85 check` and `cargo test` pass. +- **Commit 3 (bump C contract & SDK to `0.9.0` with JSON `RvToolInfo`)**: + - Update `[runvil-plugin-api/crates/runvil-plugin-sys/src/lib.rs](c:/Users/Vinnie/cursor/runvil-plugin-api/crates/runvil-plugin-sys/src/lib.rs)` (`RV_API_MINOR = 9`, `RvToolInfo { size: u32, reserved: u32, json: RvStr }` size 24, `RV_MAX_TOOL_JSON = 262_144`, keeping `RV_MAX_TOOL_TEXT = 65_536` for `description`), regenerate `[runvil-plugin-api/crates/runvil-plugin-sys/include/runvil_plugin.h](c:/Users/Vinnie/cursor/runvil-plugin-api/crates/runvil-plugin-sys/include/runvil_plugin.h)`, and update `[runvil-plugin-api/tests/c-layout/src/lib.rs](c:/Users/Vinnie/cursor/runvil-plugin-api/tests/c-layout/src/lib.rs)` + `layout.c`. + - Switch `runvil-plugin-sdk` (`src/tool.rs`, `src/entry/{pack,tool,file}.rs`, `src/testing.rs`, `src/testing/{pack,render,fixture}.rs`, `examples/hello-plugin/src/lib.rs`, `AGENTS.md`, `README.md`) to re-export `tool_info::ToolInfo`, keeping `let jsons: Vec` alive across `extern "C"` render calls and updating `Mode::Respaced` in `testing/render.rs` for semantic JSON `Value` comparison. + - Verify all CI checks (`+1.85`, `c-layout`, `clippy`, `doc`), push to `origin`, open PR, and merge to `upstream` -> SHA `P`. + +## Wave 2: Three Plugin Repos + `runvil-harness` (4 Parallel PRs once `G` and `P` Merge) + +### Wave 2a: `runvil-plugin-std`, `runvil-plugin-bashkit`, and `runvil-plugin-web` (2 Testable Commits Each -> Merged SHAs `S`, `B`, `W`) + +In each of `[runvil-plugin-std](c:/Users/Vinnie/cursor/runvil-plugin-std)`, `[runvil-plugin-bashkit](c:/Users/Vinnie/cursor/runvil-plugin-bashkit)`, and `[runvil-plugin-web](c:/Users/Vinnie/cursor/runvil-plugin-web)` independently in parallel: +- **Commit 1**: Add `plan/2026-12-02-2-unified-tool-info.plan.md`. +- **Commit 2**: Pin `runvil-plugin-sdk = "0.9.0"` at `P`, pass `serde_json::Value` directly to `ToolInfo::new` using `.with_wire_name(...)` and `.with_changes_files(true)`, update `[ToolInfo::with_changes_files]` doc link in `[runvil-plugin-std/crates/plugin-std/src/lib.rs](c:/Users/Vinnie/cursor/runvil-plugin-std/crates/plugin-std/src/lib.rs)`, and update `tool.input_schema` assertions in `pack-tests.rs` and `web-tests.rs`. +- Verify all checks (`build-checks`, `clippy`, `test`, `doc`), push to `origin`, open PRs, and merge to `upstream` -> SHAs `S`, `B`, `W`. + +### Wave 2b: `runvil-harness` (4 Testable Commits -> Merged Upstream SHA `H`) + +- **Commit 1**: Add `plan/2026-12-02-2-unified-tool-info.plan.md`. +- **Commit 2 (pin `gateway-types` at `G` and unify `ToolInfo` across Engine, Harness, and `plugin-mcp` while keeping loader on 0.8)**: + - Update `[runvil-harness/Cargo.toml](c:/Users/Vinnie/cursor/runvil-harness/Cargo.toml)` to pin `gateway-client` / `gateway-types` at `G`. + - Delete `runvil_types::tools::ToolInfo` in `[runvil-harness/crates/runvil-internal/types/src/tools.rs](c:/Users/Vinnie/cursor/runvil-harness/crates/runvil-internal/types/src/tools.rs)` and re-export `gateway_types::ToolInfo`. Split 2+ segment `ToolId`s at the first `/` (`pack` + `name`) and index `(ToolId, Arc)` inside `ToolCatalog`, `OfferedTool::Catalog`, `ToolBinding`, and `LuaToolHandle` (keeping `.id() -> &ToolId` borrowed at all 30+ Engine sites and `.parameters` userdata reading `input_schema`). + - Update `Effect::Chat` (`tools: Vec>`), `scope.rs`, `RunPacks`, `plugin-mcp` (`rmcp::model::Tool` -> `Arc` preserving `title`, `output_schema`, and hints while keeping `mcp/get_dynamic_tools` output unchanged), `harness-plugin-loader` (adapting 0.8 `RvToolInfo` into new `ToolInfo`), `harness-gateway-client`, and facades (`runvil-engine`, `runvil`, dropping `ToolSchema` re-exports and blessing `public-api.txt`). Every workspace test and `xtask` check passes at this commit. +- **Commit 3 (embed `Arc` in `Frontmatter` / `Prompt` and drop `pub struct Annotations`)**: + - In `[runvil-harness/crates/runvil-internal/prompt/src/frontmatter.rs](c:/Users/Vinnie/cursor/runvil-harness/crates/runvil-internal/prompt/src/frontmatter.rs)` and `prompt.rs`, keep private `RawAnnotations` so every YAML error message and span test in `frontmatter-tests-annotations.rs` stays identical, build `tool: Arc` on `Frontmatter` (keeping `.name()`, `.description()`, `.title()`, `.args()` delegating on `Frontmatter` and adding `Frontmatter::tool_info` + `Prompt::tool_info`), remove `Annotations` from `runvil-engine` and `runvil`, and bless `public-api.txt`. +- **Commit 4 (pin `runvil-plugin-sys = "0.9.0"` at `P` and switch loader + `test-plugin` to JSON `RvToolInfo`)**: + - Pin `runvil-plugin-sys = "0.9.0"` at `P` in `Cargo.toml`. + - Delete `AddedTool`, `Offered`, and `raw_parameters` in `[runvil-harness/crates/harness-internal/plugin-loader/src/pack.rs](c:/Users/Vinnie/cursor/runvil-harness/crates/harness-internal/plugin-loader/src/pack.rs)` and `session.rs`, deserializing `RvToolInfo.json` straight into `ToolInfo` (keeping `Vec` alive across `send_render`). + - Update zero-dep `[runvil-harness/crates/harness-internal/test-plugin/src/lib.rs](c:/Users/Vinnie/cursor/runvil-harness/crates/harness-internal/test-plugin/src/lib.rs)` + `lib-tests.rs` to contract `0.9` (`size == 24`, balanced-brace `object_of` helper for `"shape"`), add a `build-xtask` sync check when sibling repos are present, and update `decisions/tools-and-packs.md` and `decisions/prompt-language.md`. +- Run full pre-push + CI suite (`docs-claims.mjs`, `clippy`, `nextest`, `xtask tidy`, `+nightly-2026-09-05 xtask api`, `dylint`, `deny`), push to `origin`, open PR, and merge to `upstream` -> SHA `H`. + +## Wave 3: `runvil-workshop` and `runvil` (Sequential Final Wave) + +### Wave 3a: `runvil-workshop` (3 Testable Commits -> Merged Upstream SHA `K`) + +- **Commit 1**: Add `plan/2026-12-02-2-unified-tool-info.plan.md`. +- **Commit 2 (pins + broker)**: Update `[runvil-workshop/Cargo.toml](c:/Users/Vinnie/cursor/runvil-workshop/Cargo.toml)` to pin `runvil-harness` (`H`), `runvil-plugin-sdk` `0.9.0` (`P`), and `std-plugin` (`S`), `bashkit-plugin` (`B`), `web-plugin` (`W`), and switch `WorkshopBroker::chat` in `[runvil-workshop/crates/workshop/server/src/agents/broker.rs](c:/Users/Vinnie/cursor/runvil-workshop/crates/workshop/server/src/agents/broker.rs)` to `Vec>`. Verify `cargo test` and `xtask tidy`. +- **Commit 3 (`/prompts/contract` + UI)**: Flatten `&**prompt.tool_info()` onto `ContractResponse` in `[runvil-workshop/crates/workshop/server/src/routes/prompts.rs](c:/Users/Vinnie/cursor/runvil-workshop/crates/workshop/server/src/routes/prompts.rs)` (keeping explicit `null` for absent `runvil` and `max_tool_iterations`), and update `prompts-tests.rs`, `[runvil-workshop/crates/workshop/ui/src/services/run-api.ts](c:/Users/Vinnie/cursor/runvil-workshop/crates/workshop/ui/src/services/run-api.ts)`, `run-rows.ts`, `test/run-api.mjs`, and `test/run-panel.mjs`. +- Verify Rust + UI tests + `xtask tidy`, push to `origin`, open PR, and merge to `upstream` -> SHA `K`. + +### Wave 3b: `runvil` (2 Testable Commits -> Merged Upstream) + +- **Commit 1**: Add `plan/2026-12-02-2-unified-tool-info.plan.md`. +- **Commit 2**: Pin `[workspace.metadata.workshop]` in `[runvil/Cargo.toml](c:/Users/Vinnie/cursor/runvil/Cargo.toml)` to SHA `K`, verify `xtask`, push to `origin`, open PR, and merge to `upstream`. diff --git a/tests/c-layout/layout.c b/tests/c-layout/layout.c index 33deafc..0516865 100644 --- a/tests/c-layout/layout.c +++ b/tests/c-layout/layout.c @@ -57,14 +57,10 @@ static const RvLayoutEntry ENTRIES[] = { OFFSET(RvPackInfo, reserved), OFFSET(RvPackInfo, name), OFFSET(RvPackInfo, description), - SIZE(RvToolFlags), SIZE(RvToolInfo), OFFSET(RvToolInfo, size), - OFFSET(RvToolInfo, flags), - OFFSET(RvToolInfo, name), - OFFSET(RvToolInfo, wire_name), - OFFSET(RvToolInfo, description), - OFFSET(RvToolInfo, parameters), + OFFSET(RvToolInfo, reserved), + OFFSET(RvToolInfo, json), SIZE(RvResultKind), SIZE(RvToolResult), OFFSET(RvToolResult, size), @@ -165,7 +161,6 @@ static const RvLayoutEntry ENTRIES[] = { VALUE(RV_FILE_ERROR_IO), VALUE(RV_FILE_ERROR_ALREADY_EXISTS), VALUE(RV_FILE_ERROR_NOT_EMPTY), - VALUE(RV_TOOL_CHANGES_FILES), VALUE(RV_CALLER_MODEL), VALUE(RV_CALLER_SCRIPT), VALUE(RV_API_MAJOR), @@ -174,6 +169,7 @@ static const RvLayoutEntry ENTRIES[] = { VALUE(RV_MAX_LINE), VALUE(RV_MAX_PATH), VALUE(RV_MAX_TOOL_TEXT), + VALUE(RV_MAX_TOOL_JSON), VALUE(RV_MAX_RESULT), VALUE(RV_MAX_WRITE), }; diff --git a/tests/c-layout/src/lib.rs b/tests/c-layout/src/lib.rs index 50b7d3a..0ef146f 100644 --- a/tests/c-layout/src/lib.rs +++ b/tests/c-layout/src/lib.rs @@ -27,14 +27,13 @@ mod tests { RV_FILE_ERROR_NOT_A_DIRECTORY, RV_FILE_ERROR_NOT_EMPTY, RV_FILE_ERROR_NOT_FOUND, RV_FILE_ERROR_OTHER, RV_FILE_TYPE_DIRECTORY, RV_FILE_TYPE_FILE, RV_FILE_TYPE_OTHER, RV_FILE_TYPE_SYMLINK, RV_MAX_LINE, RV_MAX_NAME, RV_MAX_PATH, RV_MAX_RESULT, - RV_MAX_TOOL_TEXT, RV_MAX_WRITE, RV_OK, RV_PACK_DELETE, RV_PACK_NEW, RV_PACK_RENDER, - RV_PENDING, RV_PLUGIN_LOAD, RV_PLUGIN_UNLOAD, RV_RESULT_BACKEND, + RV_MAX_TOOL_JSON, RV_MAX_TOOL_TEXT, RV_MAX_WRITE, RV_OK, RV_PACK_DELETE, RV_PACK_NEW, + RV_PACK_RENDER, RV_PENDING, RV_PLUGIN_LOAD, RV_PLUGIN_UNLOAD, RV_RESULT_BACKEND, RV_RESULT_INVALID_ARGUMENTS, RV_RESULT_OTHER, RV_RESULT_TRANSPORT, RV_RESULT_TRUSTED, - RV_RESULT_UNTRUSTED, RV_TOOL_CALL, RV_TOOL_CANCEL, RV_TOOL_CHANGES_FILES, RvBytes, RvCall, - RvCaller, RvDirEntries, RvDirEntry, RvFileAnswer, RvFileError, RvFileErrorKind, RvFileType, - RvHost, RvLoadArgs, RvPackInfo, RvPackNewArgs, RvPackRenderArgs, RvPluginInfo, - RvResultKind, RvStat, RvStatus, RvStr, RvToolCallArgs, RvToolFlags, RvToolInfo, - RvToolResult, RvVerb, RvWaker, + RV_RESULT_UNTRUSTED, RV_TOOL_CALL, RV_TOOL_CANCEL, RvBytes, RvCall, RvCaller, RvDirEntries, + RvDirEntry, RvFileAnswer, RvFileError, RvFileErrorKind, RvFileType, RvHost, RvLoadArgs, + RvPackInfo, RvPackNewArgs, RvPackRenderArgs, RvPluginInfo, RvResultKind, RvStat, RvStatus, + RvStr, RvToolCallArgs, RvToolInfo, RvToolResult, RvVerb, RvWaker, }; /// One entry of the table in `layout.c`. @@ -166,14 +165,10 @@ mod tests { offset!(RvPackInfo, reserved), offset!(RvPackInfo, name), offset!(RvPackInfo, description), - size!(RvToolFlags), size!(RvToolInfo), offset!(RvToolInfo, size), - offset!(RvToolInfo, flags), - offset!(RvToolInfo, name), - offset!(RvToolInfo, wire_name), - offset!(RvToolInfo, description), - offset!(RvToolInfo, parameters), + offset!(RvToolInfo, reserved), + offset!(RvToolInfo, json), size!(RvResultKind), size!(RvToolResult), offset!(RvToolResult, size), @@ -287,7 +282,6 @@ mod tests { value!(RV_FILE_ERROR_IO), value!(RV_FILE_ERROR_ALREADY_EXISTS), value!(RV_FILE_ERROR_NOT_EMPTY), - value!(RV_TOOL_CHANGES_FILES), value!(RV_CALLER_MODEL), value!(RV_CALLER_SCRIPT), value!(RV_API_MAJOR), @@ -296,6 +290,7 @@ mod tests { value!(RV_MAX_LINE), value!(RV_MAX_PATH), value!(RV_MAX_TOOL_TEXT), + value!(RV_MAX_TOOL_JSON), value!(RV_MAX_RESULT), value!(RV_MAX_WRITE), ]