From 54c209a1292c7a7e5a151ff4ff84bb4eea477c87 Mon Sep 17 00:00:00 2001 From: Vinnie Falco Date: Wed, 2 Dec 2026 08:03:45 -0800 Subject: [PATCH 1/4] Add call origin and model to RV_TOOL_CALL in contract 0.8 A library Plugin could not learn whether a script or a model called a tool, which section or entry made the call, or which model requested it. `RvToolCallArgs` now carries `caller` (`RvCaller`: `RV_CALLER_MODEL` or `RV_CALLER_SCRIPT`) in place of its `reserved` field and appends `section`, `entry`, and `model` after `waker`. `RV_API_MINOR` becomes 8, both crates move to `0.8.0`, and `runvil_plugin.h` is regenerated. - `caller` sits in the 4-byte slot after `size`, and `section`, `entry`, and `model` sit at the end of `RvToolCallArgs`, bringing its size on 64-bit targets to 216 bytes. - `model` holds the same JSON object shape as `model` in `RvPackRenderArgs` when `caller` is `RV_CALLER_MODEL`, and is empty when `caller` is `RV_CALLER_SCRIPT`. - `tests/c-layout` checks `RvCaller`, `RV_CALLER_MODEL`, `RV_CALLER_SCRIPT`, and the size and field offsets of `RvToolCallArgs` across C and C++. - `testing.rs` and `entry/file.rs` fill the new fields with default values; the SDK does not read them yet. --- Cargo.lock | 4 +- crates/runvil-plugin-sdk/Cargo.toml | 2 +- crates/runvil-plugin-sdk/src/entry/file.rs | 11 ++- crates/runvil-plugin-sdk/src/testing.rs | 11 ++- crates/runvil-plugin-sys/Cargo.toml | 2 +- .../runvil-plugin-sys/include/runvil_plugin.h | 67 ++++++++++++--- crates/runvil-plugin-sys/src/lib.rs | 86 ++++++++++++++----- tests/c-layout/layout.c | 8 +- tests/c-layout/layout.cpp | 8 ++ tests/c-layout/src/lib.rs | 48 ++++++++--- 10 files changed, 188 insertions(+), 59 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ee6d3cf..33024e8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -187,14 +187,14 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "runvil-plugin-sdk" -version = "0.7.0" +version = "0.8.0" dependencies = [ "runvil-plugin-sys", ] [[package]] name = "runvil-plugin-sys" -version = "0.7.0" +version = "0.8.0" [[package]] name = "rustix" diff --git a/crates/runvil-plugin-sdk/Cargo.toml b/crates/runvil-plugin-sdk/Cargo.toml index a12afb2..f277e12 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.7.0" +version = "0.8.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/file.rs b/crates/runvil-plugin-sdk/src/entry/file.rs index 5f90616..ccbccf8 100644 --- a/crates/runvil-plugin-sdk/src/entry/file.rs +++ b/crates/runvil-plugin-sdk/src/entry/file.rs @@ -201,9 +201,9 @@ mod tests { use std::task::{Context, Poll, Waker}; use runvil_plugin_sys::{ - RV_ERR_FILE, RV_ERR_MISUSE, RV_FILE_ERROR_DENIED, RV_FILE_TYPE_FILE, RV_OK, RV_PENDING, - RV_TOOL_CALL, RvBytes, RvCall, RvDirEntries, RvFileAnswer, RvFileError, RvStat, RvStatus, - RvStr, RvToolCallArgs, RvToolResult, RvWaker, + RV_CALLER_MODEL, RV_ERR_FILE, RV_ERR_MISUSE, RV_FILE_ERROR_DENIED, RV_FILE_TYPE_FILE, + RV_OK, RV_PENDING, RV_TOOL_CALL, RvBytes, RvCall, RvDirEntries, RvFileAnswer, RvFileError, + RvStat, RvStatus, RvStr, RvToolCallArgs, RvToolResult, RvWaker, }; use super::{receive, send, text}; @@ -722,7 +722,7 @@ mod tests { ) -> RvToolCallArgs { RvToolCallArgs { size: size_field::(), - reserved: 0, + caller: RV_CALLER_MODEL, ctx: ptr::null_mut(), tool: rv_str("tool"), arguments: rv_str("{}"), @@ -742,6 +742,9 @@ mod tests { ctx: ptr::null_mut(), wake: unused_wake, }, + section: rv_str("Test"), + entry: rv_str("0.0"), + model: rv_str(""), } } diff --git a/crates/runvil-plugin-sdk/src/testing.rs b/crates/runvil-plugin-sdk/src/testing.rs index eb5af4e..7de69cf 100644 --- a/crates/runvil-plugin-sdk/src/testing.rs +++ b/crates/runvil-plugin-sdk/src/testing.rs @@ -81,9 +81,9 @@ use std::time::Duration; use std::{mem, ptr}; use runvil_plugin_sys::{ - PluginEntry, RV_API_MAJOR, RV_API_MINOR, RV_OK, RV_PACK_DELETE, RV_PACK_NEW, RV_PENDING, - RV_PLUGIN_LOAD, RV_PLUGIN_UNLOAD, RV_TOOL_CALL, RV_TOOL_CANCEL, RvCall, RvHost, RvLoadArgs, - RvPackNewArgs, RvStatus, RvToolCallArgs, + PluginEntry, RV_API_MAJOR, RV_API_MINOR, RV_CALLER_MODEL, RV_OK, RV_PACK_DELETE, RV_PACK_NEW, + RV_PENDING, RV_PLUGIN_LOAD, RV_PLUGIN_UNLOAD, RV_TOOL_CALL, RV_TOOL_CANCEL, RvCall, RvHost, + RvLoadArgs, RvPackNewArgs, RvStatus, RvToolCallArgs, }; use self::session::{Described, Session, Verb}; @@ -476,7 +476,7 @@ impl Call<'_> { let (status, mut session) = session::open(Verb::ToolCall, |ctx| { let args = RvToolCallArgs { size: size_field::(), - reserved: 0, + caller: RV_CALLER_MODEL, ctx, tool: rv_str(&self.tool), arguments: rv_str(&self.arguments), @@ -493,6 +493,9 @@ impl Call<'_> { file_copy: file::file_copy, resources: rv_str(self.pack.resources.text()), waker: WakerCell::waker(&self.waker), + section: rv_str("Test"), + entry: rv_str("0.0"), + model: rv_str(""), }; call.args = (&raw const args).cast(); // SAFETY: `load_entry`'s caller guaranteed `entry` follows the diff --git a/crates/runvil-plugin-sys/Cargo.toml b/crates/runvil-plugin-sys/Cargo.toml index 6c0c54f..e7e3602 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.7.0" +version = "0.8.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 6c6c5e1..b8ad1ec 100644 --- a/crates/runvil-plugin-sys/include/runvil_plugin.h +++ b/crates/runvil-plugin-sys/include/runvil_plugin.h @@ -139,8 +139,19 @@ * - A tool call is a series of steps. The Host starts the call by sending * `RV_TOOL_CALL` with `call->tool_call` NULL, and that step may set * `call->tool_call` to state of its own. Each later step is an - * `RV_TOOL_CALL` with the same `tool`, `arguments`, `resources`, and - * `waker`, and with the `call->tool_call` the last step left. + * `RV_TOOL_CALL` with the same `caller`, `tool`, `arguments`, + * `resources`, `waker`, `section`, `entry`, and `model`, and with the + * `call->tool_call` the last step left. + * - Every step is told who asked for the call and where, in its + * `RvToolCallArgs`: `caller` is `RV_CALLER_MODEL` when a model + * round asked for the call and `RV_CALLER_SCRIPT` when a section's + * Lua script called the tool; `section` is the name of that section; + * `entry` is the section entry, the value its Lua reads as `sys.id`, or + * empty when none is named; and `model` is the JSON text of an object + * that describes the model of the round that asked for the call, with + * the keys that `model` in `RvPackRenderArgs` holds, or empty when + * `caller` is `RV_CALLER_SCRIPT`. Like `tool` and `arguments`, each + * string is valid for the step. * - A step ends the call by calling `finish` once and returning * `RV_OK`. Any return other than `RV_PENDING` ends the call, and a * call that ends without a result fails. @@ -374,7 +385,7 @@ typedef struct RvCall RvCall; /** * The contract's minor version, which `RvHost` reports. */ -#define RV_API_MINOR 7 +#define RV_API_MINOR 8 /** * The most bytes in a name segment, a version, or a wire name. @@ -444,6 +455,12 @@ typedef uint32_t RvFileErrorKind; */ typedef uint32_t RvToolFlags; +/** + * Who asked for a tool call, in an `RvToolCallArgs`. A fixed-width + * integer, as `RvVerb` is. + */ +typedef uint32_t RvCaller; + /** * A UTF-8 string that is not NUL-terminated. */ @@ -846,11 +863,13 @@ struct RvWaker { }; /** - * The arguments of `RV_TOOL_CALL`: the tool, its arguments, the - * function that ends the call, the file functions, the answer to the - * file request of the call's last step, the Host's resources, and the - * call's waker. Every step of one call gets the same `tool`, - * `arguments`, `resources`, and `waker`. + * The arguments of `RV_TOOL_CALL`: who asked for the call and where, + * the tool, its arguments, the function that ends the call, the file + * functions, the answer to the file request of the call's last step, the + * Host's resources, the call's waker, and the model of the round that + * asked for the call. Every step of one call gets the same `caller`, + * `tool`, `arguments`, `resources`, `waker`, `section`, `entry`, and + * `model`. */ struct RvToolCallArgs { /** @@ -858,9 +877,10 @@ struct RvToolCallArgs { */ uint32_t size; /** - * Zero. + * Who asked for the call: `RV_CALLER_MODEL` or + * `RV_CALLER_SCRIPT`. */ - uint32_t reserved; + RvCaller caller; /** * The Host's context for this step, passed back as the first argument * of each function below. The Plugin never reads through it. @@ -954,6 +974,23 @@ struct RvToolCallArgs { * Its `wake` takes the waker's own `ctx`, not the `ctx` of the step. */ struct RvWaker waker; + /** + * The name of the section whose Lua was running when the call was + * made. Like `tool` and `arguments`, it is valid for the step. + */ + struct RvStr section; + /** + * The section entry that made the call, the value a prompt's Lua + * reads as `sys.id`, or empty when none is named. Valid for the step. + */ + struct RvStr entry; + /** + * The JSON text of an object that describes the model of the round + * that asked for the call, with the keys that `model` in + * `RvPackRenderArgs` holds, or empty when `caller` is + * `RV_CALLER_SCRIPT`. Valid for the step. + */ + struct RvStr model; }; /** @@ -1183,6 +1220,16 @@ struct RvCall { */ #define RV_TOOL_CHANGES_FILES 1 +/** + * A model round asked for the call. + */ +#define RV_CALLER_MODEL 0 + +/** + * A section's Lua script called the tool, with `tools.call`. + */ +#define RV_CALLER_SCRIPT 1 + #ifdef __cplusplus extern "C" { #endif diff --git a/crates/runvil-plugin-sys/src/lib.rs b/crates/runvil-plugin-sys/src/lib.rs index 7966b25..4852550 100644 --- a/crates/runvil-plugin-sys/src/lib.rs +++ b/crates/runvil-plugin-sys/src/lib.rs @@ -134,8 +134,19 @@ //! - A tool call is a series of steps. The Host starts the call by sending //! [`RV_TOOL_CALL`] with `call->tool_call` NULL, and that step may set //! `call->tool_call` to state of its own. Each later step is an -//! [`RV_TOOL_CALL`] with the same `tool`, `arguments`, `resources`, and -//! `waker`, and with the `call->tool_call` the last step left. +//! [`RV_TOOL_CALL`] with the same `caller`, `tool`, `arguments`, +//! `resources`, `waker`, `section`, `entry`, and `model`, and with the +//! `call->tool_call` the last step left. +//! - Every step is told who asked for the call and where, in its +//! [`RvToolCallArgs`]: `caller` is [`RV_CALLER_MODEL`] when a model +//! round asked for the call and [`RV_CALLER_SCRIPT`] when a section's +//! Lua script called the tool; `section` is the name of that section; +//! `entry` is the section entry, the value its Lua reads as `sys.id`, or +//! empty when none is named; and `model` is the JSON text of an object +//! that describes the model of the round that asked for the call, with +//! the keys that `model` in [`RvPackRenderArgs`] holds, or empty when +//! `caller` is [`RV_CALLER_SCRIPT`]. Like `tool` and `arguments`, each +//! string is valid for the step. //! - A step ends the call by calling `finish` once and returning //! [`RV_OK`]. Any return other than [`RV_PENDING`] ends the call, and a //! call that ends without a result fails. @@ -465,10 +476,18 @@ pub type RvToolFlags = u32; /// A call of the tool changes files of its run. Bit 0. pub const RV_TOOL_CHANGES_FILES: RvToolFlags = 1; +/// Who asked for a tool call, in an [`RvToolCallArgs`]. A fixed-width +/// integer, as [`RvVerb`] is. +pub type RvCaller = u32; +/// A model round asked for the call. +pub const RV_CALLER_MODEL: RvCaller = 0; +/// A section's Lua script called the tool, with `tools.call`. +pub const RV_CALLER_SCRIPT: RvCaller = 1; + /// The contract's major version, which [`RvHost`] reports. pub const RV_API_MAJOR: u32 = 0; /// The contract's minor version, which [`RvHost`] reports. -pub const RV_API_MINOR: u32 = 7; +pub const RV_API_MINOR: u32 = 8; /// The most bytes in a name segment, a version, or a wire name. pub const RV_MAX_NAME: usize = 64; @@ -757,18 +776,21 @@ pub struct RvWaker { pub wake: unsafe extern "C" fn(ctx: *mut c_void), } -/// The arguments of [`RV_TOOL_CALL`]: the tool, its arguments, the -/// function that ends the call, the file functions, the answer to the -/// file request of the call's last step, the Host's resources, and the -/// call's waker. Every step of one call gets the same `tool`, -/// `arguments`, `resources`, and `waker`. +/// The arguments of [`RV_TOOL_CALL`]: who asked for the call and where, +/// the tool, its arguments, the function that ends the call, the file +/// functions, the answer to the file request of the call's last step, the +/// Host's resources, the call's waker, and the model of the round that +/// asked for the call. Every step of one call gets the same `caller`, +/// `tool`, `arguments`, `resources`, `waker`, `section`, `entry`, and +/// `model`. #[repr(C)] #[derive(Debug)] pub struct RvToolCallArgs { /// The size of this struct in bytes: `sizeof(RvToolCallArgs)`. pub size: u32, - /// Zero. - pub reserved: u32, + /// Who asked for the call: [`RV_CALLER_MODEL`] or + /// [`RV_CALLER_SCRIPT`]. + pub caller: RvCaller, /// The Host's context for this step, passed back as the first argument /// of each function below. The Plugin never reads through it. pub ctx: *mut c_void, @@ -833,6 +855,17 @@ pub struct RvToolCallArgs { /// The waker of this call. Every step of one call gets the same one. /// Its `wake` takes the waker's own `ctx`, not the `ctx` of the step. pub waker: RvWaker, + /// The name of the section whose Lua was running when the call was + /// made. Like `tool` and `arguments`, it is valid for the step. + pub section: RvStr, + /// The section entry that made the call, the value a prompt's Lua + /// reads as `sys.id`, or empty when none is named. Valid for the step. + pub entry: RvStr, + /// The JSON text of an object that describes the model of the round + /// that asked for the call, with the keys that `model` in + /// [`RvPackRenderArgs`] holds, or empty when `caller` is + /// [`RV_CALLER_SCRIPT`]. Valid for the step. + pub model: RvStr, } /// One call into a Plugin's entry point. @@ -880,16 +913,16 @@ mod tests { use core::mem::{offset_of, size_of}; use super::{ - RV_API_MAJOR, RV_API_MINOR, RV_ERR_FILE, RV_ERR_MISUSE, RV_ERR_REFUSED, RV_ERR_UNSUPPORTED, - RV_FILE_ERROR_ALREADY_EXISTS, RV_FILE_ERROR_CONFLICT, RV_FILE_ERROR_DENIED, - RV_FILE_ERROR_IO, RV_FILE_ERROR_IS_A_DIRECTORY, RV_FILE_ERROR_NOT_A_DIRECTORY, - RV_FILE_ERROR_NOT_EMPTY, RV_FILE_ERROR_NOT_FOUND, RV_FILE_ERROR_OTHER, - RV_FILE_TYPE_DIRECTORY, RV_FILE_TYPE_FILE, RV_FILE_TYPE_OTHER, RV_FILE_TYPE_SYMLINK, - RV_MAX_LINE, RV_MAX_NAME, RV_MAX_PATH, RV_MAX_RESULT, RV_MAX_TOOL_TEXT, RV_MAX_WRITE, - RV_OK, RV_PACK_DELETE, RV_PACK_NEW, RV_PACK_RENDER, RV_PENDING, RV_PLUGIN_LOAD, - RV_PLUGIN_UNLOAD, RV_RESULT_BACKEND, RV_RESULT_INVALID_ARGUMENTS, RV_RESULT_OTHER, - RV_RESULT_TRANSPORT, RV_RESULT_TRUSTED, RV_RESULT_UNTRUSTED, RV_TOOL_CALL, RV_TOOL_CANCEL, - RV_TOOL_CHANGES_FILES, + RV_API_MAJOR, RV_API_MINOR, RV_CALLER_MODEL, RV_CALLER_SCRIPT, RV_ERR_FILE, RV_ERR_MISUSE, + RV_ERR_REFUSED, RV_ERR_UNSUPPORTED, RV_FILE_ERROR_ALREADY_EXISTS, RV_FILE_ERROR_CONFLICT, + RV_FILE_ERROR_DENIED, RV_FILE_ERROR_IO, RV_FILE_ERROR_IS_A_DIRECTORY, + RV_FILE_ERROR_NOT_A_DIRECTORY, RV_FILE_ERROR_NOT_EMPTY, RV_FILE_ERROR_NOT_FOUND, + RV_FILE_ERROR_OTHER, RV_FILE_TYPE_DIRECTORY, RV_FILE_TYPE_FILE, RV_FILE_TYPE_OTHER, + RV_FILE_TYPE_SYMLINK, RV_MAX_LINE, RV_MAX_NAME, RV_MAX_PATH, RV_MAX_RESULT, + RV_MAX_TOOL_TEXT, RV_MAX_WRITE, RV_OK, RV_PACK_DELETE, RV_PACK_NEW, RV_PACK_RENDER, + RV_PENDING, RV_PLUGIN_LOAD, RV_PLUGIN_UNLOAD, RV_RESULT_BACKEND, + RV_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::{ @@ -1045,9 +1078,9 @@ mod tests { #[test] #[cfg(target_pointer_width = "64")] fn the_tool_call_arguments_keep_their_layout() { - assert_eq!(size_of::(), 168); + assert_eq!(size_of::(), 216); assert_eq!(offset_of!(RvToolCallArgs, size), 0); - assert_eq!(offset_of!(RvToolCallArgs, reserved), 4); + assert_eq!(offset_of!(RvToolCallArgs, caller), 4); assert_eq!(offset_of!(RvToolCallArgs, ctx), 8); assert_eq!(offset_of!(RvToolCallArgs, tool), 16); assert_eq!(offset_of!(RvToolCallArgs, arguments), 32); @@ -1064,6 +1097,9 @@ mod tests { assert_eq!(offset_of!(RvToolCallArgs, file_copy), 128); assert_eq!(offset_of!(RvToolCallArgs, resources), 136); assert_eq!(offset_of!(RvToolCallArgs, waker), 152); + assert_eq!(offset_of!(RvToolCallArgs, section), 168); + assert_eq!(offset_of!(RvToolCallArgs, entry), 184); + assert_eq!(offset_of!(RvToolCallArgs, model), 200); } #[test] @@ -1104,6 +1140,12 @@ mod tests { assert_eq!(RV_TOOL_CHANGES_FILES, 1); } + #[test] + fn the_callers_keep_their_numbers() { + assert_eq!(RV_CALLER_MODEL, 0); + assert_eq!(RV_CALLER_SCRIPT, 1); + } + #[test] fn the_file_types_and_the_file_error_kinds_keep_their_numbers() { assert_eq!(RV_FILE_TYPE_OTHER, 0); diff --git a/tests/c-layout/layout.c b/tests/c-layout/layout.c index 1874d5f..33deafc 100644 --- a/tests/c-layout/layout.c +++ b/tests/c-layout/layout.c @@ -102,9 +102,10 @@ static const RvLayoutEntry ENTRIES[] = { SIZE(RvWaker), OFFSET(RvWaker, ctx), OFFSET(RvWaker, wake), + SIZE(RvCaller), SIZE(RvToolCallArgs), OFFSET(RvToolCallArgs, size), - OFFSET(RvToolCallArgs, reserved), + OFFSET(RvToolCallArgs, caller), OFFSET(RvToolCallArgs, ctx), OFFSET(RvToolCallArgs, tool), OFFSET(RvToolCallArgs, arguments), @@ -121,6 +122,9 @@ static const RvLayoutEntry ENTRIES[] = { OFFSET(RvToolCallArgs, file_copy), OFFSET(RvToolCallArgs, resources), OFFSET(RvToolCallArgs, waker), + OFFSET(RvToolCallArgs, section), + OFFSET(RvToolCallArgs, entry), + OFFSET(RvToolCallArgs, model), SIZE(RvCall), OFFSET(RvCall, size), OFFSET(RvCall, verb), @@ -162,6 +166,8 @@ static const RvLayoutEntry ENTRIES[] = { VALUE(RV_FILE_ERROR_ALREADY_EXISTS), VALUE(RV_FILE_ERROR_NOT_EMPTY), VALUE(RV_TOOL_CHANGES_FILES), + VALUE(RV_CALLER_MODEL), + VALUE(RV_CALLER_SCRIPT), VALUE(RV_API_MAJOR), VALUE(RV_API_MINOR), VALUE(RV_MAX_NAME), diff --git a/tests/c-layout/layout.cpp b/tests/c-layout/layout.cpp index 4538f35..ca00458 100644 --- a/tests/c-layout/layout.cpp +++ b/tests/c-layout/layout.cpp @@ -21,6 +21,14 @@ extern "C" std::size_t rv_cpp_offset_of_pack_render_add_tool(void) { return offsetof(RvPackRenderArgs, add_tool); } +extern "C" std::size_t rv_cpp_size_of_tool_call_args(void) { + return sizeof(RvToolCallArgs); +} + +extern "C" std::size_t rv_cpp_offset_of_tool_call_model(void) { + return offsetof(RvToolCallArgs, model); +} + 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 5f99e99..50b7d3a 100644 --- a/tests/c-layout/src/lib.rs +++ b/tests/c-layout/src/lib.rs @@ -21,19 +21,20 @@ mod tests { use std::{ptr, slice}; use runvil_plugin_sys::{ - RV_API_MAJOR, RV_API_MINOR, RV_ERR_FILE, RV_ERR_MISUSE, RV_ERR_REFUSED, RV_ERR_UNSUPPORTED, - RV_FILE_ERROR_ALREADY_EXISTS, RV_FILE_ERROR_CONFLICT, RV_FILE_ERROR_DENIED, - RV_FILE_ERROR_IO, RV_FILE_ERROR_IS_A_DIRECTORY, RV_FILE_ERROR_NOT_A_DIRECTORY, - RV_FILE_ERROR_NOT_EMPTY, RV_FILE_ERROR_NOT_FOUND, RV_FILE_ERROR_OTHER, - RV_FILE_TYPE_DIRECTORY, RV_FILE_TYPE_FILE, RV_FILE_TYPE_OTHER, RV_FILE_TYPE_SYMLINK, - RV_MAX_LINE, RV_MAX_NAME, RV_MAX_PATH, RV_MAX_RESULT, RV_MAX_TOOL_TEXT, RV_MAX_WRITE, - RV_OK, RV_PACK_DELETE, RV_PACK_NEW, RV_PACK_RENDER, RV_PENDING, RV_PLUGIN_LOAD, - RV_PLUGIN_UNLOAD, RV_RESULT_BACKEND, RV_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, - RvPackRenderArgs, RvPluginInfo, RvResultKind, RvStat, RvStatus, RvStr, RvToolCallArgs, - RvToolFlags, RvToolInfo, RvToolResult, RvVerb, RvWaker, + RV_API_MAJOR, RV_API_MINOR, RV_CALLER_MODEL, RV_CALLER_SCRIPT, RV_ERR_FILE, RV_ERR_MISUSE, + RV_ERR_REFUSED, RV_ERR_UNSUPPORTED, RV_FILE_ERROR_ALREADY_EXISTS, RV_FILE_ERROR_CONFLICT, + RV_FILE_ERROR_DENIED, RV_FILE_ERROR_IO, RV_FILE_ERROR_IS_A_DIRECTORY, + RV_FILE_ERROR_NOT_A_DIRECTORY, RV_FILE_ERROR_NOT_EMPTY, RV_FILE_ERROR_NOT_FOUND, + RV_FILE_ERROR_OTHER, RV_FILE_TYPE_DIRECTORY, RV_FILE_TYPE_FILE, RV_FILE_TYPE_OTHER, + RV_FILE_TYPE_SYMLINK, RV_MAX_LINE, RV_MAX_NAME, RV_MAX_PATH, RV_MAX_RESULT, + RV_MAX_TOOL_TEXT, RV_MAX_WRITE, RV_OK, RV_PACK_DELETE, RV_PACK_NEW, RV_PACK_RENDER, + RV_PENDING, RV_PLUGIN_LOAD, RV_PLUGIN_UNLOAD, RV_RESULT_BACKEND, + RV_RESULT_INVALID_ARGUMENTS, RV_RESULT_OTHER, RV_RESULT_TRANSPORT, RV_RESULT_TRUSTED, + RV_RESULT_UNTRUSTED, RV_TOOL_CALL, RV_TOOL_CANCEL, RV_TOOL_CHANGES_FILES, RvBytes, RvCall, + RvCaller, RvDirEntries, RvDirEntry, RvFileAnswer, RvFileError, RvFileErrorKind, RvFileType, + RvHost, RvLoadArgs, RvPackInfo, RvPackNewArgs, RvPackRenderArgs, RvPluginInfo, + RvResultKind, RvStat, RvStatus, RvStr, RvToolCallArgs, RvToolFlags, RvToolInfo, + RvToolResult, RvVerb, RvWaker, }; /// One entry of the table in `layout.c`. @@ -54,6 +55,10 @@ mod tests { 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; + /// sizeof(RvToolCallArgs) as C++ sees it. + safe fn rv_cpp_size_of_tool_call_args() -> usize; + /// offsetof(RvToolCallArgs, model) as C++ sees it. + safe fn rv_cpp_offset_of_tool_call_model() -> usize; /// `runvil_plugin` as C++ names it. safe fn rv_cpp_entry() -> unsafe extern "C" fn(*mut RvCall) -> RvStatus; } @@ -213,9 +218,10 @@ mod tests { size!(RvWaker), offset!(RvWaker, ctx), offset!(RvWaker, wake), + size!(RvCaller), size!(RvToolCallArgs), offset!(RvToolCallArgs, size), - offset!(RvToolCallArgs, reserved), + offset!(RvToolCallArgs, caller), offset!(RvToolCallArgs, ctx), offset!(RvToolCallArgs, tool), offset!(RvToolCallArgs, arguments), @@ -232,6 +238,9 @@ mod tests { offset!(RvToolCallArgs, file_copy), offset!(RvToolCallArgs, resources), offset!(RvToolCallArgs, waker), + offset!(RvToolCallArgs, section), + offset!(RvToolCallArgs, entry), + offset!(RvToolCallArgs, model), size!(RvCall), offset!(RvCall, size), offset!(RvCall, verb), @@ -279,6 +288,8 @@ mod tests { value!(RV_FILE_ERROR_ALREADY_EXISTS), value!(RV_FILE_ERROR_NOT_EMPTY), value!(RV_TOOL_CHANGES_FILES), + value!(RV_CALLER_MODEL), + value!(RV_CALLER_SCRIPT), value!(RV_API_MAJOR), value!(RV_API_MINOR), value!(RV_MAX_NAME), @@ -314,6 +325,15 @@ mod tests { ); } + #[test] + fn cpp_sees_the_same_tool_call_arguments_as_rust() { + assert_eq!(rv_cpp_size_of_tool_call_args(), size_of::()); + assert_eq!( + rv_cpp_offset_of_tool_call_model(), + offset_of!(RvToolCallArgs, model) + ); + } + #[test] fn cpp_sees_the_same_call_and_reaches_the_c_entry_point() { assert_eq!(rv_cpp_size_of_call(), size_of::()); From 338a225a1377cd0e2172f447a381b4794c01fbc5 Mon Sep 17 00:00:00 2001 From: Vinnie Falco Date: Wed, 2 Dec 2026 08:03:45 -0800 Subject: [PATCH 2/4] Lend caller, section, entry, and model on ToolCall in SDK A tool written against `runvil-plugin-sdk` could not read the origin or the model that `RvToolCallArgs` carries in contract 0.8. `ToolCall` now exposes `caller`, `section`, `entry`, and `model`, backed by copies in `CallState` taken in `start` on the call's first step. - `Caller` (`Model` and `Script`) is `#[non_exhaustive]` and re-exported at the crate root. - `start` in `entry/tool.rs` maps `RV_CALLER_MODEL` and `RV_CALLER_SCRIPT` to `Caller`, rejects any other number or non-UTF-8 string with `RV_ERR_MISUSE`, and stores the strings through `with_origin` on `CallState`, turning empty `entry` and `model` strings into `None`. - Unit tests in `tool.rs` and `entry/tool.rs` verify that the values survive across steps, that empty `entry` and `model` strings read as `None`, and that an invalid `caller` or non-UTF-8 `section`, `entry`, or `model` fails the step with `RV_ERR_MISUSE`. --- crates/runvil-plugin-sdk/src/entry/tool.rs | 198 +++++++++++++++++++-- crates/runvil-plugin-sdk/src/lib.rs | 18 +- crates/runvil-plugin-sdk/src/tool.rs | 113 ++++++++++-- 3 files changed, 292 insertions(+), 37 deletions(-) diff --git a/crates/runvil-plugin-sdk/src/entry/tool.rs b/crates/runvil-plugin-sdk/src/entry/tool.rs index 1eddcee..baafcc5 100644 --- a/crates/runvil-plugin-sdk/src/entry/tool.rs +++ b/crates/runvil-plugin-sdk/src/entry/tool.rs @@ -10,9 +10,10 @@ use std::sync::Arc; use std::task::{Context, Poll, Wake, Waker}; use runvil_plugin_sys::{ - RV_ERR_MISUSE, RV_MAX_RESULT, RV_OK, RV_PENDING, RV_RESULT_BACKEND, - RV_RESULT_INVALID_ARGUMENTS, RV_RESULT_OTHER, RV_RESULT_TRANSPORT, RV_RESULT_TRUSTED, - RV_RESULT_UNTRUSTED, RvCall, RvResultKind, RvStatus, RvToolCallArgs, RvToolResult, RvWaker, + RV_CALLER_MODEL, RV_CALLER_SCRIPT, RV_ERR_MISUSE, RV_MAX_RESULT, RV_OK, RV_PENDING, + RV_RESULT_BACKEND, RV_RESULT_INVALID_ARGUMENTS, RV_RESULT_OTHER, RV_RESULT_TRANSPORT, + RV_RESULT_TRUSTED, RV_RESULT_UNTRUSTED, RvCall, RvResultKind, RvStatus, RvToolCallArgs, + RvToolResult, RvWaker, }; use super::pack::pack_of; @@ -20,7 +21,7 @@ use super::{args, contain, file, panic_message, read_str, rv_str, size_field}; use crate::file::Requests; use crate::names::cut; use crate::tool::CallState; -use crate::{BoxFuture, Pack, ToolCall, ToolError, ToolErrorKind, ToolOutput}; +use crate::{BoxFuture, Caller, Pack, ToolCall, ToolError, ToolErrorKind, ToolOutput}; /// One tool call between its steps, behind `call->tool_call`. struct Call { @@ -214,12 +215,13 @@ pub(super) unsafe fn step(call: *mut RvCall) -> RvStatus { } /// Starts the call `args` describes on the instance `call` names, with -/// copies of the tool name, the arguments, and the Host's resources, -/// which the Host lends for this step only, and with the waker every -/// step of the call is handed. When the call cannot start, returns the -/// status that ends it: `RV_ERR_MISUSE` for a call with no instance or -/// with text that is not UTF-8, and what the Host's `finish` answers for -/// a `Pack::call` that panicked. +/// copies of the caller, the tool name, the arguments, the Host's +/// resources, the section, the entry, and the model, which the Host lends +/// for this step only, and with the waker every step of the call is +/// handed. When the call cannot start, returns the status that ends it: +/// `RV_ERR_MISUSE` for a call with no instance, an unknown `caller`, or +/// text that is not UTF-8, and what the Host's `finish` answers for a +/// `Pack::call` that panicked. /// /// # Safety /// `call` points to a whole `RvCall` whose `pack_run` is NULL or a live @@ -229,18 +231,29 @@ unsafe fn start(call: *mut RvCall, args: &RvToolCallArgs) -> Result, R // Host deletes the instance only after every tool call of it has // ended, so the Pack outlives this call's future. let pack: &'static dyn Pack = unsafe { pack_of((*call).pack_run) }.ok_or(RV_ERR_MISUSE)?; - // SAFETY: the Host keeps the three strings valid for the step. + let caller = match args.caller { + RV_CALLER_MODEL => Caller::Model, + RV_CALLER_SCRIPT => Caller::Script, + _ => return Err(RV_ERR_MISUSE), + }; + // SAFETY: the Host keeps the six strings valid for the step. let texts = unsafe { ( read_str(args.tool), read_str(args.arguments), read_str(args.resources), + read_str(args.section), + read_str(args.entry), + read_str(args.model), ) }; - let (Some(tool), Some(arguments), Some(resources)) = texts else { + let (Some(tool), Some(arguments), Some(resources), Some(section), Some(entry), Some(model)) = + texts + else { return Err(RV_ERR_MISUSE); }; - let state = CallState::new(tool, arguments, resources); + let state = + CallState::new(tool, arguments, resources).with_origin(caller, section, entry, model); // SAFETY: `args` belongs to the open step. Call::start(pack, state, args.waker).map_err(|error| unsafe { finish(args, &Err(error)) }) } @@ -317,15 +330,15 @@ mod tests { use std::time::Duration; use runvil_plugin_sys::{ - RV_ERR_MISUSE, RV_MAX_RESULT, RV_OK, RV_TOOL_CALL, RV_TOOL_CANCEL, RvCall, RvStatus, RvStr, - RvToolCallArgs, + RV_CALLER_SCRIPT, RV_ERR_MISUSE, RV_MAX_RESULT, RV_OK, RV_TOOL_CALL, RV_TOOL_CANCEL, + RvCall, RvStatus, RvStr, RvToolCallArgs, }; - use crate::entry::{entry, size_field}; + use crate::entry::{entry, rv_str, size_field}; use crate::testing::{self, Failure}; use crate::{ - BoxFuture, Pack, PackInfo, Plugin, Refusal, ToolCall, ToolError, ToolErrorKind, ToolInfo, - ToolOutput, next_step, + BoxFuture, Caller, Pack, PackInfo, Plugin, Refusal, ToolCall, ToolError, ToolErrorKind, + ToolInfo, ToolOutput, next_step, }; /// How many `Guard` values are alive: one sits in each `slow` call's @@ -451,6 +464,7 @@ mod tests { "panics-early", "huge", "resources", + "origin", "debug", "paced", "handoff", @@ -507,6 +521,21 @@ mod tests { next_step().await; call.resources().to_owned() } + "origin" => { + // The origin and the model are read in a later step than + // the one the Host lent them for. + next_step().await; + let caller = match call.caller() { + Caller::Model => "model", + Caller::Script => "script", + }; + format!( + "{caller}|{}|{}|{}", + call.section(), + call.entry().unwrap_or("-"), + call.model().unwrap_or("-"), + ) + } "debug" => format!("{call:?}"), "paced" => { for _ in 0..3 { @@ -790,6 +819,139 @@ mod tests { assert_eq!(pack.call("echo", "{}"), Err(Failure::Status(RV_ERR_MISUSE))); } + #[test] + fn a_call_copies_the_caller_section_entry_and_model_on_its_first_step() { + unsafe extern "C" fn with_script_origin(call: *mut RvCall) -> RvStatus { + // SAFETY: the fake Host made `call`, with an `RvToolCallArgs` + // behind `args` for a step. + unsafe { + if (*call).verb != RV_TOOL_CALL { + return entry::(call); + } + let lent = (*call).args; + let args = RvToolCallArgs { + caller: RV_CALLER_SCRIPT, + section: rv_str("Only"), + entry: rv_str(""), + model: rv_str(""), + ..lent.cast::().read() + }; + (*call).args = (&raw const args).cast(); + let status = entry::(call); + (*call).args = lent; + status + } + } + + let loaded = testing::load::().unwrap(); + let pack = loaded.new_pack("acme/tools").unwrap(); + assert_eq!( + pack.call("origin", "{}"), + Ok(Ok(ToolOutput::trusted("model|Test|0.0|-"))) + ); + + // SAFETY: `with_script_origin` follows the contract and never + // unwinds. + let loaded = unsafe { testing::load_entry(with_script_origin) }.unwrap(); + let pack = loaded.new_pack("acme/tools").unwrap(); + assert_eq!( + pack.call("origin", "{}"), + Ok(Ok(ToolOutput::trusted("script|Only|-|-"))) + ); + } + + #[test] + fn an_unknown_caller_or_non_utf8_origin_or_model_text_is_a_misuse() { + unsafe extern "C" fn bad_caller(call: *mut RvCall) -> RvStatus { + // SAFETY: the fake Host made `call`. + unsafe { + if (*call).verb != RV_TOOL_CALL { + return entry::(call); + } + let lent = (*call).args; + let args = RvToolCallArgs { + caller: 2, + ..lent.cast::().read() + }; + (*call).args = (&raw const args).cast(); + let status = entry::(call); + (*call).args = lent; + status + } + } + + unsafe extern "C" fn bad_section(call: *mut RvCall) -> RvStatus { + // SAFETY: the fake Host made `call`. + unsafe { + if (*call).verb != RV_TOOL_CALL { + return entry::(call); + } + let lent = (*call).args; + let args = RvToolCallArgs { + section: RvStr { + ptr: NOT_UTF8.as_ptr().cast(), + len: NOT_UTF8.len(), + }, + ..lent.cast::().read() + }; + (*call).args = (&raw const args).cast(); + let status = entry::(call); + (*call).args = lent; + status + } + } + + unsafe extern "C" fn bad_entry(call: *mut RvCall) -> RvStatus { + // SAFETY: the fake Host made `call`. + unsafe { + if (*call).verb != RV_TOOL_CALL { + return entry::(call); + } + let lent = (*call).args; + let args = RvToolCallArgs { + entry: RvStr { + ptr: NOT_UTF8.as_ptr().cast(), + len: NOT_UTF8.len(), + }, + ..lent.cast::().read() + }; + (*call).args = (&raw const args).cast(); + let status = entry::(call); + (*call).args = lent; + status + } + } + + unsafe extern "C" fn bad_model(call: *mut RvCall) -> RvStatus { + // SAFETY: the fake Host made `call`. + unsafe { + if (*call).verb != RV_TOOL_CALL { + return entry::(call); + } + let lent = (*call).args; + let args = RvToolCallArgs { + model: RvStr { + ptr: NOT_UTF8.as_ptr().cast(), + len: NOT_UTF8.len(), + }, + ..lent.cast::().read() + }; + (*call).args = (&raw const args).cast(); + let status = entry::(call); + (*call).args = lent; + status + } + } + + for entry_fn in [bad_caller, bad_section, bad_entry, bad_model] { + // SAFETY: each wrapper follows the contract apart from the + // field under test, and never unwinds. + let loaded = unsafe { testing::load_entry(entry_fn) }.unwrap(); + let pack = loaded.new_pack("acme/tools").unwrap(); + assert_eq!(pack.call("echo", "{}"), Err(Failure::Status(RV_ERR_MISUSE))); + } + } + #[test] fn a_step_without_arguments_is_a_misuse_and_a_cancel_without_state_is_fine() { let mut call = RvCall { diff --git a/crates/runvil-plugin-sdk/src/lib.rs b/crates/runvil-plugin-sdk/src/lib.rs index a0c5675..d39a289 100644 --- a/crates/runvil-plugin-sdk/src/lib.rs +++ b/crates/runvil-plugin-sdk/src/lib.rs @@ -61,7 +61,12 @@ //! request, parks for good. A long job awaits [`next_step`], which ends //! the step and wakes the call for the next one. //! -//! [`ToolCall::resources`] lends what the Host offers every Plugin, such +//! [`ToolCall::caller`], [`ToolCall::section`], [`ToolCall::entry`], and +//! [`ToolCall::model`] tell the tool who asked for the call and where: +//! whether a model round or a section's Lua script called it, the name +//! of that section and its entry (`sys.id`), and, for a model call, the +//! JSON text describing that round's model. [`ToolCall::resources`] lends +//! what the Host offers every Plugin, such //! as the address and the key of a service: the JSON text of an object //! keyed by resource name, as it was when the call started. //! @@ -104,9 +109,10 @@ //! code [`export_plugin!`] expands to, and `testing`. A Plugin written //! against it needs none. //! - What the Host lends in the answer to a file request is copied before -//! the step polls the call's future, and the tool name, the arguments, -//! and the Host's resources are copied on a call's first step, so -//! nothing a Plugin holds points into the Host's memory. +//! the step polls the call's future, and the caller, the tool name, the +//! arguments, the Host's resources, the section, the entry, and the +//! model are copied on a call's first step, so nothing a Plugin holds +//! points into the Host's memory. //! - The Host's resources can hold a key. They sit in one private type //! whose `Debug` prints none of them, so no `Debug` of a [`ToolCall`] //! or of the fake Host's values does. @@ -143,7 +149,9 @@ pub use entry::entry; pub use file::{DirEntry, FileError, FileErrorKind, FileFuture, FileType, Stat}; pub use pack::{BoxFuture, Pack, PackInfo, RenderContext}; pub use runvil_plugin_sys as sys; -pub use tool::{NextStep, ToolCall, ToolError, ToolErrorKind, ToolInfo, ToolOutput, next_step}; +pub use tool::{ + Caller, NextStep, ToolCall, ToolError, ToolErrorKind, ToolInfo, ToolOutput, next_step, +}; /// A Plugin: the instance the Host holds while the Plugin is loaded, and /// the maker of each run's Pack instances. diff --git a/crates/runvil-plugin-sdk/src/tool.rs b/crates/runvil-plugin-sdk/src/tool.rs index d98c5e5..97ae4cf 100644 --- a/crates/runvil-plugin-sdk/src/tool.rs +++ b/crates/runvil-plugin-sdk/src/tool.rs @@ -1,6 +1,6 @@ //! A tool as data, [`ToolInfo`]; what one call of it is lent, -//! [`ToolCall`]; how the call ends, [`ToolOutput`] or [`ToolError`]; and -//! [`next_step`], which splits a long call into steps. +//! [`ToolCall`] and [`Caller`]; how the call ends, [`ToolOutput`] or +//! [`ToolError`]; and [`next_step`], which splits a long call into steps. use std::fmt; use std::future::Future; @@ -74,11 +74,22 @@ impl ToolInfo { } } -/// What one tool call lends its [`Pack`](crate::Pack): the tool's name, -/// the call's arguments, the Host's resources, and the files of the -/// call's run. It borrows from the call, so a Pack cannot keep it past -/// the call's end. Its `Debug` prints none of the resources, because -/// they can hold a key. +/// Who asked for a [`ToolCall`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum Caller { + /// A model round asked for the call. + Model, + /// A section's Lua script called the tool, with `tools.call`. + Script, +} + +/// What one tool call lends its [`Pack`](crate::Pack): who asked for the +/// call and where, the tool's name, the call's arguments, the model of +/// the round that asked for the call, the Host's resources, and the +/// files of the call's run. It borrows from the call, so a Pack cannot +/// keep it past the call's end. Its `Debug` prints none of the +/// resources, because they can hold a key. /// /// The file methods ask the Host, so the run's policy applies to every /// operation, and one the policy denies fails like any other. Each @@ -123,6 +134,37 @@ impl<'a> ToolCall<'a> { &self.state.arguments } + /// Returns who asked for the call: a model round, or a section's Lua + /// script. + #[must_use] + pub fn caller(&self) -> Caller { + self.state.caller + } + + /// Returns the name of the section whose Lua was running when the + /// call was made. + #[must_use] + pub fn section(&self) -> &'a str { + &self.state.section + } + + /// Returns the section entry that made the call, the value a + /// prompt's Lua reads as `sys.id`, or `None` when the Host named + /// none. + #[must_use] + pub fn entry(&self) -> Option<&'a str> { + self.state.entry.as_deref() + } + + /// Returns the JSON text of an object that describes the model of + /// the round that asked for the call, with the keys that + /// [`RenderContext::model`](crate::RenderContext::model) holds, or + /// `None` when the Host named none, as on a script call. + #[must_use] + pub fn model(&self) -> Option<&'a str> { + self.state.model.as_deref() + } + /// The Host's resources as they were when the call started: the JSON /// text of an object keyed by resource name, `{}` when there are none. /// The Plugin parses it with a JSON library of its own. The text can @@ -282,16 +324,20 @@ impl fmt::Debug for Resources { } } -/// What one tool call keeps for all of its steps: the copies of its tool -/// name, its arguments, and the Host's resources that a [`ToolCall`] -/// reads, and the file requests its file methods make. The Host lends -/// the three texts for one step only, so the call's first step copies -/// them here. +/// What one tool call keeps for all of its steps: who asked for the call +/// and where, the copies of its tool name, its arguments, the model, and +/// the Host's resources that a [`ToolCall`] reads, and the file requests +/// its file methods make. The Host lends the strings for one step only, +/// so the call's first step copies them here. #[derive(Debug)] pub(crate) struct CallState { + pub(crate) caller: Caller, pub(crate) tool: String, pub(crate) arguments: String, pub(crate) resources: Resources, + pub(crate) section: String, + pub(crate) entry: Option, + pub(crate) model: Option, /// The call's file requests: its futures queue them, and its steps /// take them to the Host and bring the answers back. pub(crate) requests: Requests, @@ -302,12 +348,33 @@ impl CallState { /// which has asked for no file. pub(crate) fn new(tool: &str, arguments: &str, resources: &str) -> CallState { CallState { + caller: Caller::Model, tool: tool.to_owned(), arguments: arguments.to_owned(), resources: Resources::new(resources), + section: String::new(), + entry: None, + model: None, requests: Requests::default(), } } + + /// Sets who asked for the call, the section and its entry, and the + /// model of the round that asked for the call. Empty `entry` and + /// `model` texts become `None`. + pub(crate) fn with_origin( + mut self, + caller: Caller, + section: &str, + entry: &str, + model: &str, + ) -> CallState { + self.caller = caller; + section.clone_into(&mut self.section); + self.entry = (!entry.is_empty()).then(|| entry.to_owned()); + self.model = (!model.is_empty()).then(|| model.to_owned()); + self + } } /// The text a successful tool call returns, and whether the Plugin @@ -450,7 +517,9 @@ mod tests { use std::sync::atomic::{AtomicUsize, Ordering}; use std::task::{Context, Poll, Wake, Waker}; - use super::{CallState, ToolCall, ToolError, ToolErrorKind, ToolInfo, ToolOutput, next_step}; + use super::{ + CallState, Caller, ToolCall, ToolError, ToolErrorKind, ToolInfo, ToolOutput, next_step, + }; use crate::file::Request; use crate::{FileError, FileErrorKind}; @@ -486,11 +555,27 @@ mod tests { #[test] fn a_tool_call_lends_the_tool_name_the_arguments_and_the_resources() { - let state = CallState::new("fetch", r#"{"url":"x"}"#, RESOURCES); + let state = CallState::new("fetch", r#"{"url":"x"}"#, RESOURCES).with_origin( + Caller::Model, + "Ask", + "0.1", + r#"{"name":"m"}"#, + ); let call = ToolCall::new(&state); + assert_eq!(call.caller(), Caller::Model); assert_eq!(call.tool(), "fetch"); assert_eq!(call.arguments(), r#"{"url":"x"}"#); assert_eq!(call.resources(), RESOURCES); + assert_eq!(call.section(), "Ask"); + assert_eq!(call.entry(), Some("0.1")); + assert_eq!(call.model(), Some(r#"{"name":"m"}"#)); + let script = + CallState::new("fetch", "{}", "{}").with_origin(Caller::Script, "Only", "", ""); + let script_call = ToolCall::new(&script); + assert_eq!(script_call.caller(), Caller::Script); + assert_eq!(script_call.section(), "Only"); + assert_eq!(script_call.entry(), None); + assert_eq!(script_call.model(), None); } #[test] From 57987bd406b46233b0aa4208b6baf30cc1a052a4 Mon Sep 17 00:00:00 2001 From: Vinnie Falco Date: Wed, 2 Dec 2026 08:03:45 -0800 Subject: [PATCH 3/4] Support call origin and model in fake Host and update docs A Plugin test using `testing` had no way to set the caller, the section, the entry, or the model of a tool call. `Call` now defaults to `Caller::Model`, section `"Test"`, entry `"0.0"`, and an empty model, and gains `with_caller`, `with_section`, `with_entry`, `with_model`, and `run`, while `PackRun::call` delegates to `run`. `README.md` is updated for contract 0.8 (`api-v0.8.0`). - `with_caller`, `with_section`, `with_entry`, and `with_model` panic if called after a step has been sent, and `with_model` also panics when a non-empty model string is not a JSON object. - `ORIGIN` in `fixture.rs` records the `caller`, `section`, `entry`, and `model` of each step, and the tests in `testing/call.rs` verify that every step of a call receives the configured values. --- README.md | 11 +- crates/runvil-plugin-sdk/src/entry/tool.rs | 49 +++---- crates/runvil-plugin-sdk/src/testing.rs | 135 +++++++++++++++--- crates/runvil-plugin-sdk/src/testing/call.rs | 63 +++++++- .../runvil-plugin-sdk/src/testing/fixture.rs | 16 ++- 5 files changed, 214 insertions(+), 60 deletions(-) diff --git a/README.md b/README.md index 9118f09..d87d524 100644 --- a/README.md +++ b/README.md @@ -35,10 +35,10 @@ edition = "2024" crate-type = ["cdylib"] [dependencies] -runvil-plugin-sdk = { git = "https://github.com/cppalliance/runvil-plugin-api", tag = "api-v0.7.0" } +runvil-plugin-sdk = { git = "https://github.com/cppalliance/runvil-plugin-api", tag = "api-v0.8.0" } [dev-dependencies] -runvil-plugin-sdk = { git = "https://github.com/cppalliance/runvil-plugin-api", tag = "api-v0.7.0", features = ["test-support"] } +runvil-plugin-sdk = { git = "https://github.com/cppalliance/runvil-plugin-api", tag = "api-v0.8.0", features = ["test-support"] } ``` `src/lib.rs`: @@ -91,6 +91,7 @@ export_plugin!(Acme); - The Plugin's name and version, and the name and description of each Pack, are checked when the Plugin is compiled: one the Harness would reject fails the build, with a message naming the rule. - The Pack's name is a vendor and a Pack id joined by `/`. A prompt reaches the tool above as `hello/greet`, the Pack id and the tool's name. A model calls it by its wire name, which is `hello_greet` unless `ToolInfo::wire_name` sets another. - Arguments and parameter schemas cross as JSON text, so the SDK needs no JSON library. A Plugin parses `call.arguments()` with one of its own. +- `call.caller()` says whether a model round (`Caller::Model`) or a section's Lua script (`Caller::Script`) asked for the call. `call.section()` names the section that made the call, `call.entry()` is the section entry (`sys.id`) when the Host names one, and `call.model()` is the JSON text describing the model of the round that asked for the call, or `None` on a script call. - `call.resources()` is what the Host offers every Plugin, such as the address and the key of a service: the JSON text of an object keyed by resource name, as it was when the call started, and `{}` when the Host offers nothing. A Plugin parses it the same way. It can hold a key, so no `Debug` in the SDK prints it, and a Plugin puts none of it in an output or a failure. - A tool call is a future the Host polls once per step. A `Pending` parks the call, and the Host sends the next step when the future's waker is woken. So a call may wait on a waker like any Rust future: on a timer, a channel, or a task on a runtime the Plugin owns. A future that returns `Pending` without arranging a wake, and without a file request, parks for good. A call that does a long job awaits `next_step()` every so often, which ends the step and wakes the call for the next one, so that no step works for long and the Host can abandon the call between two steps. - A tool reaches the files of its run through its `ToolCall`. `stat`, `list`, `read`, and `read_range` read them, and `write`, `append`, `mkdir`, `remove`, `rename`, and `copy` change them. Each returns a future, as in `call.read(path).await`. Awaiting it ends the step with a request to the Host, and a later step goes on with the answer, so the run's policy applies to every operation. An operation that fails resolves to a `FileError` with a kind and the Host's words for what went wrong, and the call goes on, so the tool decides what the model reads. An answer comes only with a step, so a file method is awaited inside the future that `Pack::call` returns. A file future gets its answer only when a step polls it, so it does not work inside a set that polls a child only after that child's waker fired, such as `FuturesUnordered`. @@ -138,7 +139,7 @@ let pack = loaded.new_pack("acme/hello").unwrap(); assert_eq!(pack.call("greet", "{}"), Ok(Ok(ToolOutput::trusted("Hello.")))); ``` -`load` returns the Plugin's name, version, and Packs, or the failure the Harness would report. `new_pack` returns one run's instance with its tools. `call` runs a tool call to its end as the Harness does: it sends a step, and after each step that parks the call it waits until the Plugin has woken the call, or goes on at once when the step made a file request. A call that nothing wakes fails its test after 60 seconds, with a sentence that says so, and does not hang it. `start` hands back a call whose steps the test sends one at a time with `step`, and `wait` blocks until the call is due its next one. Dropping each value sends the verb that frees what it stands for. +`load` returns the Plugin's name, version, and Packs, or the failure the Harness would report. `new_pack` returns one run's instance with its tools. `call` runs a tool call to its end as the Harness does: it sends a step, and after each step that parks the call it waits until the Plugin has woken the call, or goes on at once when the step made a file request. A call that nothing wakes fails its test after 60 seconds, with a sentence that says so, and does not hang it. `start` hands back a `Call` whose caller, section, entry, and model a test can set with `with_caller`, `with_section`, `with_entry`, and `with_model` before calling `run`, or whose steps the test sends one at a time with `step`, and `wait` blocks until the call is due its next one. Dropping each value sends the verb that frees what it stands for. Every call is lent `{}` as the Host's resources, unless `with_resources` gives the run another text: @@ -178,11 +179,11 @@ A Host can also link a Plugin crate in and pass `runvil_plugin_sdk::entry::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. +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. `caller` (`RV_CALLER_MODEL` or `RV_CALLER_SCRIPT`), `section`, `entry`, `model`, and `resources` in the same `RvToolCallArgs` tell the step who asked for the call, which section and entry made it, the JSON text describing the round's model on a model call, and 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.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. +The contract's version is `RV_API_MAJOR`.`RV_API_MINOR`, and `runvil-plugin-sys` has the same version number. While the major version is 0, each version is its own contract, so a Plugin built for 0.8 loads only in a Host that speaks exactly 0.8. From 1.0, minor versions only add, and a Plugin built for 1.n loads in any Host that speaks 1.n or later. 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/src/entry/tool.rs b/crates/runvil-plugin-sdk/src/entry/tool.rs index baafcc5..b92e5f8 100644 --- a/crates/runvil-plugin-sdk/src/entry/tool.rs +++ b/crates/runvil-plugin-sdk/src/entry/tool.rs @@ -330,11 +330,11 @@ mod tests { use std::time::Duration; use runvil_plugin_sys::{ - RV_CALLER_SCRIPT, RV_ERR_MISUSE, RV_MAX_RESULT, RV_OK, RV_TOOL_CALL, RV_TOOL_CANCEL, - RvCall, RvStatus, RvStr, RvToolCallArgs, + RV_ERR_MISUSE, RV_MAX_RESULT, RV_OK, RV_TOOL_CALL, RV_TOOL_CANCEL, RvCall, RvStatus, RvStr, + RvToolCallArgs, }; - use crate::entry::{entry, rv_str, size_field}; + use crate::entry::{entry, size_field}; use crate::testing::{self, Failure}; use crate::{ BoxFuture, Caller, Pack, PackInfo, Plugin, Refusal, ToolCall, ToolError, ToolErrorKind, @@ -821,43 +821,30 @@ mod tests { #[test] fn a_call_copies_the_caller_section_entry_and_model_on_its_first_step() { - unsafe extern "C" fn with_script_origin(call: *mut RvCall) -> RvStatus { - // SAFETY: the fake Host made `call`, with an `RvToolCallArgs` - // behind `args` for a step. - unsafe { - if (*call).verb != RV_TOOL_CALL { - return entry::(call); - } - let lent = (*call).args; - let args = RvToolCallArgs { - caller: RV_CALLER_SCRIPT, - section: rv_str("Only"), - entry: rv_str(""), - model: rv_str(""), - ..lent.cast::().read() - }; - (*call).args = (&raw const args).cast(); - let status = entry::(call); - (*call).args = lent; - status - } - } - let loaded = testing::load::().unwrap(); let pack = loaded.new_pack("acme/tools").unwrap(); assert_eq!( pack.call("origin", "{}"), Ok(Ok(ToolOutput::trusted("model|Test|0.0|-"))) ); - - // SAFETY: `with_script_origin` follows the contract and never - // unwinds. - let loaded = unsafe { testing::load_entry(with_script_origin) }.unwrap(); - let pack = loaded.new_pack("acme/tools").unwrap(); assert_eq!( - pack.call("origin", "{}"), + pack.start("origin", "{}") + .with_caller(Caller::Script) + .with_section("Only") + .with_entry("") + .with_model("") + .run(), Ok(Ok(ToolOutput::trusted("script|Only|-|-"))) ); + assert_eq!( + pack.start("origin", "{}") + .with_caller(Caller::Model) + .with_section("Ask") + .with_entry("0.2") + .with_model(r#"{"name":"m"}"#) + .run(), + Ok(Ok(ToolOutput::trusted(r#"model|Ask|0.2|{"name":"m"}"#))) + ); } #[test] diff --git a/crates/runvil-plugin-sdk/src/testing.rs b/crates/runvil-plugin-sdk/src/testing.rs index 7de69cf..5b8c346 100644 --- a/crates/runvil-plugin-sdk/src/testing.rs +++ b/crates/runvil-plugin-sdk/src/testing.rs @@ -47,8 +47,14 @@ //! [`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: +//! Every call is lent a caller, a section, an entry, a model, and the +//! Host's resources. By default a call is from [`Caller::Model`], in the +//! section `"Test"` with the entry `"0.0"` and no model, and [`Call`] has +//! [`with_caller`](Call::with_caller), [`with_section`](Call::with_section), +//! [`with_entry`](Call::with_entry), and [`with_model`](Call::with_model) +//! to set others before [`Call::run`] or the first [`Call::step`]. The +//! resources are `{}` unless [`PackRun::with_resources`] gives the run +//! another: //! //! ```text //! let resources = r#"{"acme/search":{"url":"http://127.0.0.1:9/search"}}"#; @@ -81,9 +87,9 @@ use std::time::Duration; use std::{mem, ptr}; use runvil_plugin_sys::{ - PluginEntry, RV_API_MAJOR, RV_API_MINOR, RV_CALLER_MODEL, RV_OK, RV_PACK_DELETE, RV_PACK_NEW, - RV_PENDING, RV_PLUGIN_LOAD, RV_PLUGIN_UNLOAD, RV_TOOL_CALL, RV_TOOL_CANCEL, RvCall, RvHost, - RvLoadArgs, RvPackNewArgs, RvStatus, RvToolCallArgs, + PluginEntry, RV_API_MAJOR, RV_API_MINOR, RV_CALLER_MODEL, RV_CALLER_SCRIPT, RV_OK, + RV_PACK_DELETE, RV_PACK_NEW, RV_PENDING, RV_PLUGIN_LOAD, RV_PLUGIN_UNLOAD, RV_TOOL_CALL, + RV_TOOL_CANCEL, RvCall, RvHost, RvLoadArgs, RvPackNewArgs, RvStatus, RvToolCallArgs, }; use self::session::{Described, Session, Verb}; @@ -91,7 +97,7 @@ pub use self::tree::Files; use self::wake::WakerCell; use crate::entry::{rv_str, size_field}; use crate::tool::Resources; -use crate::{Plugin, ToolError, ToolInfo, ToolOutput, entry}; +use crate::{Caller, Plugin, ToolError, ToolInfo, ToolOutput, entry}; /// How a tool call ended: its output, or its failure. pub type ToolResult = Result; @@ -354,18 +360,13 @@ impl PackRun<'_> { /// 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 { - if let Some(result) = call.step()? { - return Ok(result); - } - call.wait(); - } + self.start(tool, arguments).run() } /// Starts one call of `tool` with `arguments`, the JSON text of its - /// arguments, for a test that sends each step itself. Nothing is sent - /// until the first [`Call::step`]. + /// arguments, for a test that configures who asked for the call or + /// sends each step itself. Nothing is sent until [`Call::run`] or the + /// first [`Call::step`]. /// /// # Panics /// Panics when the instance added no tool named `tool` and no render @@ -381,8 +382,12 @@ impl PackRun<'_> { ); Call { pack: self, + caller: Caller::Model, tool: tool.to_owned(), arguments: arguments.to_owned(), + section: "Test".to_owned(), + entry: "0.0".to_owned(), + model: String::new(), state: ptr::null_mut(), pending: false, ended: false, @@ -417,8 +422,12 @@ impl Drop for PackRun<'_> { #[derive(Debug)] pub struct Call<'a> { pack: &'a PackRun<'a>, + caller: Caller, tool: String, arguments: String, + section: String, + entry: String, + model: String, /// What the last step left in `call->tool_call`. state: *mut c_void, /// Whether the last step returned `RV_PENDING`. @@ -434,6 +443,91 @@ pub struct Call<'a> { } impl Call<'_> { + /// Sets who asked for the call, in place of [`Caller::Model`]. + /// + /// # Panics + /// Panics when a step of the call has been sent already. + #[must_use] + pub fn with_caller(mut self, caller: Caller) -> Self { + self.assert_unstarted(); + self.caller = caller; + self + } + + /// Sets the name of the section that made the call, in place of + /// `"Test"`. + /// + /// # Panics + /// Panics when a step of the call has been sent already. + #[must_use] + pub fn with_section(mut self, section: impl Into) -> Self { + self.assert_unstarted(); + self.section = section.into(); + self + } + + /// Sets the section entry (`sys.id`) that made the call, in place of + /// `"0.0"`. An empty string lends an empty `entry`, which + /// [`ToolCall::entry`](crate::ToolCall::entry) reads as `None`. + /// + /// # Panics + /// Panics when a step of the call has been sent already. + #[must_use] + pub fn with_entry(mut self, entry: impl Into) -> Self { + self.assert_unstarted(); + self.entry = entry.into(); + self + } + + /// Sets the JSON text describing the model of the round that asked + /// for the call, in place of an empty string. An empty string lends + /// an empty `model`, which [`ToolCall::model`](crate::ToolCall::model) + /// reads as `None`. + /// + /// # Panics + /// Panics when a step of the call has been sent already, or when + /// `model` is neither empty nor the JSON text of an object, which the + /// Harness never sends. + #[must_use] + pub fn with_model(mut self, model: impl Into) -> Self { + self.assert_unstarted(); + let model = model.into(); + assert!( + model.is_empty() || json::is_object(&model), + "the model must be a JSON object or empty: {model}" + ); + self.model = model; + self + } + + /// Runs the call to its end, as [`PackRun::call`] does: sends a step + /// with [`Call::step`], and after each one that returns `RV_PENDING` + /// waits with [`Call::wait`] until the call is due its next step. + /// + /// # Errors + /// Returns the [`Failure`] the Harness would report for a call that + /// breaks the contract; see [`Call::step`]. + /// + /// # Panics + /// Panics when the call has ended, or when a step parks the call and + /// the Plugin does not wake it within 60 seconds; see [`Call::wait`]. + pub fn run(mut self) -> Result { + loop { + if let Some(result) = self.step()? { + return Ok(result); + } + self.wait(); + } + } + + /// Checks that no step of the call has been sent yet. + fn assert_unstarted(&self) { + assert!( + self.state.is_null() && !self.pending && !self.ended, + "the call's origin and model are fixed before its first step" + ); + } + /// Sends one `RV_TOOL_CALL`. Returns `None` when the step returned /// `RV_PENDING`, which parks the call, and the tool's own result once /// the call ended. [`Call::wait`] blocks until a parked call is due @@ -476,7 +570,10 @@ impl Call<'_> { let (status, mut session) = session::open(Verb::ToolCall, |ctx| { let args = RvToolCallArgs { size: size_field::(), - caller: RV_CALLER_MODEL, + caller: match self.caller { + Caller::Model => RV_CALLER_MODEL, + Caller::Script => RV_CALLER_SCRIPT, + }, ctx, tool: rv_str(&self.tool), arguments: rv_str(&self.arguments), @@ -493,9 +590,9 @@ impl Call<'_> { file_copy: file::file_copy, resources: rv_str(self.pack.resources.text()), waker: WakerCell::waker(&self.waker), - section: rv_str("Test"), - entry: rv_str("0.0"), - model: rv_str(""), + section: rv_str(&self.section), + entry: rv_str(&self.entry), + model: rv_str(&self.model), }; call.args = (&raw const args).cast(); // SAFETY: `load_entry`'s caller guaranteed `entry` follows the diff --git a/crates/runvil-plugin-sdk/src/testing/call.rs b/crates/runvil-plugin-sdk/src/testing/call.rs index 0046a84..b2e083b 100644 --- a/crates/runvil-plugin-sdk/src/testing/call.rs +++ b/crates/runvil-plugin-sdk/src/testing/call.rs @@ -79,11 +79,11 @@ mod tests { use std::time::Duration; - use runvil_plugin_sys::RV_ERR_UNSUPPORTED; + use runvil_plugin_sys::{RV_CALLER_MODEL, RV_CALLER_SCRIPT, RV_ERR_UNSUPPORTED}; - use crate::testing::fixture::{self, ANSWERS, Breach, CANCELS, LENT, WAKER}; + use crate::testing::fixture::{self, ANSWERS, Breach, CANCELS, LENT, ORIGIN, WAKER}; use crate::testing::{Failure, Files}; - use crate::{ToolError, ToolErrorKind, ToolOutput}; + use crate::{Caller, ToolError, ToolErrorKind, ToolOutput}; #[test] fn a_call_that_follows_the_contract_ends_with_its_result_and_no_cancel() { @@ -386,4 +386,61 @@ mod tests { let _result = call.step(); let _again = call.step(); } + + #[test] + fn every_step_of_a_call_is_lent_its_caller_section_entry_and_model() { + let loaded = fixture::load(Breach::None).unwrap(); + let pack = loaded.new_pack("acme/fixture").unwrap(); + let _ = ORIGIN.take(); + assert!(pack.call("tool", "{}").is_ok()); + assert_eq!( + ORIGIN.take(), + vec![( + RV_CALLER_MODEL, + "Test".to_owned(), + "0.0".to_owned(), + String::new() + )] + ); + + let result = pack + .start("other", "{}") + .with_caller(Caller::Script) + .with_section("Ask") + .with_entry("0.2") + .with_model(r#"{"name":"m"}"#) + .run(); + assert_eq!(result, Ok(Ok(ToolOutput::untrusted("other after 2 steps")))); + let origin = ORIGIN.take(); + assert_eq!(origin.len(), 3, "one for each step"); + for step_origin in origin { + assert_eq!( + step_origin, + ( + RV_CALLER_SCRIPT, + "Ask".to_owned(), + "0.2".to_owned(), + r#"{"name":"m"}"#.to_owned(), + ) + ); + } + } + + #[test] + #[should_panic(expected = "the model must be a JSON object or empty: [1]")] + fn a_model_that_is_not_an_object_is_the_tests_own_fault() { + let loaded = fixture::load(Breach::None).unwrap(); + let pack = loaded.new_pack("acme/fixture").unwrap(); + let _call = pack.start("tool", "{}").with_model("[1]"); + } + + #[test] + #[should_panic(expected = "the call's origin and model are fixed before its first step")] + fn setting_a_calls_origin_after_a_step_is_the_tests_own_fault() { + let loaded = fixture::load(Breach::None).unwrap(); + let pack = loaded.new_pack("acme/fixture").unwrap(); + let mut call = pack.start("other", "{}"); + assert_eq!(call.step(), Ok(None)); + let _call = call.with_caller(Caller::Script); + } } diff --git a/crates/runvil-plugin-sdk/src/testing/fixture.rs b/crates/runvil-plugin-sdk/src/testing/fixture.rs index 39f2900..2e10225 100644 --- a/crates/runvil-plugin-sdk/src/testing/fixture.rs +++ b/crates/runvil-plugin-sdk/src/testing/fixture.rs @@ -32,6 +32,10 @@ thread_local! { /// What each step the fixture on this thread got was lent: the /// resources, and the address of the waker's `ctx`. pub(super) static LENT: RefCell> = const { RefCell::new(Vec::new()) }; + /// The caller, section, entry, and model each step the fixture on + /// this thread got was lent. + pub(super) static ORIGIN: RefCell> = + const { RefCell::new(Vec::new()) }; } /// The one rule the fixture breaks. @@ -319,9 +323,17 @@ unsafe fn tool_call(call: *mut RvCall, args: &RvToolCallArgs, breach: Breach) -> // Host only ever sends UTF-8. let (tool, arguments) = unsafe { (text(args.tool), text(args.arguments)) }; WAKER.set(Some(args.waker)); - // SAFETY: the Host keeps the resources valid for the step. - let resources = unsafe { text(args.resources) }.to_owned(); + // SAFETY: the Host keeps the strings valid for the step. + let (resources, section, entry, model) = unsafe { + ( + text(args.resources).to_owned(), + text(args.section).to_owned(), + text(args.entry).to_owned(), + text(args.model).to_owned(), + ) + }; LENT.with_borrow_mut(|lent| lent.push((resources, args.waker.ctx.addr()))); + ORIGIN.with_borrow_mut(|origin| origin.push((args.caller, section, entry, model))); if !args.answer.is_null() { ANSWERS.set(ANSWERS.get() + 1); } From f2d42cc41b0f28f81ac73193f21c2eacfafc11d9 Mon Sep 17 00:00:00 2001 From: Vinnie Falco Date: Wed, 2 Dec 2026 08:16:31 -0800 Subject: [PATCH 4/4] Answer the review of the call origin and model The review of the contract 0.8 pull request found three cases where the contract, the entry point, and the fake Host could disagree. `RvToolCallArgs` now states that `model` is empty whenever no model is named, `run` in `testing.rs` waits before each `step`, and both `start` and `Call::step` reject a `Caller::Script` call that carries a non-empty `model`. - `runvil_plugin.h` is regenerated with the updated `model` comment. - `start` in `entry/tool.rs` returns `RV_ERR_MISUSE` when `caller` is `Caller::Script` and `model` is not empty, and `Call::step` in `testing.rs` panics on that pair. - `testing/call.rs` adds tests for `run` resuming an already-pending call and for `Call::step` rejecting a script call with a model. --- crates/runvil-plugin-sdk/src/entry/tool.rs | 141 +++++++++--------- crates/runvil-plugin-sdk/src/testing.rs | 23 ++- crates/runvil-plugin-sdk/src/testing/call.rs | 45 +++++- .../runvil-plugin-sys/include/runvil_plugin.h | 8 +- crates/runvil-plugin-sys/src/lib.rs | 8 +- 5 files changed, 135 insertions(+), 90 deletions(-) diff --git a/crates/runvil-plugin-sdk/src/entry/tool.rs b/crates/runvil-plugin-sdk/src/entry/tool.rs index b92e5f8..5818355 100644 --- a/crates/runvil-plugin-sdk/src/entry/tool.rs +++ b/crates/runvil-plugin-sdk/src/entry/tool.rs @@ -252,6 +252,9 @@ unsafe fn start(call: *mut RvCall, args: &RvToolCallArgs) -> Result, R else { return Err(RV_ERR_MISUSE); }; + if caller == Caller::Script && !model.is_empty() { + return Err(RV_ERR_MISUSE); + } let state = CallState::new(tool, arguments, resources).with_origin(caller, section, entry, model); // SAFETY: `args` belongs to the open step. @@ -330,11 +333,11 @@ mod tests { use std::time::Duration; use runvil_plugin_sys::{ - RV_ERR_MISUSE, RV_MAX_RESULT, RV_OK, RV_TOOL_CALL, RV_TOOL_CANCEL, RvCall, RvStatus, RvStr, - RvToolCallArgs, + RV_CALLER_SCRIPT, RV_ERR_MISUSE, RV_MAX_RESULT, RV_OK, RV_TOOL_CALL, RV_TOOL_CANCEL, + RvCall, RvStatus, RvStr, RvToolCallArgs, }; - use crate::entry::{entry, size_field}; + use crate::entry::{entry, rv_str, size_field}; use crate::testing::{self, Failure}; use crate::{ BoxFuture, Caller, Pack, PackInfo, Plugin, Refusal, ToolCall, ToolError, ToolErrorKind, @@ -784,9 +787,16 @@ mod tests { /// Bytes that are not UTF-8. static NOT_UTF8: [u8; 2] = [0xff, 0xfe]; - /// The entry point of [`Tools`], behind a Host that lends every step - /// resources that are not UTF-8. - unsafe extern "C" fn garbled(call: *mut RvCall) -> RvStatus { + /// Calls `entry::(call)`, replacing the `RvToolCallArgs` of a + /// step with what `edit` returns. + /// + /// # Safety + /// The fake Host made `call`, with an `RvToolCallArgs` behind `args` + /// for a step. + unsafe fn replace_step_args( + call: *mut RvCall, + edit: impl FnOnce(RvToolCallArgs) -> RvToolCallArgs, + ) -> RvStatus { // SAFETY: the fake Host made `call`, with an `RvToolCallArgs` // behind `args` for a step. The copy lent in its place lives // until the entry point has returned, and the Host's own is put @@ -796,13 +806,7 @@ mod tests { return entry::(call); } let lent = (*call).args; - let args = RvToolCallArgs { - resources: RvStr { - ptr: NOT_UTF8.as_ptr().cast(), - len: NOT_UTF8.len(), - }, - ..lent.cast::().read() - }; + let args = edit(lent.cast::().read()); (*call).args = (&raw const args).cast(); let status = entry::(call); (*call).args = lent; @@ -810,6 +814,26 @@ mod tests { } } + /// An `RvStr` pointing at [`NOT_UTF8`]. + fn non_utf8_str() -> RvStr { + RvStr { + ptr: NOT_UTF8.as_ptr().cast(), + len: NOT_UTF8.len(), + } + } + + /// The entry point of [`Tools`], behind a Host that lends every step + /// resources that are not UTF-8. + unsafe extern "C" fn garbled(call: *mut RvCall) -> RvStatus { + // SAFETY: the fake Host made `call`. + unsafe { + replace_step_args(call, |args| RvToolCallArgs { + resources: non_utf8_str(), + ..args + }) + } + } + #[test] fn resources_that_are_not_utf8_are_a_misuse() { // SAFETY: `garbled` follows the contract apart from the text this @@ -851,86 +875,57 @@ mod tests { fn an_unknown_caller_or_non_utf8_origin_or_model_text_is_a_misuse() { unsafe extern "C" fn bad_caller(call: *mut RvCall) -> RvStatus { // SAFETY: the fake Host made `call`. - unsafe { - if (*call).verb != RV_TOOL_CALL { - return entry::(call); - } - let lent = (*call).args; - let args = RvToolCallArgs { - caller: 2, - ..lent.cast::().read() - }; - (*call).args = (&raw const args).cast(); - let status = entry::(call); - (*call).args = lent; - status - } + unsafe { replace_step_args(call, |args| RvToolCallArgs { caller: 2, ..args }) } } unsafe extern "C" fn bad_section(call: *mut RvCall) -> RvStatus { // SAFETY: the fake Host made `call`. unsafe { - if (*call).verb != RV_TOOL_CALL { - return entry::(call); - } - let lent = (*call).args; - let args = RvToolCallArgs { - section: RvStr { - ptr: NOT_UTF8.as_ptr().cast(), - len: NOT_UTF8.len(), - }, - ..lent.cast::().read() - }; - (*call).args = (&raw const args).cast(); - let status = entry::(call); - (*call).args = lent; - status + replace_step_args(call, |args| RvToolCallArgs { + section: non_utf8_str(), + ..args + }) } } unsafe extern "C" fn bad_entry(call: *mut RvCall) -> RvStatus { // SAFETY: the fake Host made `call`. unsafe { - if (*call).verb != RV_TOOL_CALL { - return entry::(call); - } - let lent = (*call).args; - let args = RvToolCallArgs { - entry: RvStr { - ptr: NOT_UTF8.as_ptr().cast(), - len: NOT_UTF8.len(), - }, - ..lent.cast::().read() - }; - (*call).args = (&raw const args).cast(); - let status = entry::(call); - (*call).args = lent; - status + replace_step_args(call, |args| RvToolCallArgs { + entry: non_utf8_str(), + ..args + }) } } unsafe extern "C" fn bad_model(call: *mut RvCall) -> RvStatus { // SAFETY: the fake Host made `call`. unsafe { - if (*call).verb != RV_TOOL_CALL { - return entry::(call); - } - let lent = (*call).args; - let args = RvToolCallArgs { - model: RvStr { - ptr: NOT_UTF8.as_ptr().cast(), - len: NOT_UTF8.len(), - }, - ..lent.cast::().read() - }; - (*call).args = (&raw const args).cast(); - let status = entry::(call); - (*call).args = lent; - status + replace_step_args(call, |args| RvToolCallArgs { + model: non_utf8_str(), + ..args + }) } } - for entry_fn in [bad_caller, bad_section, bad_entry, bad_model] { + unsafe extern "C" fn script_with_model(call: *mut RvCall) -> RvStatus { + // SAFETY: the fake Host made `call`. + unsafe { + replace_step_args(call, |args| RvToolCallArgs { + caller: RV_CALLER_SCRIPT, + model: rv_str(r#"{"name":"m"}"#), + ..args + }) + } + } + + for entry_fn in [ + bad_caller, + bad_section, + bad_entry, + bad_model, + script_with_model, + ] { // SAFETY: each wrapper follows the contract apart from the // field under test, and never unwinds. let loaded = unsafe { testing::load_entry(entry_fn) }.unwrap(); diff --git a/crates/runvil-plugin-sdk/src/testing.rs b/crates/runvil-plugin-sdk/src/testing.rs index 5b8c346..c94fda9 100644 --- a/crates/runvil-plugin-sdk/src/testing.rs +++ b/crates/runvil-plugin-sdk/src/testing.rs @@ -500,23 +500,25 @@ impl Call<'_> { self } - /// Runs the call to its end, as [`PackRun::call`] does: sends a step - /// with [`Call::step`], and after each one that returns `RV_PENDING` - /// waits with [`Call::wait`] until the call is due its next step. + /// Runs the call to its end, as [`PackRun::call`] does: waits with + /// [`Call::wait`] until the call is due its next step, and then sends + /// a step with [`Call::step`], until a step ends the call. /// /// # Errors /// Returns the [`Failure`] the Harness would report for a call that /// breaks the contract; see [`Call::step`]. /// /// # Panics - /// Panics when the call has ended, or when a step parks the call and - /// the Plugin does not wake it within 60 seconds; see [`Call::wait`]. + /// Panics when the call has ended, when `caller` is + /// [`Caller::Script`] and `model` is not empty, or when a step parks + /// the call and the Plugin does not wake it within 60 seconds; see + /// [`Call::step`] and [`Call::wait`]. pub fn run(mut self) -> Result { loop { + self.wait(); if let Some(result) = self.step()? { return Ok(result); } - self.wait(); } } @@ -552,9 +554,16 @@ impl Call<'_> { /// call, and the file request of a step that failed is not performed. /// /// # Panics - /// Panics when the call has ended, which the Harness never steps. + /// Panics when the call has ended, or when `caller` is + /// [`Caller::Script`] and `model` is not empty, which the Harness + /// never sends. pub fn step(&mut self) -> Result, Failure> { assert!(!self.ended, "the call has ended and takes no more steps"); + assert!( + self.caller != Caller::Script || self.model.is_empty(), + "a script call has no model: {}", + self.model + ); let mut call = RvCall { tool_call: self.state, ..self.pack.new_call(RV_TOOL_CALL) diff --git a/crates/runvil-plugin-sdk/src/testing/call.rs b/crates/runvil-plugin-sdk/src/testing/call.rs index b2e083b..b8daccd 100644 --- a/crates/runvil-plugin-sdk/src/testing/call.rs +++ b/crates/runvil-plugin-sdk/src/testing/call.rs @@ -405,7 +405,7 @@ mod tests { let result = pack .start("other", "{}") - .with_caller(Caller::Script) + .with_caller(Caller::Model) .with_section("Ask") .with_entry("0.2") .with_model(r#"{"name":"m"}"#) @@ -417,13 +417,54 @@ mod tests { assert_eq!( step_origin, ( - RV_CALLER_SCRIPT, + RV_CALLER_MODEL, "Ask".to_owned(), "0.2".to_owned(), r#"{"name":"m"}"#.to_owned(), ) ); } + + let script_result = pack + .start("tool", "{}") + .with_caller(Caller::Script) + .with_section("Only") + .with_entry("0.1") + .run(); + assert_eq!(script_result, Ok(Ok(ToolOutput::untrusted("tool {}")))); + assert_eq!( + ORIGIN.take(), + vec![( + RV_CALLER_SCRIPT, + "Only".to_owned(), + "0.1".to_owned(), + String::new() + )] + ); + } + + #[test] + fn run_waits_for_a_pending_call_before_sending_its_next_step() { + let loaded = fixture::load(Breach::None).unwrap(); + let pack = loaded.new_pack("acme/fixture").unwrap(); + let mut call = pack.start("other", "{}"); + assert_eq!(call.step(), Ok(None)); + assert_eq!( + call.run(), + Ok(Ok(ToolOutput::untrusted("other after 2 steps"))) + ); + } + + #[test] + #[should_panic(expected = "a script call has no model: {\"name\":\"m\"}")] + fn a_script_call_with_a_model_is_the_tests_own_fault() { + let loaded = fixture::load(Breach::None).unwrap(); + let pack = loaded.new_pack("acme/fixture").unwrap(); + let _result = pack + .start("tool", "{}") + .with_caller(Caller::Script) + .with_model(r#"{"name":"m"}"#) + .step(); } #[test] diff --git a/crates/runvil-plugin-sys/include/runvil_plugin.h b/crates/runvil-plugin-sys/include/runvil_plugin.h index b8ad1ec..bf0bb43 100644 --- a/crates/runvil-plugin-sys/include/runvil_plugin.h +++ b/crates/runvil-plugin-sys/include/runvil_plugin.h @@ -150,8 +150,8 @@ * empty when none is named; and `model` is the JSON text of an object * that describes the model of the round that asked for the call, with * the keys that `model` in `RvPackRenderArgs` holds, or empty when - * `caller` is `RV_CALLER_SCRIPT`. Like `tool` and `arguments`, each - * string is valid for the step. + * none is named, as when `caller` is `RV_CALLER_SCRIPT`. Like `tool` + * and `arguments`, each string is valid for the step. * - A step ends the call by calling `finish` once and returning * `RV_OK`. Any return other than `RV_PENDING` ends the call, and a * call that ends without a result fails. @@ -987,8 +987,8 @@ struct RvToolCallArgs { /** * The JSON text of an object that describes the model of the round * that asked for the call, with the keys that `model` in - * `RvPackRenderArgs` holds, or empty when `caller` is - * `RV_CALLER_SCRIPT`. Valid for the step. + * `RvPackRenderArgs` holds, or empty when none is named, as when + * `caller` is `RV_CALLER_SCRIPT`. Valid for the step. */ struct RvStr model; }; diff --git a/crates/runvil-plugin-sys/src/lib.rs b/crates/runvil-plugin-sys/src/lib.rs index 4852550..f6fa5c7 100644 --- a/crates/runvil-plugin-sys/src/lib.rs +++ b/crates/runvil-plugin-sys/src/lib.rs @@ -145,8 +145,8 @@ //! empty when none is named; and `model` is the JSON text of an object //! that describes the model of the round that asked for the call, with //! the keys that `model` in [`RvPackRenderArgs`] holds, or empty when -//! `caller` is [`RV_CALLER_SCRIPT`]. Like `tool` and `arguments`, each -//! string is valid for the step. +//! none is named, as when `caller` is [`RV_CALLER_SCRIPT`]. Like `tool` +//! and `arguments`, each string is valid for the step. //! - A step ends the call by calling `finish` once and returning //! [`RV_OK`]. Any return other than [`RV_PENDING`] ends the call, and a //! call that ends without a result fails. @@ -863,8 +863,8 @@ pub struct RvToolCallArgs { pub entry: RvStr, /// The JSON text of an object that describes the model of the round /// that asked for the call, with the keys that `model` in - /// [`RvPackRenderArgs`] holds, or empty when `caller` is - /// [`RV_CALLER_SCRIPT`]. Valid for the step. + /// [`RvPackRenderArgs`] holds, or empty when none is named, as when + /// `caller` is [`RV_CALLER_SCRIPT`]. Valid for the step. pub model: RvStr, }