diff --git a/.vibelight/.gitignore b/.vibelight/.gitignore index d2ac727..39ece03 100644 --- a/.vibelight/.gitignore +++ b/.vibelight/.gitignore @@ -1,2 +1,3 @@ *.md *.html +*.js diff --git a/AGENTS.md b/AGENTS.md index 436691c..11f825a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,13 +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. - 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. - 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. 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, 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. ## Engineering diff --git a/Cargo.lock b/Cargo.lock index f42267a..ee6d3cf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -187,14 +187,14 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "runvil-plugin-sdk" -version = "0.6.0" +version = "0.7.0" dependencies = [ "runvil-plugin-sys", ] [[package]] name = "runvil-plugin-sys" -version = "0.6.0" +version = "0.7.0" [[package]] name = "rustix" diff --git a/README.md b/README.md index b150814..9118f09 100644 --- a/README.md +++ b/README.md @@ -10,12 +10,13 @@ The contract between a runvil Host and its Plugins: a C header, the raw Rust mir ## What a Plugin does -A Plugin loads once, names itself, and inserts its Packs. For each run that holds one of those Packs, the Host asks the Plugin for an instance of it, and the instance lists its tools. The Host then runs each tool call as a series of short steps, and frees the instance when the run ends. +A Plugin loads once, names itself, and inserts its Packs. For each run that holds one of those Packs, the Host asks the Plugin for an instance of it, and the instance lists its tools. When a section of a prompt is about to show a model its tools, the Host may ask the instance which tools that model should see. The Host then runs each tool call as a series of short steps, and frees the instance when the run ends. | Verb | When the Host sends it | |---|---| | `RV_PLUGIN_LOAD` | Once, as the Host inserts the Plugin | | `RV_PACK_NEW` | Once for each run that holds one of the Plugin's Packs | +| `RV_PACK_RENDER` | When a section entry's first model round is about to show its tools, once for each of the section's two sets of tools that holds a tool of the Pack | | `RV_TOOL_CALL` | Once for each step of a tool call, until a step ends the call | | `RV_TOOL_CANCEL` | When the Host abandons a call between two steps | | `RV_PACK_DELETE` | When the run ends | @@ -34,10 +35,10 @@ edition = "2024" crate-type = ["cdylib"] [dependencies] -runvil-plugin-sdk = { git = "https://github.com/cppalliance/runvil-plugin-api", tag = "api-v0.6.0" } +runvil-plugin-sdk = { git = "https://github.com/cppalliance/runvil-plugin-api", tag = "api-v0.7.0" } [dev-dependencies] -runvil-plugin-sdk = { git = "https://github.com/cppalliance/runvil-plugin-api", tag = "api-v0.6.0", features = ["test-support"] } +runvil-plugin-sdk = { git = "https://github.com/cppalliance/runvil-plugin-api", tag = "api-v0.7.0", features = ["test-support"] } ``` `src/lib.rs`: @@ -94,7 +95,38 @@ export_plugin!(Acme); - 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 panic in `load` or `new_pack` reaches the Host as a refusal, and a panic in a tool call ends that call as a failure. Neither unwinds into the Host. +- 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. + +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. + +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. + +```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(), + ); + 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. ### Testing @@ -128,17 +160,29 @@ assert_eq!(pack.files().read("/notes/b.md", 0, u64::MAX), Ok(b"three\n".to_vec() `file` and `dir` add a node and every directory on the way to it, and `fails` makes every operation on a path fail with the error given, a change included, as a path the run's policy denies does. A path that fails has nothing under it: `fails` refuses a directory that has entries, because those entries would stay readable, and a change that would make something under it fails with the same error. The calls of one `PackRun` share the tree, and `PackRun::files` lends it to the test, which reads what a call left there. The fake Host performs a file request on the tree once the step that made it has returned, and lends the call's next step the answer. +A Pack that renders is tested with `PackRun::render(entry, model, offered)`, which sends `RV_PACK_RENDER` with the tools the section offered and returns the tools the model is shown: + +```rust +// `Fs` is a Plugin that inserts the Pack `acme/fs` and renders as above. +let loaded = testing::load::().unwrap(); +let pack = loaded.new_pack("acme/fs").unwrap(); +let shown = pack.render("entry-1", r#"{"name":"claude-x"}"#, pack.tools()).unwrap(); +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. + ### Linked and library builds of one Plugin A Host can also link a Plugin crate in and pass `runvil_plugin_sdk::entry::` to the Harness's `insert_plugin`, so no symbol is exported. Two linked Plugins that both export `runvil_plugin` cannot share one binary, so a crate built both ways puts `export_plugin!` behind a feature of its own, as `examples/hello-plugin` does with `dll`. ## Writing a Plugin in C or C++ -Include `runvil_plugin.h` and define `RvStatus runvil_plugin(RvCall *call)`. The header's opening comment is the whole contract: the verbs, who calls what on which thread, and what the Plugin must free on every path. The functions a Plugin may call back come with the verb they serve, in its arguments struct behind `call->args` (an `RvLoadArgs` for `RV_PLUGIN_LOAD`, an `RvPackNewArgs` for `RV_PACK_NEW`, an `RvToolCallArgs` for `RV_TOOL_CALL`), and each takes that struct's `ctx` first. A step of a tool call makes one file request through one of the nine file functions in its `RvToolCallArgs`, such as `file_read` or `file_write`, and returns `RV_PENDING`, and the call's next step finds the answer behind `answer` in its own `RvToolCallArgs`. A step that returns `RV_PENDING` without a file request parks its call, and the Host owes it no step until a wake. So such a step first calls `args->waker.wake(args->waker.ctx)` when it wants the next step right away, or a thread of the Plugin makes that call later, when what the tool call waits for is there. `wake` takes the `ctx` of its own `RvWaker` and not the step's, and it is the one function a Plugin may call on any thread, until `RV_PLUGIN_UNLOAD` returns. `resources` in the same `RvToolCallArgs` is the JSON text of what the Host offers every Plugin. `tests/c-layout` compiles the header as C99 and as C++ on every CI run. +Include `runvil_plugin.h` and define `RvStatus runvil_plugin(RvCall *call)`. The header's opening comment is the whole contract: the verbs, who calls what on which thread, and what the Plugin must free on every path. The functions a Plugin may call back come with the verb they serve, in its arguments struct behind `call->args` (an `RvLoadArgs` for `RV_PLUGIN_LOAD`, an `RvPackNewArgs` for `RV_PACK_NEW`, an `RvPackRenderArgs` for `RV_PACK_RENDER`, an `RvToolCallArgs` for `RV_TOOL_CALL`), and each takes that struct's `ctx` first. A step of a tool call makes one file request through one of the nine file functions in its `RvToolCallArgs`, such as `file_read` or `file_write`, and returns `RV_PENDING`, and the call's next step finds the answer behind `answer` in its own `RvToolCallArgs`. A step that returns `RV_PENDING` without a file request parks its call, and the Host owes it no step until a wake. So such a step first calls `args->waker.wake(args->waker.ctx)` when it wants the next step right away, or a thread of the Plugin makes that call later, when what the tool call waits for is there. `wake` takes the `ctx` of its own `RvWaker` and not the step's, and it is the one function a Plugin may call on any thread, until `RV_PLUGIN_UNLOAD` returns. `resources` in the same `RvToolCallArgs` is the JSON text of what the Host offers every Plugin. A Plugin that shapes its tools for a model answers `RV_PACK_RENDER`: its `RvPackRenderArgs` holds the section entry in `entry`, the model as JSON text in `model`, the tools the section offered in `offered` and `offered_len`, and the functions `add_tool` and `refuse`. The Plugin calls `add_tool` once for each tool the model is shown and returns `RV_OK`. A Plugin that does not render answers `RV_ERR_UNSUPPORTED`, and the model is shown the offered tools as they are. `tests/c-layout` compiles the header as C99 and as C++ on every CI run. ## 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.6 loads only in a Host that speaks exactly 0.6. 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.7 loads only in a Host that speaks exactly 0.7. 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. diff --git a/crates/runvil-plugin-sdk/Cargo.toml b/crates/runvil-plugin-sdk/Cargo.toml index 300417b..a12afb2 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.6.0" +version = "0.7.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. diff --git a/crates/runvil-plugin-sdk/src/entry.rs b/crates/runvil-plugin-sdk/src/entry.rs index 28ac134..8563798 100644 --- a/crates/runvil-plugin-sdk/src/entry.rs +++ b/crates/runvil-plugin-sdk/src/entry.rs @@ -15,7 +15,7 @@ use std::panic::{self, AssertUnwindSafe}; use std::slice; use runvil_plugin_sys::{ - RV_ERR_MISUSE, RV_ERR_UNSUPPORTED, RV_PACK_DELETE, RV_PACK_NEW, RV_PLUGIN_LOAD, + RV_ERR_MISUSE, RV_ERR_UNSUPPORTED, RV_PACK_DELETE, RV_PACK_NEW, RV_PACK_RENDER, RV_PLUGIN_LOAD, RV_PLUGIN_UNLOAD, RV_TOOL_CALL, RV_TOOL_CANCEL, RvCall, RvStatus, RvStr, }; @@ -42,6 +42,8 @@ use crate::{Plugin, Refusal}; /// [`Plugin::new_pack`] and adding each of its /// [`tools`](crate::Pack::tools); /// - `RV_PACK_DELETE` by dropping that instance; +/// - `RV_PACK_RENDER` by calling [`Pack::render`](crate::Pack::render) +/// with the tools the section offered, and adding each tool it lists; /// - `RV_TOOL_CALL` by polling the future of /// [`Pack::call`](crate::Pack::call) once, with the answer to its file /// request at hand and a waker over the Host's waker for the call, and @@ -83,6 +85,7 @@ pub unsafe extern "C" fn entry(call: *mut RvCall) -> RvStatus { RV_PLUGIN_UNLOAD => plugin::unload::

(call), RV_PACK_NEW => pack::new::

(call), RV_PACK_DELETE => pack::delete(call), + RV_PACK_RENDER => pack::render(call), RV_TOOL_CALL => tool::step(call), RV_TOOL_CANCEL => tool::cancel(call), _ => RV_ERR_UNSUPPORTED, diff --git a/crates/runvil-plugin-sdk/src/entry/pack.rs b/crates/runvil-plugin-sdk/src/entry/pack.rs index e2b7898..acb3bf2 100644 --- a/crates/runvil-plugin-sdk/src/entry/pack.rs +++ b/crates/runvil-plugin-sdk/src/entry/pack.rs @@ -1,16 +1,21 @@ -//! `RV_PACK_NEW` and `RV_PACK_DELETE`: making one run's instance of a -//! Pack, adding its tools, and dropping the instance. +//! `RV_PACK_NEW`, `RV_PACK_RENDER`, and `RV_PACK_DELETE`: making one run's +//! instance of a Pack and adding its tools, listing the tools a model is +//! shown, and dropping the instance. +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_OK, RV_TOOL_CHANGES_FILES, RvCall, RvPackNewArgs, RvStatus, RvStr, RvToolInfo, + RV_ERR_MISUSE, RV_ERR_UNSUPPORTED, RV_OK, RV_TOOL_CHANGES_FILES, RvCall, RvPackNewArgs, + RvPackRenderArgs, RvStatus, RvStr, RvToolInfo, }; use super::{args, contain, panic_message, read_str, refuse, rv_str, size_field}; use crate::pack::PackRun; -use crate::{Pack, Plugin, Refusal, ToolInfo}; +use crate::{Pack, Plugin, Refusal, RenderContext, ToolInfo}; /// Answers `RV_PACK_NEW`: makes the instance with [`Plugin::new_pack`], /// adds each of its tools, and only then hands the instance to the Host. @@ -59,7 +64,7 @@ pub(super) unsafe fn new(call: *mut RvCall) -> RvStatus { } }; // SAFETY: `args` belongs to the open call, and this is its thread. - let status = unsafe { add_tools(args, &tools) }; + let status = unsafe { add_tools(args.add_tool, args.ctx, &tools) }; if status != RV_OK { contain(move || drop(pack)); return status; @@ -71,12 +76,16 @@ pub(super) unsafe fn new(call: *mut RvCall) -> RvStatus { RV_OK } -/// Adds each of `tools` to the instance being made, stopping at the first -/// status that is not `RV_OK`. +/// 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`. /// /// # Safety -/// `args` belongs to the `RV_PACK_NEW` call open on this thread. -unsafe fn add_tools(args: &RvPackNewArgs, tools: &[ToolInfo]) -> RvStatus { +/// `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 info = RvToolInfo { size: size_field::(), @@ -90,9 +99,9 @@ unsafe fn add_tools(args: &RvPackNewArgs, tools: &[ToolInfo]) -> RvStatus { description: rv_str(&tool.description), parameters: rv_str(&tool.parameters), }; - // SAFETY: the caller passes the open call's arguments, and `info` - // and its strings outlive the call. - let status = unsafe { (args.add_tool)(args.ctx, &raw const info) }; + // SAFETY: the caller passes the open call's function and `ctx`, and + // `info` and its strings outlive the call. + let status = unsafe { add_tool(ctx, &raw const info) }; if status != RV_OK { return status; } @@ -106,6 +115,109 @@ const EMPTY: RvStr = RvStr { 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 +/// instance is as it was after every outcome, so nothing is freed. +/// +/// # Safety +/// `call` points to a whole `RvCall` whose `pack_run` is NULL or the +/// pointer [`new`] set, not yet deleted, and whose `args` is NULL or an +/// `RvPackRenderArgs` that follows the contract. +pub(super) unsafe fn render(call: *mut RvCall) -> RvStatus { + // SAFETY: the caller makes `call` point to a whole `RvCall`, and the + // Host deletes the instance only after this call returns. + let Some(pack) = (unsafe { pack_of((*call).pack_run) }) else { + return RV_ERR_MISUSE; + }; + // SAFETY: for this verb `args` is NULL or an `RvPackRenderArgs`. + let args = match unsafe { args::(call) } { + Ok(args) => args, + Err(status) => return status, + }; + // SAFETY: the Host keeps both strings valid for the call. + let (entry, model) = unsafe { (read_str(args.entry), read_str(args.model)) }; + let (Some(entry), Some(model)) = (entry, model) else { + return RV_ERR_MISUSE; + }; + // SAFETY: the Host keeps the offered tools valid for the call. + let offered = match unsafe { copy_offered(args) } { + Ok(offered) => offered, + Err(status) => return status, + }; + let cx = RenderContext::new(entry, model); + let rendered = panic::catch_unwind(AssertUnwindSafe(|| pack.render(&cx, offered))); + let tools = match rendered { + Ok(Ok(tools)) => tools, + // SAFETY: `args` belongs to the open call. + Ok(Err(refusal)) => return unsafe { refuse(args.refuse, args.ctx, &refusal) }, + Err(payload) => { + let refusal = Refusal::new(format!( + "the Pack panicked while it rendered: {}", + panic_message(&*payload) + )); + // The payload belongs to the Pack, and its drop may panic. + contain(move || drop(payload)); + // SAFETY: as above. + return unsafe { refuse(args.refuse, args.ctx, &refusal) }; + } + }; + // SAFETY: `args` belongs to the open call, and this is its thread. + unsafe { add_tools(args.add_tool, args.ctx, &tools) } +} + +/// A copy of the tools a render is offered. +/// +/// # Safety +/// `args.offered` is NULL or points to `args.offered_len` readable +/// `RvToolInfo` values whose strings are valid, for the call. +unsafe fn copy_offered(args: &RvPackRenderArgs) -> Result, RvStatus> { + if args.offered_len == 0 { + return Ok(Vec::new()); + } + let longest = isize::MAX as usize / size_of::(); + if args.offered.is_null() || !args.offered.is_aligned() || args.offered_len > longest { + return Err(RV_ERR_MISUSE); + } + // SAFETY: the pointer is not NULL, is aligned, and the length cannot + // overflow a slice; the caller vouches that the values are readable. + let offered = unsafe { slice::from_raw_parts(args.offered, args.offered_len) }; + // SAFETY: the caller vouches for each value's strings. + offered + .iter() + .map(|info| unsafe { copy_tool(info) }) + .collect() +} + +/// A copy of one offered tool. +/// +/// # Safety +/// Each string in `info` 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 { + 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, + }) +} + /// Answers `RV_PACK_DELETE`: drops the instance `RV_PACK_NEW` set, /// containing a panic in its `Drop`. /// @@ -142,15 +254,22 @@ pub(super) unsafe fn pack_of<'a>(pack_run: *mut std::ffi::c_void) -> Option<&'a #[cfg(test)] mod tests { + use std::ffi::c_void; use std::ptr; use std::sync::atomic::{AtomicIsize, Ordering}; - use runvil_plugin_sys::{RV_ERR_MISUSE, RV_PACK_DELETE, RV_PACK_NEW, RvCall}; + 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, + }; - use crate::entry::{entry, size_field}; + use super::{EMPTY, PackRun}; + use crate::entry::{entry, read_str, rv_str, size_field}; use crate::testing::{self, Failure}; use crate::{ - BoxFuture, Pack, PackInfo, Plugin, Refusal, ToolCall, ToolError, ToolInfo, ToolOutput, + BoxFuture, Pack, PackInfo, Plugin, Refusal, RenderContext, ToolCall, ToolError, ToolInfo, + ToolOutput, }; /// How many `Counted` Pack instances are alive, for the one test that @@ -314,6 +433,333 @@ mod tests { ); } + /// A change to a render's arguments that breaks one rule. + type Edit = fn(&mut RvPackRenderArgs, &mut [RvToolInfo]); + + /// What a render's hand-built Host recorded. + #[derive(Default)] + struct Recorder { + /// Each tool added, as the Host reads it. + added: Vec, + /// The reason of each refusal. + refusals: Vec, + /// The status `add_tool` returns for the tool at this index. + fail_at: Option, + } + + /// `add_tool` of a hand-built Host: records the tool and fails the + /// 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. + 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 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, + }); + RV_OK + } + + /// `refuse` of a hand-built Host: records the reason. + unsafe extern "C" fn record_refusal(ctx: *mut c_void, reason: RvStr) -> RvStatus { + // SAFETY: the test passes a `Recorder` as `ctx`, and the entry point's + // reason is valid for the call. + let (recorder, reason) = + unsafe { (&mut *ctx.cast::(), read_str(reason).unwrap()) }; + recorder.refusals.push(reason.to_owned()); + RV_ERR_REFUSED + } + + /// What a render's Pack does. + #[derive(Clone, Copy)] + enum Renders { + /// Keeps the default. + Default, + /// Hides `second`, shows `first` as `Look`, and adds `lite`. + Reshapes, + /// Refuses. + Refuses, + /// Panics. + Panics, + /// Panics with a payload whose drop panics too. + PanicsWithBomb, + } + + /// A panic payload whose drop panics. + struct Bomb; + + impl Drop for Bomb { + fn drop(&mut self) { + panic!("the payload's drop panics"); + } + } + + impl Pack for Renders { + fn tools(&self) -> Vec { + Vec::new() + } + + fn call<'a>(&'a self, _call: ToolCall<'a>) -> BoxFuture<'a, Result> { + uncalled() + } + + fn render( + &self, + cx: &RenderContext<'_>, + offered: Vec, + ) -> Result, Refusal> { + match self { + Renders::Default => Ok(offered), + Renders::Reshapes => { + let mut shown: Vec = offered + .into_iter() + .filter(|tool| tool.name != "second") + .map(|tool| tool.wire_name("Look")) + .collect(); + shown.push(ToolInfo::new( + "lite", + format!("seen by {} in {}", cx.model, cx.entry), + SCHEMA, + )); + Ok(shown) + } + Renders::Refuses => Err(Refusal::new("no tools for this model")), + Renders::Panics => panic!("boom"), + Renders::PanicsWithBomb => std::panic::panic_any(Bomb), + } + } + } + + const ENTRY: &str = "entry-1"; + const MODEL: &str = r#"{"name":"m"}"#; + + /// 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(), + ] + } + + /// Sends `RV_PACK_RENDER` for an instance of `pack` with `offered`, to + /// a Host that records what the entry point does, and returns the + /// status and the record. `edit` may break the arguments first. + fn render_with( + pack: Renders, + fail_at: Option, + edit: impl FnOnce(&mut RvPackRenderArgs, &mut [RvToolInfo]), + ) -> (RvStatus, Recorder) { + let tools = offered(); + let mut values: Vec = tools + .iter() + .map(|tool| 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), + }) + .collect(); + let mut recorder = Recorder { + fail_at, + ..Recorder::default() + }; + let mut args = RvPackRenderArgs { + size: size_field::(), + reserved: 0, + ctx: (&raw mut recorder).cast(), + entry: rv_str(ENTRY), + model: rv_str(MODEL), + offered: values.as_ptr(), + offered_len: values.len(), + refuse: record_refusal, + add_tool: record_tool, + }; + edit(&mut args, &mut values); + let pack_run = Box::into_raw(Box::new(PackRun { + pack: Box::new(pack), + })); + let mut call = RvCall { + size: size_field::(), + verb: RV_PACK_RENDER, + host: ptr::null(), + plugin: ptr::null_mut(), + pack_run: pack_run.cast(), + args: (&raw const args).cast(), + tool_call: ptr::null_mut(), + }; + // SAFETY: the call, the arguments, the tools, and the recorder + // follow the contract and outlive the call; `Maker` is never read. + let status = unsafe { entry::(&raw mut call) }; + // SAFETY: `pack_run` is the box leaked above, freed once, with no + // call of it still open. + drop(unsafe { Box::from_raw(pack_run) }); + (status, recorder) + } + + #[test] + fn a_render_that_keeps_the_default_lists_the_offered_tools_as_they_came() { + let (status, recorder) = render_with(Renders::Default, None, |_, _| {}); + assert_eq!(status, RV_OK); + assert_eq!(recorder.added, offered()); + assert_eq!(recorder.refusals, Vec::::new()); + } + + #[test] + fn a_render_may_rename_hide_and_add_and_reads_the_entry_and_the_model() { + let (status, recorder) = render_with(Renders::Reshapes, None, |_, _| {}); + assert_eq!(status, RV_OK); + assert_eq!( + recorder.added, + [ + ToolInfo::new("first", "The first tool.", SCHEMA).wire_name("Look"), + ToolInfo::new("lite", format!("seen by {MODEL} in {ENTRY}"), SCHEMA), + ] + ); + } + + #[test] + fn a_render_that_offers_nothing_adds_nothing_even_with_a_null_pointer() { + let (status, recorder) = render_with(Renders::Default, None, |args, _| { + args.offered = ptr::null(); + args.offered_len = 0; + }); + assert_eq!(status, RV_OK); + assert_eq!(recorder.added, Vec::::new()); + } + + #[test] + fn a_refusal_of_a_render_reaches_the_host_with_its_reason() { + let (status, recorder) = render_with(Renders::Refuses, None, |_, _| {}); + assert_eq!(status, RV_ERR_REFUSED); + assert_eq!(recorder.refusals, ["no tools for this model"]); + assert_eq!(recorder.added, Vec::::new()); + } + + #[test] + fn a_panic_in_a_render_becomes_a_refusal() { + let (status, recorder) = render_with(Renders::Panics, None, |_, _| {}); + assert_eq!(status, RV_ERR_REFUSED); + assert_eq!( + recorder.refusals, + ["the Pack panicked while it rendered: boom"] + ); + } + + #[test] + fn a_panic_payload_whose_drop_panics_is_contained_and_the_render_is_refused() { + let (status, recorder) = render_with(Renders::PanicsWithBomb, None, |_, _| {}); + assert_eq!(status, RV_ERR_REFUSED); + assert_eq!( + recorder.refusals, + ["the Pack panicked while it rendered: a panic payload that is not text"] + ); + } + + #[test] + fn a_status_from_add_tool_stops_the_render_and_is_returned() { + let (status, recorder) = render_with(Renders::Default, Some(1), |_, _| {}); + assert_eq!(status, RV_ERR_MISUSE); + assert_eq!(recorder.added, offered()[..1]); + } + + #[test] + fn a_render_the_host_breaks_is_a_misuse_or_unsupported() { + let cases: [(&str, Edit, RvStatus); 7] = [ + ( + "offered tools with a NULL pointer", + |args, _| args.offered = ptr::null(), + RV_ERR_MISUSE, + ), + ( + "a misaligned pointer", + |args, _| args.offered = args.offered.cast::().wrapping_add(1).cast(), + RV_ERR_MISUSE, + ), + ( + "an entry that is not UTF-8", + |args, _| { + args.entry = RvStr { + ptr: [0xff_u8].as_ptr().cast(), + len: 1, + }; + }, + RV_ERR_MISUSE, + ), + ( + "a model with a NULL pointer", + |args, _| { + args.model = RvStr { + ptr: ptr::null(), + len: 2, + }; + }, + RV_ERR_MISUSE, + ), + ( + "a struct shorter than this crate's", + |args, _| args.size = 8, + RV_ERR_UNSUPPORTED, + ), + ( + "an offered tool struct shorter than this crate's", + |_, tools| tools[1].size = 8, + RV_ERR_UNSUPPORTED, + ), + ( + "an offered tool whose name has a NULL pointer", + |_, tools| { + tools[0].name = RvStr { + ptr: ptr::null(), + len: 5, + }; + }, + RV_ERR_MISUSE, + ), + ]; + for (what, edit, expected) in cases { + let (status, recorder) = render_with(Renders::Default, None, edit); + assert_eq!(status, expected, "{what}"); + assert_eq!(recorder.added, Vec::::new(), "{what}"); + } + } + + #[test] + fn a_render_without_its_instance_or_its_arguments_is_a_misuse() { + let mut call = RvCall { + size: size_field::(), + verb: RV_PACK_RENDER, + host: ptr::null(), + plugin: ptr::null_mut(), + pack_run: ptr::null_mut(), + args: ptr::null(), + tool_call: ptr::null_mut(), + }; + // SAFETY: the entry point checks the instance pointer first. + assert_eq!(unsafe { entry::(&raw mut call) }, RV_ERR_MISUSE); + let pack_run = Box::into_raw(Box::new(PackRun { + pack: Box::new(Renders::Default), + })); + call.pack_run = pack_run.cast(); + // SAFETY: the entry point checks `args` before it reads through it. + assert_eq!(unsafe { entry::(&raw mut call) }, RV_ERR_MISUSE); + // SAFETY: `pack_run` is the box leaked above, freed once. + drop(unsafe { Box::from_raw(pack_run) }); + } + #[test] fn a_pack_verb_without_its_instance_is_a_misuse() { for verb in [RV_PACK_NEW, RV_PACK_DELETE] { diff --git a/crates/runvil-plugin-sdk/src/lib.rs b/crates/runvil-plugin-sdk/src/lib.rs index acdbddb..a0c5675 100644 --- a/crates/runvil-plugin-sdk/src/lib.rs +++ b/crates/runvil-plugin-sdk/src/lib.rs @@ -79,6 +79,19 @@ //! [`ToolInfo::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. +//! //! The `test-support` feature adds `testing`, a fake Host for a Plugin //! crate's own tests. //! @@ -104,7 +117,8 @@ //! when the Host refuses a file request, whose failure no answer would //! bring. //! - A panic in [`Plugin::load`] or [`Plugin::new_pack`] becomes a -//! refusal, a panic in a tool call ends that call as a failure, and a +//! refusal, a panic in [`Pack::render`] becomes a refusal of that +//! render, a panic in a tool call ends that call as a failure, and a //! panic while something the Plugin owns drops stays inside the Plugin; //! none unwinds across the C boundary. //! - The Plugin instance is made on the loading thread, may be dropped on @@ -127,7 +141,7 @@ mod tool; pub use entry::entry; pub use file::{DirEntry, FileError, FileErrorKind, FileFuture, FileType, Stat}; -pub use pack::{BoxFuture, Pack, PackInfo}; +pub use pack::{BoxFuture, Pack, PackInfo, RenderContext}; pub use runvil_plugin_sys as sys; pub use tool::{NextStep, ToolCall, ToolError, ToolErrorKind, ToolInfo, ToolOutput, next_step}; diff --git a/crates/runvil-plugin-sdk/src/pack.rs b/crates/runvil-plugin-sdk/src/pack.rs index f6ce39b..5249653 100644 --- a/crates/runvil-plugin-sdk/src/pack.rs +++ b/crates/runvil-plugin-sdk/src/pack.rs @@ -4,6 +4,7 @@ use std::future::Future; use std::pin::Pin; +use crate::Refusal; use crate::tool::{ToolCall, ToolError, ToolInfo, ToolOutput}; /// A boxed future that is `Send`, which [`Pack::call`] returns. An @@ -104,6 +105,83 @@ pub trait Pack: Send + Sync + 'static { /// Returns a [`ToolError`], whose message a model reads, when the call /// rejects its arguments or fails. fn call<'a>(&'a self, call: ToolCall<'a>) -> BoxFuture<'a, Result>; + + /// Lists the tools a model is shown, given the tools a section + /// offered from this Pack. The Host calls it when a section entry's + /// first model round is about to advertise its tools, once for each of + /// the entry's two sets of tools that holds a tool of this Pack, with + /// the same [`RenderContext`] each time. What it lists stays fixed for + /// that section entry. The default lists `offered` as it came. + /// + /// `offered` holds the catalog tools of this Pack the section offered + /// in this set, as [`Pack::tools`] listed them. The answer decides + /// what the model sees: + /// + /// - 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. + /// - 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 + /// model-facing tool that changes files says so with + /// [`ToolInfo::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. + /// + /// It returns promptly: it does not block and does no I/O. It may + /// run on any thread and at the same time as calls of this instance. + /// A panic in it ends the render as a refusal and never unwinds into + /// the Host. + /// + /// # Errors + /// Returns a [`Refusal`], whose reason a model can read, when the Pack + /// cannot render for this model. The round that asked for the render + /// then fails. + fn render( + &self, + cx: &RenderContext<'_>, + offered: Vec, + ) -> Result, Refusal> { + let _ = cx; + Ok(offered) + } +} + +/// What a [`Pack`] learns about the section entry it renders for, in +/// [`Pack::render`]. +/// +/// A section entry is one execution of a section. The entry point builds +/// the context from what the Host lends for the call, and a Pack keeps +/// none of it past the call. A later version adds facts as new fields, so +/// a Pack reads the fields it names and matches no other way. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct RenderContext<'a> { + /// The section entry, the value a prompt's Lua reads as `sys.id`. + pub entry: &'a str, + /// 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. + pub model: &'a str, +} + +impl<'a> RenderContext<'a> { + /// A context for the section entry `entry` and the model `model`, for + /// a Pack author who calls [`Pack::render`] in a test without a Host. + #[must_use] + pub fn new(entry: &'a str, model: &'a str) -> RenderContext<'a> { + RenderContext { entry, model } + } } /// One run's instance of a Pack as `call->pack_run` holds it: a thin diff --git a/crates/runvil-plugin-sdk/src/testing.rs b/crates/runvil-plugin-sdk/src/testing.rs index 7aa18bb..eb5af4e 100644 --- a/crates/runvil-plugin-sdk/src/testing.rs +++ b/crates/runvil-plugin-sdk/src/testing.rs @@ -37,6 +37,16 @@ //! call that nothing wakes fails its test after 60 seconds, with a //! sentence that says so, and does not hang it. //! +//! A Pack that renders is tested with [`PackRun::render`], which sends +//! `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. +//! //! Every call is lent the Host's resources, the JSON text of an object. //! It is `{}` unless [`PackRun::with_resources`] gives the run another: //! @@ -59,6 +69,7 @@ mod fixture; mod json; mod load; mod pack; +mod render; mod session; mod tree; mod wake; @@ -216,8 +227,10 @@ impl Loaded { session.rejection(status)?; Ok(PackRun { loaded: self, + pack_id: pack.split_once('/').map_or(pack, |(_, id)| id).to_owned(), instance: call.pack_run, tools: mem::take(&mut session.tools), + rendered: RefCell::new(Vec::new()), files: Files::new(), resources: Resources::new("{}"), }) @@ -275,9 +288,15 @@ pub struct InsertedPack { #[derive(Debug)] pub struct PackRun<'a> { loaded: &'a Loaded, + /// The Pack's id, the second segment of its name, which the tool ids + /// and the default wire names of its tools start with. + pack_id: String, /// What `RV_PACK_NEW` left in `call->pack_run`. instance: *mut c_void, tools: Vec, + /// The names of the model-facing tools a render of this instance has + /// listed, which a test may call as the model does. + rendered: RefCell>, /// The run's files, which the file requests of each call are /// performed on. files: Files, @@ -330,9 +349,10 @@ impl PackRun<'_> { /// breaks the contract; see [`Call::step`]. /// /// # Panics - /// Panics when the instance added no tool named `tool`, which the - /// Harness never calls, and when a step parks the call and the Plugin - /// does not wake it within 60 seconds; see [`Call::wait`]. + /// Panics when the instance added no tool named `tool` and no render + /// of it has listed one, which the Harness never calls, and when a + /// step parks the call and the Plugin does not wake it within 60 + /// seconds; see [`Call::wait`]. pub fn call(&self, tool: &str, arguments: &str) -> Result { let mut call = self.start(tool, arguments); loop { @@ -348,12 +368,15 @@ impl PackRun<'_> { /// until the first [`Call::step`]. /// /// # Panics - /// Panics when the instance added no tool named `tool`, which the - /// Harness never calls. + /// Panics when the instance added no tool named `tool` and no render + /// of it has listed one, which the Harness never calls. A model-facing + /// tool that [`PackRun::render`] listed is called by the name it was + /// listed under, as a model calls it. #[must_use] pub fn start(&self, tool: &str, arguments: &str) -> Call<'_> { assert!( - self.tools.iter().any(|added| added.name == tool), + self.tools.iter().any(|added| added.name == tool) + || self.rendered.borrow().iter().any(|listed| listed == tool), "the Pack instance has no tool named {tool}" ); Call { @@ -575,6 +598,9 @@ pub enum Failure { Undescribed, /// `RV_TOOL_CALL` returned `RV_OK` without finishing the call. Unfinished, + /// `RV_PACK_RENDER` returned `RV_OK`, and the Harness rejects what the + /// render listed, for the reason given, which names the tool. + Rejected(String), } /// The `RvHost` every call hands the Plugin. diff --git a/crates/runvil-plugin-sdk/src/testing/pack.rs b/crates/runvil-plugin-sdk/src/testing/pack.rs index 5c98aff..1d24df4 100644 --- a/crates/runvil-plugin-sdk/src/testing/pack.rs +++ b/crates/runvil-plugin-sdk/src/testing/pack.rs @@ -1,6 +1,7 @@ //! The functions a fake Host's `RvPackNewArgs` carries: `refuse` and //! `add_tool`, each checking what the Plugin hands it as the Harness -//! does. +//! does. The checks of one tool are shared with `RV_PACK_RENDER`, whose +//! functions sit in the `render` module. use std::ffi::c_void; @@ -9,7 +10,7 @@ use runvil_plugin_sys::{ }; use super::json; -use super::session::{self, Field, PACK_NEW, Shape, answer, field, shape}; +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}; @@ -27,20 +28,44 @@ pub(super) unsafe extern "C" fn refuse(ctx: *mut c_void, reason: RvStr) -> RvSta /// Records one tool the instance adds, validated; returns `RV_OK` or /// `RV_ERR_MISUSE`. pub(super) unsafe extern "C" fn add_tool(ctx: *mut c_void, info: *const RvToolInfo) -> RvStatus { - answer(ctx, &PACK_NEW, |session| { - // SAFETY: the contract makes `info` point at a readable - // `RvToolInfo` during this call. + // SAFETY: the contract makes `info` point at a readable `RvToolInfo` + // with valid strings during this call. + unsafe { + add( + ctx, + &PACK_NEW, + info, + "two tools of one Pack instance share a name", + ) + } +} + +/// Records one tool that the open call of `family` is given, validated: +/// the rules of a tool's fields are the same for `RV_PACK_NEW` and +/// `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. +pub(super) unsafe fn add( + ctx: *mut c_void, + family: &Family, + info: *const RvToolInfo, + twice: &'static str, +) -> RvStatus { + 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"); } - // SAFETY: the contract makes each string valid for its length. + // 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("two tools of one Pack instance share a name"); + return Err(twice); } // SAFETY: as above. let wire_name = unsafe { WIRE_NAME.read(info.wire_name) }?; diff --git a/crates/runvil-plugin-sdk/src/testing/render.rs b/crates/runvil-plugin-sdk/src/testing/render.rs new file mode 100644 index 0000000..ff586b1 --- /dev/null +++ b/crates/runvil-plugin-sdk/src/testing/render.rs @@ -0,0 +1,601 @@ +//! `RV_PACK_RENDER` in the fake Host: [`PackRun::render`] sends the verb +//! with the tools a section offered, the functions an `RvPackRenderArgs` +//! carries check what the Plugin hands them as the Harness does, and the +//! rules the Harness applies to a whole render are checked on the answer. + +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, + RvToolInfo, +}; + +use super::json; +use super::pack::add; +use super::session::{self, PACK_RENDER, Verb}; +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 +/// `ctx` and `reason` come from the `RvPackRenderArgs` of a call, and the +/// reason is valid for its length during this call. +unsafe extern "C" fn refuse(ctx: *mut c_void, reason: RvStr) -> RvStatus { + session::refuse(ctx, &PACK_RENDER, reason) +} + +/// Records one tool the render lists, validated; returns `RV_OK` or +/// `RV_ERR_MISUSE`. +/// +/// # Safety +/// `ctx` and `info` come from the `RvPackRenderArgs` of a call, and `info`, +/// when it is not NULL, is readable with valid strings during this call. +unsafe extern "C" fn add_tool(ctx: *mut c_void, info: *const RvToolInfo) -> RvStatus { + // SAFETY: the contract makes `info` point at a readable `RvToolInfo` + // with valid strings during this call. + unsafe { + add( + ctx, + &PACK_RENDER, + info, + "two tools of one render share a name", + ) + } +} + +impl PackRun<'_> { + /// Sends `RV_PACK_RENDER` for the section entry `entry` and the model + /// `model`, the JSON text of an object, with `offered` as the tools the + /// section offered from this Pack in one set, and returns the tools the + /// model is shown, in order. A Pack that answers `RV_ERR_UNSUPPORTED` + /// shows the offered tools as they are, as the Harness does. + /// + /// Each tool the Plugin lists is checked as one a Pack adds in + /// `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. + /// - 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 + /// call it by that name, as a model does. + /// - No two tools may show one wire name, the default one included. + /// + /// # Errors + /// Returns the [`Failure`] the Harness would report, checked in the + /// Harness's order: a refusal, then a misuse, then a status other than + /// `RV_OK`, and then the first rule above that the answer breaks, as + /// [`Failure::Rejected`], which names the tool. + /// + /// # Panics + /// Panics when `model` is not the JSON text of an object, or `offered` + /// holds a tool this instance did not add, which the Harness never + /// sends. + pub fn render( + &self, + entry: &str, + model: &str, + offered: &[ToolInfo], + ) -> Result, Failure> { + assert!( + json::is_object(model), + "the model must be the JSON text of an object, as the Host lends it" + ); + for tool in offered { + assert!( + self.tools.iter().any(|added| added.name == tool.name), + "the Pack instance has no tool named {}", + tool.name + ); + } + let infos: Vec = offered.iter().map(raw_info).collect(); + let mut call = self.new_call(RV_PACK_RENDER); + let (status, mut session) = session::open(Verb::PackRender, |ctx| { + let args = RvPackRenderArgs { + size: size_field::(), + reserved: 0, + ctx, + entry: rv_str(entry), + model: rv_str(model), + offered: if infos.is_empty() { + ptr::null() + } else { + infos.as_ptr() + }, + offered_len: infos.len(), + refuse, + add_tool, + }; + 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. + unsafe { (self.loaded.entry)(&raw mut call) } + }); + if status == RV_ERR_UNSUPPORTED && session.refusal.is_none() && session.misuse.is_none() { + return Ok(offered.to_vec()); + } + session.rejection(status)?; + let listed = mem::take(&mut session.tools); + self.check_render(offered, &listed)?; + self.rendered + .borrow_mut() + .extend(listed.iter().map(|tool| tool.name.clone())); + Ok(listed) + } + + /// The rules of a whole render, which no single `add_tool` can check. + fn check_render(&self, offered: &[ToolInfo], listed: &[ToolInfo]) -> Result<(), Failure> { + 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 { + 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 \ + parameters as a model-facing tool under a name of its own", + tool.name + ))); + } + } else if self.tools.iter().any(|added| added.name == tool.name) { + return Err(Failure::Rejected(format!( + "the render listed {}, a catalog tool the section did not offer in this \ + set; a render lists a catalog tool only when the section offered it", + tool.name + ))); + } + let wire_name = self.wire_name_of(tool); + if let Some((_, first)) = shown.iter().find(|(held, _)| *held == wire_name) { + return Err(Failure::Rejected(format!( + "the render shows the tools {first} and {} under one wire name, {wire_name}", + tool.name + ))); + } + shown.push((wire_name, &tool.name)); + } + Ok(()) + } + + /// The wire name a model calls `tool` by: its own, or else the id of + /// the tool with each `/` and `.` turned into `_`. + fn wire_name_of(&self, tool: &ToolInfo) -> String { + tool.wire_name + .clone() + .unwrap_or_else(|| format!("{}/{}", self.pack_id, tool.name).replace(['/', '.'], "_")) + } +} + +/// `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 + //! that keeps the default, one that reshapes its tools, one that + //! refuses, and one for each rule a render can break. + + use runvil_plugin_sys::{RV_ERR_UNSUPPORTED, RV_PACK_RENDER, RvCall, RvStatus}; + + use crate::entry::entry; + use crate::testing::{self, Failure}; + use crate::{ + BoxFuture, Pack, PackInfo, Plugin, Refusal, RenderContext, ToolCall, ToolError, ToolInfo, + 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"}"#; + + /// 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(), + ] + } + + /// What a Pack of [`Renderer`] does with a render. + #[derive(Clone, Copy)] + enum Mode { + /// Keeps the default. + Plain, + /// Hides `second`, shows `first` as `Look`, and adds the + /// model-facing `lite`, which changes files. + Reshapes, + /// Refuses. + Refuses, + /// Panics. + Panics, + /// Lists `first` with other parameters. + ChangesParameters, + /// Lists `second` whatever was offered. + ListsUnoffered, + /// Lists `first` twice. + Repeats, + /// Lists two tools under the wire name `Same`. + SharesWireName, + /// Lists the model-facing tool `copy` under the wire name that + /// `other` has by default. + ClashesWithDefault, + /// Lists a tool whose name is not one name segment. + BadName, + /// 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. + Respaced, + } + + /// A Plugin whose Packs differ only in what their render does. + struct Renderer; + + impl Plugin for Renderer { + const NAME: &'static str = "renderer"; + const VERSION: &'static str = "1"; + const PACKS: &'static [PackInfo] = &[ + PackInfo::new("acme/plain"), + PackInfo::new("acme/reshape"), + PackInfo::new("acme/refuses"), + PackInfo::new("acme/panics"), + PackInfo::new("acme/changes"), + PackInfo::new("acme/unoffered"), + PackInfo::new("acme/repeats"), + PackInfo::new("acme/shares"), + PackInfo::new("acme/clashes"), + PackInfo::new("acme/badname"), + PackInfo::new("acme/dots"), + PackInfo::new("acme/spaced"), + PackInfo::new("acme/inherits"), + ]; + + fn load() -> Result { + Ok(Renderer) + } + + fn new_pack(&self, pack: &str) -> Result, Refusal> { + let mode = match pack { + "acme/plain" => Mode::Plain, + "acme/reshape" => Mode::Reshapes, + "acme/refuses" => Mode::Refuses, + "acme/panics" => Mode::Panics, + "acme/changes" => Mode::ChangesParameters, + "acme/unoffered" => Mode::ListsUnoffered, + "acme/repeats" => Mode::Repeats, + "acme/shares" => Mode::SharesWireName, + "acme/clashes" => Mode::ClashesWithDefault, + "acme/dots" => Mode::Dotted, + "acme/spaced" => Mode::Respaced, + "acme/inherits" => return Ok(Box::new(Inherits)), + _ => Mode::BadName, + }; + Ok(Box::new(Shaper(mode))) + } + } + + /// A Pack that does not override `render`. + struct Inherits; + + impl Pack for Inherits { + fn tools(&self) -> Vec { + catalog() + } + + fn call<'a>(&'a self, _call: ToolCall<'a>) -> BoxFuture<'a, Result> { + Box::pin(async { Ok(ToolOutput::trusted("")) }) + } + } + + struct Shaper(Mode); + + impl Pack for Shaper { + fn tools(&self) -> Vec { + catalog() + } + + fn call<'a>(&'a self, call: ToolCall<'a>) -> BoxFuture<'a, Result> { + let text = format!("called {}", call.tool()); + Box::pin(async move { Ok(ToolOutput::trusted(text)) }) + } + + fn render( + &self, + cx: &RenderContext<'_>, + offered: Vec, + ) -> Result, Refusal> { + let first = || offered.iter().find(|tool| tool.name == "first").cloned(); + match self.0 { + Mode::Plain => Ok(offered), + Mode::Reshapes => { + let mut shown: Vec = offered + .into_iter() + .filter(|tool| tool.name != "second") + .map(|tool| tool.wire_name("Look")) + .collect(); + shown.push( + ToolInfo::new( + "lite", + format!("{} saw {}", cx.entry, cx.model), + OTHER_SCHEMA, + ) + .changes_files(), + ); + 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 + }) + .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"), + ]), + Mode::ClashesWithDefault => Ok(vec![ + ToolInfo::new("copy", "A copy.", SCHEMA).wire_name("clashes_other"), + ToolInfo::new("other", "Another.", 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), + ]), + Mode::Respaced => Ok(first() + .map(|mut tool| { + tool.parameters = SCHEMA.replace(':', ": "); + tool + }) + .into_iter() + .collect()), + } + } + } + + /// Sends `RV_PACK_RENDER` for the Pack `pack` of [`Renderer`] with + /// `offered`, and returns the result. + fn render(pack: &str, offered: &[ToolInfo]) -> Result, Failure> { + let loaded = testing::load::().unwrap(); + let run = loaded.new_pack(pack).unwrap(); + run.render(ENTRY, MODEL, offered) + } + + #[test] + fn a_pack_that_keeps_the_default_lists_what_it_was_offered() { + assert_eq!(render("acme/plain", &catalog()), Ok(catalog())); + assert_eq!( + render("acme/plain", &catalog()[..1]), + Ok(catalog()[..1].to_vec()) + ); + assert_eq!(render("acme/plain", &[]), Ok(Vec::new())); + } + + #[test] + fn a_pack_that_inherits_the_default_render_lists_what_it_was_offered_in_order() { + let mut backwards = catalog(); + backwards.reverse(); + assert_eq!( + render("acme/inherits", &backwards), + Ok(backwards), + "the default keeps every tool, its order, and its text" + ); + assert_eq!(render("acme/inherits", &[]), Ok(Vec::new())); + } + + #[test] + fn a_test_calls_a_model_facing_tool_by_the_name_a_render_listed_it_under() { + let loaded = testing::load::().unwrap(); + let run = loaded.new_pack("acme/reshape").unwrap(); + run.render(ENTRY, MODEL, &catalog()).unwrap(); + assert_eq!( + run.call("lite", "{}"), + Ok(Ok(ToolOutput::trusted("called lite"))) + ); + } + + #[test] + #[should_panic(expected = "the Pack instance has no tool named lite")] + fn a_model_facing_tool_is_not_callable_before_a_render_lists_it() { + let loaded = testing::load::().unwrap(); + let run = loaded.new_pack("acme/reshape").unwrap(); + let _call = run.start("lite", "{}"); + } + + #[test] + fn a_render_may_rename_hide_and_add_a_model_facing_tool() { + let shown = render("acme/reshape", &catalog()).unwrap(); + assert_eq!( + shown, + [ + ToolInfo::new("first", "The first tool.", SCHEMA).wire_name("Look"), + ToolInfo::new("lite", format!("{ENTRY} saw {MODEL}"), OTHER_SCHEMA).changes_files(), + ] + ); + } + + #[test] + fn a_render_leaves_the_instance_as_it_was() { + let loaded = testing::load::().unwrap(); + let run = loaded.new_pack("acme/reshape").unwrap(); + let first = run.render(ENTRY, MODEL, &catalog()).unwrap(); + assert_eq!(run.render(ENTRY, MODEL, &catalog()).unwrap(), first); + assert_eq!(run.tools(), catalog()); + assert_eq!( + run.call("second", "{}"), + Ok(Ok(ToolOutput::trusted("called second"))) + ); + } + + #[test] + fn a_refusal_reaches_the_test_with_its_reason() { + assert_eq!( + render("acme/refuses", &catalog()), + Err(Failure::Refused("no tools for this model".to_owned())) + ); + } + + #[test] + fn a_panic_in_a_render_is_a_refusal() { + assert_eq!( + render("acme/panics", &catalog()), + Err(Failure::Refused( + "the Pack panicked while it rendered: boom".to_owned() + )) + ); + } + + #[test] + fn a_catalog_tool_listed_with_other_parameters_fails_and_names_the_tool() { + let Err(Failure::Rejected(reason)) = render("acme/changes", &catalog()) else { + panic!("the render should be rejected"); + }; + assert!( + reason.contains("the catalog tool first with other parameters"), + "{reason}" + ); + assert!( + reason.contains("model-facing tool under a name of its own"), + "{reason}" + ); + } + + #[test] + fn a_catalog_tool_the_section_did_not_offer_fails_and_names_the_tool() { + let Err(Failure::Rejected(reason)) = render("acme/unoffered", &catalog()[..1]) else { + panic!("the render should be rejected"); + }; + assert!( + reason.contains("the render listed second, a catalog tool the section did not offer"), + "{reason}" + ); + // Offered, the same tool is the section's own. + assert_eq!( + render("acme/unoffered", &catalog()), + Ok(vec![catalog().remove(1)]) + ); + } + + #[test] + fn two_tools_under_one_wire_name_fail_the_default_name_included() { + assert_eq!( + render("acme/shares", &[]), + Err(Failure::Rejected( + "the render shows the tools one and two under one wire name, Same".to_owned() + )) + ); + assert_eq!( + render("acme/clashes", &[]), + Err(Failure::Rejected( + "the render shows the tools copy and other under one wire name, clashes_other" + .to_owned() + )) + ); + } + + #[test] + fn default_wire_names_that_differ_only_by_a_dot_clash() { + assert_eq!( + render("acme/dots", &[]), + Err(Failure::Rejected( + "the render shows the tools a.b and a_b under one wire name, dots_a_b".to_owned() + )) + ); + } + + #[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}" + ); + } + + #[test] + fn a_tool_the_host_rejects_is_a_misuse() { + assert_eq!( + render("acme/repeats", &catalog()), + Err(Failure::Misused("two tools of one render share a name")) + ); + assert_eq!( + render("acme/badname", &catalog()), + Err(Failure::Misused( + "the tool's name is not one name segment, such as `fetch`" + )) + ); + } + + /// The entry point of [`Renderer`], behind a Plugin that does not + /// render: it answers verb 7 as a Plugin built for no render does. + /// + /// # Safety + /// `call` is a whole `RvCall` that the fake Host made. + unsafe extern "C" fn no_render(call: *mut RvCall) -> RvStatus { + // SAFETY: the fake Host made `call`, so it is whole. + if unsafe { (*call).verb } == RV_PACK_RENDER { + return RV_ERR_UNSUPPORTED; + } + // SAFETY: any other verb follows the contract, which `entry` needs. + unsafe { entry::(call) } + } + + #[test] + fn a_plugin_that_answers_unsupported_shows_the_offered_tools_as_they_are() { + // SAFETY: `no_render` follows the contract and never unwinds. + let loaded = unsafe { testing::load_entry(no_render) }.unwrap(); + let run = loaded.new_pack("acme/plain").unwrap(); + assert_eq!( + run.render(ENTRY, MODEL, &catalog()[1..]), + Ok(catalog()[1..].to_vec()) + ); + } + + #[test] + #[should_panic(expected = "the Pack instance has no tool named ghost")] + 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)]); + } + + #[test] + #[should_panic(expected = "the model must be the JSON text of an object")] + fn a_model_that_is_not_an_object_is_the_tests_own_fault() { + let loaded = testing::load::().unwrap(); + let run = loaded.new_pack("acme/plain").unwrap(); + let _shown = run.render(ENTRY, "not json", &catalog()); + } +} diff --git a/crates/runvil-plugin-sdk/src/testing/session.rs b/crates/runvil-plugin-sdk/src/testing/session.rs index 80760ec..adb4087 100644 --- a/crates/runvil-plugin-sdk/src/testing/session.rs +++ b/crates/runvil-plugin-sdk/src/testing/session.rs @@ -28,6 +28,8 @@ pub(super) enum Verb { Load, /// `RV_PACK_NEW`. PackNew, + /// `RV_PACK_RENDER`. + PackRender, /// `RV_TOOL_CALL`. ToolCall, } @@ -46,7 +48,7 @@ pub(super) struct Session { pub(super) described: Option, /// The Packs a load inserted, in order. pub(super) packs: Vec, - /// The tools an `RV_PACK_NEW` added, in order. + /// The tools an `RV_PACK_NEW` or an `RV_PACK_RENDER` added, in order. pub(super) tools: Vec, /// The result a step finished its call with. pub(super) result: Option>, @@ -142,6 +144,13 @@ pub(super) const PACK_NEW: Family = Family { wrong_call: "a Pack function was called outside RV_PACK_NEW", }; +/// The functions in an `RvPackRenderArgs`. +pub(super) const PACK_RENDER: Family = Family { + verb: Verb::PackRender, + wrong_ctx: "a render function was handed a ctx other than the open RV_PACK_RENDER call's", + wrong_call: "a render function was called outside RV_PACK_RENDER", +}; + /// The functions in an `RvToolCallArgs`. pub(super) const TOOL_CALL: Family = Family { verb: Verb::ToolCall, diff --git a/crates/runvil-plugin-sys/Cargo.toml b/crates/runvil-plugin-sys/Cargo.toml index bb2de3f..6c0c54f 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.6.0" +version = "0.7.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 60beda2..3de4671 100644 --- a/crates/runvil-plugin-sys/include/runvil_plugin.h +++ b/crates/runvil-plugin-sys/include/runvil_plugin.h @@ -54,6 +54,10 @@ * tool call on `call->pack_run`. * - `RV_TOOL_CANCEL` (6), with no arguments: frees `call->tool_call`, * the state of a tool call the Host has abandoned. + * - `RV_PACK_RENDER` (7), with an `RvPackRenderArgs`: lends one run's + * instance of a Pack the tools a section offered from it and the model + * that will read them, and lists the tools the model is shown, with + * `add_tool`. * * A Plugin answers a verb it does not know with `RV_ERR_UNSUPPORTED`. * `RV_PLUGIN_UNLOAD`, `RV_PACK_DELETE`, and `RV_TOOL_CANCEL` return @@ -65,14 +69,71 @@ * makes one instance of a Pack for each run that holds the Pack, with * `RV_PACK_NEW`, and frees the instance with `RV_PACK_DELETE` when * the run ends. - * - An instance's tools are the ones it adds during `RV_PACK_NEW`, and - * they stay fixed for the run. The Host forms each tool's id from the - * Pack's id, which is the second segment of the Pack's name, and the - * tool's name: the tool `fetch` of the Pack `acme/url` is `url/fetch`. + * - An instance's catalog tools are the ones it adds during + * `RV_PACK_NEW`, and they stay fixed for the run. A render may list + * other tools for a model, as the section on renders says. The Host + * forms each tool's id from the Pack's id, which is the second segment + * of the Pack's name, and the tool's name: the tool `fetch` of the Pack + * `acme/url` is `url/fetch`. * - `RV_PACK_NEW` runs while the Host prepares a run, so it returns * promptly: it does not block and does no I/O. What is costly to make * belongs in the Plugin instance, which every run shares. * + * # Renders + * + * - 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 + * 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 + * tools, the Host sends `RV_PACK_RENDER` to the instance of each Pack + * the section offered tools from, so that the Pack can shape what the + * model sees for that model. The Host sends it once for each of the + * section's two sets of tools that holds a tool of the Pack, so up to + * twice for one section entry, with the same `entry` and `model`. What + * the Pack lists stays fixed for that section entry. + * - `entry` is the section entry, the value a prompt's Lua reads as + * `sys.id`. `model` is the JSON text of an object that describes the + * model of the entry's first round, with the keys `server`, `name`, + * `description`, `context` (the window in tokens), and `thinking` + * (`"never"`, `"always"`, or `"switchable"`), and `provider` when the + * Host's catalog names one. A model the Host's catalog does not hold + * reports `"never"`. A later version adds a fact as a new key, so a + * 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. + * - 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. + * - 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 + * `RV_ERR_REFUSED`, at most once, with a UTF-8 reason of at most + * `RV_MAX_LINE` bytes. A refusal, a misuse, and any other status + * fail the render, and the round that asked for it fails with it. + * - `RV_PACK_RENDER` returns promptly: it does not block and does no + * I/O. It keeps nothing: `entry`, `model`, and `offered` are valid for + * the call only, every tool it lists is copied by the Host as it is + * added, and there is nothing for the Plugin to free. + * * # Tool calls * * - A tool call is a series of steps. The Host starts the call by sending @@ -181,8 +242,10 @@ * - Calls may run at the same time on different threads, with three * exceptions. No two steps of one tool call run at the same time, and * `RV_TOOL_CANCEL` runs beside no step of its call. - * `RV_PACK_DELETE` comes after every tool call of its - * `pack_run` has ended, and runs beside no call that names it. + * `RV_PACK_DELETE` comes after every tool call and every render of + * its `pack_run` has ended, and runs beside no call that names it. So + * `RV_PACK_RENDER` may run beside tool calls of its `pack_run` and + * beside another render of it. * `RV_PLUGIN_UNLOAD` comes after every Pack instance of the Plugin is * deleted, and runs beside no other call. * - The functions in a verb's arguments struct answer only while that @@ -225,6 +288,9 @@ * refusal, a misuse, or a status other than `RV_OK`. The Plugin frees * whatever it made before it returns on every such path. One that * succeeds gets exactly one `RV_PACK_DELETE`. + * - An `RV_PACK_RENDER` leaves the instance as it was, whether it + * succeeds, is refused, or is rejected, so it gets no later verb. The + * Plugin frees whatever it made during the call before it returns. * - The step that ends a tool call frees the call's state before it * returns. A call that is abandoned gets `RV_TOOL_CANCEL` instead, * which frees the state; its `call->tool_call` is NULL when no step set @@ -234,20 +300,21 @@ * * # Reserved numbers * - * Verbs 7 and 8 and status codes 1 to 3 are reserved for later versions, - * so those numbers never get another meaning. This version declares no - * constant for them, sends neither verb, and returns none of those codes. + * Verb 8 and status codes 1 to 3 are reserved for later versions, so + * those numbers never get another meaning. This version declares no + * constant for them, sends no such verb, and returns none of those codes. * * # Status codes * * - `RV_OK` (0) is success. * - Codes 1 to 3 are reserved. * - `RV_ERR_MISUSE` (4) means the caller broke the contract. - * - `RV_ERR_REFUSED` (5) means the Plugin declined: to load, or to make - * a Pack instance. + * - `RV_ERR_REFUSED` (5) means the Plugin declined: to load, to make a + * Pack instance, or to render a Pack's tools. * - `RV_ERR_UNSUPPORTED` (6) means the Plugin cannot answer the call: it - * does not know the verb, the Host reports a version the Plugin was not - * built for, or a struct's `size` is smaller than the Plugin expects. + * does not know the verb, does not render for `RV_PACK_RENDER`, the + * Host reports a version the Plugin was not built for, or a struct's + * `size` is smaller than the Plugin expects. * - `RV_PENDING` (7) means a tool call is parked: the Host sends its * next step after the Plugin wakes the call, or when the answer to the * step's file request is ready. Only `RV_TOOL_CALL` returns it. @@ -294,6 +361,7 @@ typedef struct RvToolResult RvToolResult; typedef struct RvHost RvHost; typedef struct RvLoadArgs RvLoadArgs; typedef struct RvPackNewArgs RvPackNewArgs; +typedef struct RvPackRenderArgs RvPackRenderArgs; typedef struct RvWaker RvWaker; typedef struct RvToolCallArgs RvToolCallArgs; typedef struct RvCall RvCall; @@ -306,7 +374,7 @@ typedef struct RvCall RvCall; /** * The contract's minor version, which `RvHost` reports. */ -#define RV_API_MINOR 6 +#define RV_API_MINOR 7 /** * The most bytes in a name segment, a version, or a wire name. @@ -703,6 +771,58 @@ struct RvPackNewArgs { RvStatus (*add_tool)(void *ctx, const struct RvToolInfo *info); }; +/** + * The arguments of `RV_PACK_RENDER`: the section entry, the model, the + * tools the section offered from the Pack, and the functions the Plugin + * may call while it renders, each taking `ctx` first. + */ +struct RvPackRenderArgs { + /** + * The size of this struct in bytes: `sizeof(RvPackRenderArgs)`. + */ + uint32_t size; + /** + * Zero. + */ + uint32_t reserved; + /** + * The Host's context for this call, passed back as the first argument + * of each function below. The Plugin never reads through it. + */ + void *ctx; + /** + * The section entry, the value a prompt's Lua reads as `sys.id`. + */ + struct RvStr entry; + /** + * The JSON text of an object that describes the model of the entry's + * first round: `server`, `name`, `description`, `context`, `thinking`, + * and `provider` when the Host's catalog names one. + */ + struct RvStr model; + /** + * The first of `offered_len` tools the section offered from this Pack + * in this set, in the order they were offered. It may be NULL when + * `offered_len` is zero. + */ + const struct RvToolInfo *offered; + /** + * How many tools `offered` points at. + */ + size_t offered_len; + /** + * Declines to render, at most once, with a UTF-8 reason of at most + * `RV_MAX_LINE` bytes that a model can read; returns + * `RV_ERR_REFUSED`. The round that asked for the render fails. + */ + RvStatus (*refuse)(void *ctx, struct RvStr reason); + /** + * Adds one tool the model is shown, once for each, in the order the + * model sees them. No two tools of one render share a name. + */ + RvStatus (*add_tool)(void *ctx, const struct RvToolInfo *info); +}; + /** * Wakes one tool call. The Plugin may call `wake` from any thread, any * number of times, from the call's first step until @@ -859,13 +979,15 @@ struct RvCall { /** * One run's instance of a Pack: NULL going into `RV_PACK_NEW`, * which sets it, that pointer on `RV_PACK_DELETE`, - * `RV_TOOL_CALL`, and `RV_TOOL_CANCEL`, and NULL otherwise. + * `RV_PACK_RENDER`, `RV_TOOL_CALL`, and `RV_TOOL_CANCEL`, and + * NULL otherwise. */ void *pack_run; /** * The verb's own arguments: an `RvLoadArgs` for `RV_PLUGIN_LOAD`, - * an `RvPackNewArgs` for `RV_PACK_NEW`, an `RvToolCallArgs` for - * `RV_TOOL_CALL`, and NULL for every other verb. + * an `RvPackNewArgs` for `RV_PACK_NEW`, an `RvPackRenderArgs` + * for `RV_PACK_RENDER`, an `RvToolCallArgs` for `RV_TOOL_CALL`, + * and NULL for every other verb. */ const void *args; /** @@ -887,8 +1009,8 @@ struct RvCall { #define RV_ERR_MISUSE 4 /** - * The Plugin declined to load or to make a Pack instance; `refuse` - * returns it. + * The Plugin declined to load, to make a Pack instance, or to render a + * Pack's tools; `refuse` returns it. */ #define RV_ERR_REFUSED 5 @@ -945,6 +1067,12 @@ struct RvCall { */ #define RV_TOOL_CANCEL 6 +/** + * Lend a Pack instance the tools a section offered from it and the model + * that will read them, and list the tools the model is shown. + */ +#define RV_PACK_RENDER 7 + /** * The call succeeded, and its text may hold data an attacker can * influence, such as the contents of a file or a web page. The Host marks diff --git a/crates/runvil-plugin-sys/src/lib.rs b/crates/runvil-plugin-sys/src/lib.rs index fd7a9ad..9301fb5 100644 --- a/crates/runvil-plugin-sys/src/lib.rs +++ b/crates/runvil-plugin-sys/src/lib.rs @@ -49,6 +49,10 @@ //! tool call on `call->pack_run`. //! - [`RV_TOOL_CANCEL`] (6), with no arguments: frees `call->tool_call`, //! the state of a tool call the Host has abandoned. +//! - [`RV_PACK_RENDER`] (7), with an [`RvPackRenderArgs`]: lends one run's +//! instance of a Pack the tools a section offered from it and the model +//! that will read them, and lists the tools the model is shown, with +//! `add_tool`. //! //! A Plugin answers a verb it does not know with [`RV_ERR_UNSUPPORTED`]. //! [`RV_PLUGIN_UNLOAD`], [`RV_PACK_DELETE`], and [`RV_TOOL_CANCEL`] return @@ -60,14 +64,71 @@ //! makes one instance of a Pack for each run that holds the Pack, with //! [`RV_PACK_NEW`], and frees the instance with [`RV_PACK_DELETE`] when //! the run ends. -//! - An instance's tools are the ones it adds during [`RV_PACK_NEW`], and -//! they stay fixed for the run. The Host forms each tool's id from the -//! Pack's id, which is the second segment of the Pack's name, and the -//! tool's name: the tool `fetch` of the Pack `acme/url` is `url/fetch`. +//! - An instance's catalog tools are the ones it adds during +//! [`RV_PACK_NEW`], and they stay fixed for the run. A render may list +//! other tools for a model, as the section on renders says. The Host +//! forms each tool's id from the Pack's id, which is the second segment +//! of the Pack's name, and the tool's name: the tool `fetch` of the Pack +//! `acme/url` is `url/fetch`. //! - [`RV_PACK_NEW`] runs while the Host prepares a run, so it returns //! promptly: it does not block and does no I/O. What is costly to make //! belongs in the Plugin instance, which every run shares. //! +//! # Renders +//! +//! - 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 +//! 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 +//! tools, the Host sends [`RV_PACK_RENDER`] to the instance of each Pack +//! the section offered tools from, so that the Pack can shape what the +//! model sees for that model. The Host sends it once for each of the +//! section's two sets of tools that holds a tool of the Pack, so up to +//! twice for one section entry, with the same `entry` and `model`. What +//! the Pack lists stays fixed for that section entry. +//! - `entry` is the section entry, the value a prompt's Lua reads as +//! `sys.id`. `model` is the JSON text of an object that describes the +//! model of the entry's first round, with the keys `server`, `name`, +//! `description`, `context` (the window in tokens), and `thinking` +//! (`"never"`, `"always"`, or `"switchable"`), and `provider` when the +//! Host's catalog names one. A model the Host's catalog does not hold +//! reports `"never"`. A later version adds a fact as a new key, so a +//! 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. +//! - 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. +//! - 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 +//! [`RV_ERR_REFUSED`], at most once, with a UTF-8 reason of at most +//! [`RV_MAX_LINE`] bytes. A refusal, a misuse, and any other status +//! fail the render, and the round that asked for it fails with it. +//! - [`RV_PACK_RENDER`] returns promptly: it does not block and does no +//! I/O. It keeps nothing: `entry`, `model`, and `offered` are valid for +//! the call only, every tool it lists is copied by the Host as it is +//! added, and there is nothing for the Plugin to free. +//! //! # Tool calls //! //! - A tool call is a series of steps. The Host starts the call by sending @@ -176,8 +237,10 @@ //! - Calls may run at the same time on different threads, with three //! exceptions. No two steps of one tool call run at the same time, and //! [`RV_TOOL_CANCEL`] runs beside no step of its call. -//! [`RV_PACK_DELETE`] comes after every tool call of its -//! `pack_run` has ended, and runs beside no call that names it. +//! [`RV_PACK_DELETE`] comes after every tool call and every render of +//! its `pack_run` has ended, and runs beside no call that names it. So +//! [`RV_PACK_RENDER`] may run beside tool calls of its `pack_run` and +//! beside another render of it. //! [`RV_PLUGIN_UNLOAD`] comes after every Pack instance of the Plugin is //! deleted, and runs beside no other call. //! - The functions in a verb's arguments struct answer only while that @@ -220,6 +283,9 @@ //! refusal, a misuse, or a status other than [`RV_OK`]. The Plugin frees //! whatever it made before it returns on every such path. One that //! succeeds gets exactly one [`RV_PACK_DELETE`]. +//! - An [`RV_PACK_RENDER`] leaves the instance as it was, whether it +//! succeeds, is refused, or is rejected, so it gets no later verb. The +//! Plugin frees whatever it made during the call before it returns. //! - The step that ends a tool call frees the call's state before it //! returns. A call that is abandoned gets [`RV_TOOL_CANCEL`] instead, //! which frees the state; its `call->tool_call` is NULL when no step set @@ -229,20 +295,21 @@ //! //! # Reserved numbers //! -//! Verbs 7 and 8 and status codes 1 to 3 are reserved for later versions, -//! so those numbers never get another meaning. This version declares no -//! constant for them, sends neither verb, and returns none of those codes. +//! Verb 8 and status codes 1 to 3 are reserved for later versions, so +//! those numbers never get another meaning. This version declares no +//! constant for them, sends no such verb, and returns none of those codes. //! //! # Status codes //! //! - [`RV_OK`] (0) is success. //! - Codes 1 to 3 are reserved. //! - [`RV_ERR_MISUSE`] (4) means the caller broke the contract. -//! - [`RV_ERR_REFUSED`] (5) means the Plugin declined: to load, or to make -//! a Pack instance. +//! - [`RV_ERR_REFUSED`] (5) means the Plugin declined: to load, to make a +//! Pack instance, or to render a Pack's tools. //! - [`RV_ERR_UNSUPPORTED`] (6) means the Plugin cannot answer the call: it -//! does not know the verb, the Host reports a version the Plugin was not -//! built for, or a struct's `size` is smaller than the Plugin expects. +//! does not know the verb, does not render for [`RV_PACK_RENDER`], the +//! Host reports a version the Plugin was not built for, or a struct's +//! `size` is smaller than the Plugin expects. //! - [`RV_PENDING`] (7) means a tool call is parked: the Host sends its //! next step after the Plugin wakes the call, or when the answer to the //! step's file request is ready. Only [`RV_TOOL_CALL`] returns it. @@ -295,8 +362,8 @@ pub type RvStatus = u32; pub const RV_OK: RvStatus = 0; /// The caller broke the contract. pub const RV_ERR_MISUSE: RvStatus = 4; -/// The Plugin declined to load or to make a Pack instance; `refuse` -/// returns it. +/// The Plugin declined to load, to make a Pack instance, or to render a +/// Pack's tools; `refuse` returns it. pub const RV_ERR_REFUSED: RvStatus = 5; /// The Plugin cannot answer the call: it does not know the verb, it was /// not built for the Host's version, or a struct is shorter than it @@ -328,6 +395,9 @@ pub const RV_PACK_DELETE: RvVerb = 4; pub const RV_TOOL_CALL: RvVerb = 5; /// Free the state of a tool call the Host has abandoned. pub const RV_TOOL_CANCEL: RvVerb = 6; +/// Lend a Pack instance the tools a section offered from it and the model +/// that will read them, and list the tools the model is shown. +pub const RV_PACK_RENDER: RvVerb = 7; /// How a tool call ended, in an [`RvToolResult`]. A fixed-width integer, /// as [`RvVerb`] is. @@ -398,7 +468,7 @@ pub const RV_TOOL_CHANGES_FILES: RvToolFlags = 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 = 6; +pub const RV_API_MINOR: u32 = 7; /// The most bytes in a name segment, a version, or a wire name. pub const RV_MAX_NAME: usize = 64; @@ -635,6 +705,40 @@ pub struct RvPackNewArgs { pub add_tool: unsafe extern "C" fn(ctx: *mut c_void, info: *const RvToolInfo) -> RvStatus, } +/// The arguments of [`RV_PACK_RENDER`]: the section entry, the model, the +/// tools the section offered from the Pack, and the functions the Plugin +/// may call while it renders, each taking `ctx` first. +#[repr(C)] +#[derive(Debug)] +pub struct RvPackRenderArgs { + /// The size of this struct in bytes: `sizeof(RvPackRenderArgs)`. + pub size: u32, + /// Zero. + pub reserved: u32, + /// The Host's context for this call, passed back as the first argument + /// of each function below. The Plugin never reads through it. + pub ctx: *mut c_void, + /// The section entry, the value a prompt's Lua reads as `sys.id`. + pub entry: RvStr, + /// The JSON text of an object that describes the model of the entry's + /// first round: `server`, `name`, `description`, `context`, `thinking`, + /// and `provider` when the Host's catalog names one. + pub model: RvStr, + /// The first of `offered_len` tools the section offered from this Pack + /// in this set, in the order they were offered. It may be NULL when + /// `offered_len` is zero. + pub offered: *const RvToolInfo, + /// How many tools `offered` points at. + pub offered_len: usize, + /// Declines to render, at most once, with a UTF-8 reason of at most + /// [`RV_MAX_LINE`] bytes that a model can read; returns + /// [`RV_ERR_REFUSED`]. The round that asked for the render fails. + pub refuse: unsafe extern "C" fn(ctx: *mut c_void, reason: RvStr) -> RvStatus, + /// Adds one tool the model is shown, once for each, in the order the + /// model sees them. No two tools of one render share a name. + pub add_tool: unsafe extern "C" fn(ctx: *mut c_void, info: *const RvToolInfo) -> RvStatus, +} + /// Wakes one tool call. The Plugin may call `wake` from any thread, any /// number of times, from the call's first step until /// [`RV_PLUGIN_UNLOAD`] returns. The Host keeps what `ctx` points at @@ -745,11 +849,13 @@ pub struct RvCall { pub plugin: *mut c_void, /// One run's instance of a Pack: NULL going into [`RV_PACK_NEW`], /// which sets it, that pointer on [`RV_PACK_DELETE`], - /// [`RV_TOOL_CALL`], and [`RV_TOOL_CANCEL`], and NULL otherwise. + /// [`RV_PACK_RENDER`], [`RV_TOOL_CALL`], and [`RV_TOOL_CANCEL`], and + /// NULL otherwise. pub pack_run: *mut c_void, /// The verb's own arguments: an [`RvLoadArgs`] for [`RV_PLUGIN_LOAD`], - /// an [`RvPackNewArgs`] for [`RV_PACK_NEW`], an [`RvToolCallArgs`] for - /// [`RV_TOOL_CALL`], and NULL for every other verb. + /// an [`RvPackNewArgs`] for [`RV_PACK_NEW`], an [`RvPackRenderArgs`] + /// for [`RV_PACK_RENDER`], an [`RvToolCallArgs`] for [`RV_TOOL_CALL`], + /// and NULL for every other verb. pub args: *const c_void, /// The state of one tool call: NULL going into the call's first /// [`RV_TOOL_CALL`], what the last step left on each later step and on @@ -779,16 +885,16 @@ mod tests { 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_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_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, }; #[cfg(target_pointer_width = "64")] use super::{ RvBytes, RvCall, RvDirEntries, RvDirEntry, RvFileAnswer, RvFileError, RvHost, RvLoadArgs, - RvPackInfo, RvPackNewArgs, RvPluginInfo, RvStat, RvStr, RvToolCallArgs, RvToolInfo, - RvToolResult, RvWaker, + RvPackInfo, RvPackNewArgs, RvPackRenderArgs, RvPluginInfo, RvStat, RvStr, RvToolCallArgs, + RvToolInfo, RvToolResult, RvWaker, }; #[test] @@ -912,6 +1018,21 @@ mod tests { assert_eq!(offset_of!(RvPackNewArgs, add_tool), 40); } + #[test] + #[cfg(target_pointer_width = "64")] + fn the_pack_render_arguments_keep_their_layout() { + assert_eq!(size_of::(), 80); + assert_eq!(offset_of!(RvPackRenderArgs, size), 0); + assert_eq!(offset_of!(RvPackRenderArgs, reserved), 4); + assert_eq!(offset_of!(RvPackRenderArgs, ctx), 8); + assert_eq!(offset_of!(RvPackRenderArgs, entry), 16); + assert_eq!(offset_of!(RvPackRenderArgs, model), 32); + assert_eq!(offset_of!(RvPackRenderArgs, offered), 48); + assert_eq!(offset_of!(RvPackRenderArgs, offered_len), 56); + assert_eq!(offset_of!(RvPackRenderArgs, refuse), 64); + assert_eq!(offset_of!(RvPackRenderArgs, add_tool), 72); + } + #[test] #[cfg(target_pointer_width = "64")] fn the_waker_keeps_its_layout() { @@ -1007,6 +1128,7 @@ mod tests { assert_eq!(RV_PACK_DELETE, 4); assert_eq!(RV_TOOL_CALL, 5); assert_eq!(RV_TOOL_CANCEL, 6); + assert_eq!(RV_PACK_RENDER, 7); } #[test] diff --git a/tests/c-layout/layout.c b/tests/c-layout/layout.c index 28403ba..1874d5f 100644 --- a/tests/c-layout/layout.c +++ b/tests/c-layout/layout.c @@ -89,6 +89,16 @@ static const RvLayoutEntry ENTRIES[] = { OFFSET(RvPackNewArgs, pack), OFFSET(RvPackNewArgs, refuse), OFFSET(RvPackNewArgs, add_tool), + SIZE(RvPackRenderArgs), + OFFSET(RvPackRenderArgs, size), + OFFSET(RvPackRenderArgs, reserved), + OFFSET(RvPackRenderArgs, ctx), + OFFSET(RvPackRenderArgs, entry), + OFFSET(RvPackRenderArgs, model), + OFFSET(RvPackRenderArgs, offered), + OFFSET(RvPackRenderArgs, offered_len), + OFFSET(RvPackRenderArgs, refuse), + OFFSET(RvPackRenderArgs, add_tool), SIZE(RvWaker), OFFSET(RvWaker, ctx), OFFSET(RvWaker, wake), @@ -131,6 +141,7 @@ static const RvLayoutEntry ENTRIES[] = { VALUE(RV_PACK_DELETE), VALUE(RV_TOOL_CALL), VALUE(RV_TOOL_CANCEL), + VALUE(RV_PACK_RENDER), VALUE(RV_RESULT_UNTRUSTED), VALUE(RV_RESULT_TRUSTED), VALUE(RV_RESULT_INVALID_ARGUMENTS), diff --git a/tests/c-layout/layout.cpp b/tests/c-layout/layout.cpp index 26452ef..4538f35 100644 --- a/tests/c-layout/layout.cpp +++ b/tests/c-layout/layout.cpp @@ -13,6 +13,14 @@ extern "C" std::size_t rv_cpp_size_of_call(void) { return sizeof(RvCall); } +extern "C" std::size_t rv_cpp_size_of_pack_render_args(void) { + return sizeof(RvPackRenderArgs); +} + +extern "C" std::size_t rv_cpp_offset_of_pack_render_add_tool(void) { + return offsetof(RvPackRenderArgs, add_tool); +} + extern "C" RvEntry rv_cpp_entry(void) { return &runvil_plugin; } diff --git a/tests/c-layout/src/lib.rs b/tests/c-layout/src/lib.rs index c6f474e..5f99e99 100644 --- a/tests/c-layout/src/lib.rs +++ b/tests/c-layout/src/lib.rs @@ -27,13 +27,13 @@ mod tests { 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_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_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, RvDirEntries, RvDirEntry, RvFileAnswer, RvFileError, RvFileErrorKind, RvFileType, RvHost, RvLoadArgs, RvPackInfo, RvPackNewArgs, - RvPluginInfo, RvResultKind, RvStat, RvStatus, RvStr, RvToolCallArgs, RvToolFlags, - RvToolInfo, RvToolResult, RvVerb, RvWaker, + RvPackRenderArgs, RvPluginInfo, RvResultKind, RvStat, RvStatus, RvStr, RvToolCallArgs, + RvToolFlags, RvToolInfo, RvToolResult, RvVerb, RvWaker, }; /// One entry of the table in `layout.c`. @@ -50,6 +50,10 @@ mod tests { fn runvil_plugin(call: *mut RvCall) -> RvStatus; /// `sizeof(RvCall)` as C++ sees it. safe fn rv_cpp_size_of_call() -> usize; + /// sizeof(RvPackRenderArgs) as C++ sees it. + safe fn rv_cpp_size_of_pack_render_args() -> usize; + /// offsetof(RvPackRenderArgs, add_tool) as C++ sees it. + safe fn rv_cpp_offset_of_pack_render_add_tool() -> usize; /// `runvil_plugin` as C++ names it. safe fn rv_cpp_entry() -> unsafe extern "C" fn(*mut RvCall) -> RvStatus; } @@ -196,6 +200,16 @@ mod tests { offset!(RvPackNewArgs, pack), offset!(RvPackNewArgs, refuse), offset!(RvPackNewArgs, add_tool), + size!(RvPackRenderArgs), + offset!(RvPackRenderArgs, size), + offset!(RvPackRenderArgs, reserved), + offset!(RvPackRenderArgs, ctx), + offset!(RvPackRenderArgs, entry), + offset!(RvPackRenderArgs, model), + offset!(RvPackRenderArgs, offered), + offset!(RvPackRenderArgs, offered_len), + offset!(RvPackRenderArgs, refuse), + offset!(RvPackRenderArgs, add_tool), size!(RvWaker), offset!(RvWaker, ctx), offset!(RvWaker, wake), @@ -244,6 +258,7 @@ mod tests { value!(RV_PACK_DELETE), value!(RV_TOOL_CALL), value!(RV_TOOL_CANCEL), + value!(RV_PACK_RENDER), value!(RV_RESULT_UNTRUSTED), value!(RV_RESULT_TRUSTED), value!(RV_RESULT_INVALID_ARGUMENTS), @@ -287,6 +302,18 @@ mod tests { assert_eq!(status, RV_ERR_UNSUPPORTED); } + #[test] + fn cpp_sees_the_same_render_arguments_as_rust() { + assert_eq!( + rv_cpp_size_of_pack_render_args(), + size_of::() + ); + assert_eq!( + rv_cpp_offset_of_pack_render_add_tool(), + offset_of!(RvPackRenderArgs, add_tool) + ); + } + #[test] fn cpp_sees_the_same_call_and_reaches_the_c_entry_point() { assert_eq!(rv_cpp_size_of_call(), size_of::());