From a4d8f4d98a031ed6394084ae1aa6eda2d2faa8a9 Mon Sep 17 00:00:00 2001 From: Vinnie Falco Date: Wed, 2 Dec 2026 18:44:15 -0800 Subject: [PATCH 1/4] Add the plan for native preludes and RvLua Record the multi-wave plan to add native preludes (RV_PACK_OPEN and RvLua) and optional Lua source preludes to the C Plugin contract (version 0.10.0), unvil-plugin-sdk, and unvil-harness. Plan: /plan/2026-12-02-3-native-preludes.plan.md --- plan/2026-12-02-3-native-preludes.plan.md | 131 ++++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 plan/2026-12-02-3-native-preludes.plan.md diff --git a/plan/2026-12-02-3-native-preludes.plan.md b/plan/2026-12-02-3-native-preludes.plan.md new file mode 100644 index 0000000..e0492b4 --- /dev/null +++ b/plan/2026-12-02-3-native-preludes.plan.md @@ -0,0 +1,131 @@ +--- +name: Native Preludes and RvLua +overview: Add native preludes (RV_PACK_OPEN and the handle-based RvLua C API) and optional Lua source preludes to the C Plugin contract (v0.10.0) and runvil-plugin-sdk, implement the Engine's mlua-backed RvLua host and native Prelude support in runvil-harness, and roll out contract 0.10.0 across the downstream plugin, workshop, and runvil repositories with lean, bloat-free commits, rust-rulebook compliance on every touched file, PRs, CodeRabbit triage, and ordered upstream merges. +todos: + - id: wave1-plugin-api + content: "Wave 1 (runvil-plugin-api v0.10.0 -> SHA P): 3 testable commits (plan copy, bump runvil-plugin-sys to 0.10.0 + runvil_plugin.h + c-layout, add lean LuaPrelude/Pack::open/PackInfo::lua_prelude + fake Host in runvil-plugin-sdk); apply rust-rulebook to all touched files, push to origin, open PR, address worthwhile CodeRabbit feedback, and merge to upstream" + status: pending + - id: wave2a-three-plugins + content: "Wave 2a (runvil-plugin-std, bashkit, web in parallel -> SHAs S, B, W): 2 testable commits per repo (plan copy, pin runvil-plugin-sdk 0.10.0 at SHA P); apply rust-rulebook, push to origin, open PRs, triage CodeRabbit, and merge to upstream" + status: pending + - id: wave2b-harness + content: "Wave 2b (runvil-harness -> SHA H, parallel with Wave 2a): 4 testable commits (plan copy, lean mlua host + Prelude open in runvil-lua/runvil-types/runvil-plugin, pin contract 0.10.0 at SHA P + RV_PACK_OPEN/RvLua in harness-plugin-loader/harness-runner, update harness-test-plugin + decisions/ + public-api.txt); apply rust-rulebook to all touched files, push to origin, open PR, triage CodeRabbit, and merge to upstream" + status: pending + - id: wave3-workshop-and-runvil + content: "Wave 3 (runvil-workshop -> SHA K, then runvil): 2 testable commits in runvil-workshop pinning H/P/S/B/W, PR + CodeRabbit + merge to upstream (SHA K); then 2 testable commits in runvil pinning Workshop SHA K, PR + CodeRabbit + merge to upstream" + status: pending +isProject: false +--- + +# Native Preludes and Handle-Based `RvLua` in the Plugin Contract and Engine + +## Core Discipline: Lean Code, `rust-rulebook.md`, Testable Commits, and Ordered PRs + +1. **Tight, lean code with zero bloat**: + - Do not invent redundant wrapper structs, traits, or helper functions when an existing type or direct function suffices. + - Reuse existing code directly instead of duplicating logic: + - In `runvil-lua`: reuse `order::WalkPlace` / `order::compare_places` for deterministic table walks, `proxy::view_data` for \(O(1)\) Engine view unsealing, `json::json_of_text` and `json::to_json` for `from_json` / `to_json`, and `prelude.rs`'s existing `env` creation, `defined_globals`, collision checks, and `read_only_proxy` sealing. + - In `harness-plugin-loader`: reuse `session::{Field, Shape, RESERVED, field, shape, size_field, rv_str}` and `Plugin`'s `Arc` ownership. + - In `runvil-plugin-sdk`: keep the safe Lua wrapper in one focused `src/lua.rs` module (`Lua<'a>`, `Value<'a>`, `Table<'a>`, `UserDataType`) without mirroring unnecessary `mlua` traits. + - Keep `Prelude` in `crates/runvil-internal/types/src/packs.rs` (or `runvil-lua`) as a single struct rather than introducing parallel prelude types; attach the optional native opener closure directly on `Prelude` with crate-internal constructors so `public-api.txt` gains zero unnecessary surface items. + +2. **Apply `tools-public/rulebooks/rust-rulebook.md` to every touched `.rs` file**: + - Three-block `use` grouping (`std`/`core`/`alloc`, external crates, `crate`/`super`/`self`); import types by name and free functions through their module (`use std::fmt;` then `fmt::Display`). + - `pub(crate)` default visibility; `unreachable_pub` clean; no test-only `#[cfg(test)] use` in parent modules feeding child test globs. + - Guard clauses with `let Some(...) = ... else { return ... };`; no `.unwrap()` in library code; `#[expect(..., reason = "...")]` instead of `#[allow(...)]`. + - Every `unsafe fn` has `# Safety`, every `unsafe` block is preceded immediately by `// SAFETY:`, and edition 2024 inner `unsafe` blocks are explicit inside `unsafe fn`s. + - Every `pub` item has third-person indicative `///` docs (`# Errors`, `# Panics`, `# Safety` where applicable), and module headers start with `//!`. Note: `runvil-harness` enforces `no_doctests` (`crates/build-xtask/src/no_doctests.rs`), so doc code fences in `runvil-harness` use ` ```text `. + - In `runvil-plugin-api`, keep Rust 1.85 compatibility (no `let` chains, which require 1.88). + +3. **Git, Testable Commits, PRs, CodeRabbit, and Upstream Merge Order**: + - Stay on `master` in every repository (no topical branches; `origin` is `vinniefalco/*`, `upstream` is `cppalliance/*`). Sync `master` with `upstream/master` before starting each repo. + - Commit 1 in every touched repository adds `plan/2026-12-02-3-native-preludes.plan.md` so every commit message ends with `Plan: /plan/2026-12-02-3-native-preludes.plan.md`. + - Every commit must compile and pass `cargo fmt --all --check`, `cargo clippy --all-targets --all-features -- -D warnings`, and the repo's test / `xtask` suite before committing. + - At the end of each wave: push `master` to `origin`, open a PR to `cppalliance/:master` with `gh pr create`, monitor CI and CodeRabbit review comments, address worthwhile CodeRabbit feedback in clean testable commits (and reply/resolve noise), merge the PR to `upstream` once green, and `git fetch upstream` + `git merge --ff-only upstream/master` to record the exact merged `upstream` SHA for the next wave. + +```mermaid +flowchart TD + W1["Wave 1: plugin-api 0.10"] -->|"SHA P"| W2Std["Wave 2a: plugin-std"] + W1 -->|"SHA P"| W2Bash["Wave 2a: plugin-bashkit"] + W1 -->|"SHA P"| W2Web["Wave 2a: plugin-web"] + W1 -->|"SHA P"| W2Harness["Wave 2b: runvil-harness"] + W2Std -->|"SHA S"| W3Workshop["Wave 3a: runvil-workshop"] + W2Bash -->|"SHA B"| W3Workshop + W2Web -->|"SHA W"| W3Workshop + W2Harness -->|"SHA H"| W3Workshop + W3Workshop -->|"SHA K"| W3Runvil["Wave 3b: runvil"] +``` + +--- + +## Technical Design + +### 1. C Contract (`runvil-plugin-sys` v0.10.0) +- **Status codes & verb**: + - Fill the reserved status slots `1..3`: `RV_ERR_LUA = 1`, `RV_ERR_FATAL = 2`, `RV_ERR_TYPE = 3`. + - Fill the reserved verb slot `8`: `RV_PACK_OPEN = 8`, sent once per section VM for each declared Pack on `call->pack_run` with `RvPackOpenArgs`. + - A Pack with no native prelude answers `RV_PACK_OPEN` with `RV_ERR_UNSUPPORTED` (matching `RV_PACK_RENDER`), which the loader treats as a no-op. +- **`RvPackInfo` & `RvPackOpenArgs`**: + - Append `pub lua_prelude: RvStr` to `RvPackInfo` (empty `{NULL, 0}` when unset, capped at `RV_MAX_TOOL_TEXT = 65_536` bytes of UTF-8; size grows from 40 to 56 bytes on 64-bit). + - `RvPackOpenArgs { size: u32, reserved: u32, ctx: *mut c_void, pack_id: RvStr, env: RvValue, lua: *const RvLua, refuse: unsafe extern "C" fn(ctx: *mut c_void, reason: RvStr) -> RvStatus }`. +- **Flat 16-byte `RvValue` (zero `union` / zero `unsafe` in `runvil-plugin-sys`)**: + - `#[repr(C)] pub struct RvValue { pub kind: RvKind, pub reserved: u32, pub payload: u64 }`. + - `RvKind`: `RV_NIL = 0`, `RV_BOOLEAN = 1` (`0` or `1`), `RV_INTEGER = 2` (`payload as i64`), `RV_NUMBER = 3` (`f64::from_bits(payload)`), `RV_NULL = 4` (`json.null`), `RV_LIGHTUSERDATA = 5` (`payload as usize as *mut c_void`), `RV_STRING = 6`, `RV_TABLE = 7`, `RV_FUNCTION = 8`, `RV_USERDATA = 9`, `RV_OPAQUE = 10`. +- **Call-scoped tokens, callbacks, and `RvLua`**: + - `RvCx { pub bits: u64 }`, `RvMark { pub bits: u64 }`, `RvIter { pub bits: u64 }`. + - `RvFunction = unsafe extern "C" fn(cx: RvCx, lua: *const RvLua, data: *mut c_void, args: *const RvValue, nargs: usize) -> RvStatus`. + - `RvDrop = unsafe extern "C" fn(data: *mut c_void)`. + - `RvFunctionInfo`, `RvMethod`, `RvUserdataType` (with `user_values` up to `RV_MAX_USER_VALUES = 4`, `methods`, `index`, `newindex`, `tostring`, `eq`, `lt`, `le`, `len`, `call`, `drop`), and `RvLua` (`size`, `reserved`, and the 30 functions from `2026-10-18-mlua-c-wrapper.md`, using `RvStr` for UTF-8 names/messages/JSON and `RvBytes` for arbitrary Lua string bytes). + +### 2. Engine & Loader Architecture (`runvil-harness`) +- **Why no new crates or public facade types are needed**: + - `runvil-lua` implements the safe `mlua` operations in `crates/runvil-internal/lua/src/prelude/native.rs` (table-backed handle arena with generational slots, error states, table/view ops, deterministic iteration, functions, userdata with protected metatables, and JSON conversion) and exposes a lean `LuaHost` API to `runvil-plugin`. + - `Prelude` in `runvil-types` (or moved to `runvil-lua` and re-exported by `runvil-types`, `runvil-engine::packs::Prelude`, and `runvil-plugin`) keeps its exact existing public API (`Prelude::new`, `Prelude::pack`, `Prelude::source`) while gaining crate-internal support for an optional native opener callback and optional Lua source. + - In `crates/runvil-internal/lua/src/prelude.rs` (`install_preludes`), for each declared Pack: build `env` once, run the native opener first (if present), run the Lua source chunk second in the same `env` (if present), and run `defined_globals`, collision checks, and top-level table sealing (`read_only_proxy` for `Value::Table`, unchanged `Value::UserData` / `Value::Function`). + - In `harness-plugin-loader`: `EntryPack` implements `Pack::open` by opening an `RV_PACK_OPEN` session and calling the `PluginEntry` with `RvPackOpenArgs` pointing to the static `RvLua` vtable in `crates/harness-internal/plugin-loader/src/lua.rs`. Every userdata and function wrapper holds an `Arc` field declared **after** its native data drop guard so `(type.drop)(data)` / `(info.drop)(data)` runs during `SectionVm::teardown` (`lua_close`) before the last `Arc` can drop and close the library. + +--- + +## Wave 1: `runvil-plugin-api` v0.10.0 (3 Testable Commits -> Merged Upstream SHA `P`) + +- **Commit 1**: Add `plan/2026-12-02-3-native-preludes.plan.md`. +- **Commit 2 (`runvil-plugin-sys` v0.10.0 + `runvil_plugin.h` + `c-layout`)**: + - Update `crates/runvil-plugin-sys/src/lib.rs` (`RV_API_MINOR = 10`, status codes `1..3`, verb `RV_PACK_OPEN = 8`, `RvPackInfo.lua_prelude`, `RvValue`, `RvCx`, `RvMark`, `RvIter`, `RvFunction`, `RvDrop`, `RvFunctionInfo`, `RvMethod`, `RvUserdataType`, `RvLua`, `RvPackOpenArgs`) and bump `Cargo.toml` versions to `0.10.0`. + - Regenerate `crates/runvil-plugin-sys/include/runvil_plugin.h` with `cargo xtask header` and update `tests/c-layout/src/lib.rs`, `layout.c`, and `layout.cpp`. +- **Commit 3 (`runvil-plugin-sdk` v0.10.0 + `testing`)**: + - Add `PackInfo::lua_prelude` and `Pack::open` in `crates/runvil-plugin-sdk/src/pack.rs` and wire `RV_PACK_OPEN` in `crates/runvil-plugin-sdk/src/entry/pack.rs` and `entry/plugin.rs`. + - Add `crates/runvil-plugin-sdk/src/lua.rs` with lean, safe lifetime-bound wrappers over `RvCx` and `*const RvLua`, panic containment on all callbacks/drops, and fake Host support in `src/testing/`. + - Apply `rust-rulebook.md` to every touched file, verify MSRV `1.85`, `c-layout`, `clippy`, `nextest`/`test`, and `doc`, push to `origin`, open PR, address worthwhile CodeRabbit comments, and merge to `upstream` -> SHA `P`. + +--- + +## Wave 2: Three Plugin Repos + `runvil-harness` (Parallel PRs once `P` Merges) + +### Wave 2a: `runvil-plugin-std`, `runvil-plugin-bashkit`, `runvil-plugin-web` (2 Commits Each -> SHAs `S`, `B`, `W`) +- **Commit 1**: Add `plan/2026-12-02-3-native-preludes.plan.md`. +- **Commit 2**: Pin `runvil-plugin-sdk = "0.10.0"` at SHA `P`, verify `build-checks`, `fmt`, `clippy`, `test`, and `doc`, push to `origin`, open PRs, triage CodeRabbit, and merge to `upstream` -> SHAs `S`, `B`, `W`. + +### Wave 2b: `runvil-harness` (4 Testable Commits -> Merged Upstream SHA `H`) +- **Commit 1**: Add `plan/2026-12-02-3-native-preludes.plan.md`. +- **Commit 2 (Engine `mlua` host + hybrid `Prelude` in `runvil-lua`, `runvil-types`, `runvil-plugin`, `harness-runner`)**: + - Implement `crates/runvil-internal/lua/src/prelude/native.rs` and wire native + Lua source execution in `crates/runvil-internal/lua/src/prelude.rs`. + - Add `Pack::open` in `crates/runvil-plugin/src/pack.rs` and wire `RunPacks::snapshot` in `crates/harness-internal/runner/src/packs.rs` so declared usable Packs contribute native `open`, `info.prelude`, or both. + - Add thorough unit tests in `runvil-lua` covering arena handles, `mark`/`release_to`, error catching vs. sticky fatal errors, guarded `var`/`args`/`sys` table access, deterministic iteration, functions, userdata with `drop` on VM teardown, light userdata, and `from_json`/`to_json`. +- **Commit 3 (Pin contract `0.10.0` at `P` and wire `RV_PACK_OPEN` + `RvLua` in `harness-plugin-loader`)**: + - Pin `runvil-plugin-sys = "0.10.0"` at SHA `P` in `Cargo.toml`. + - Read `info.lua_prelude` in `crates/harness-internal/plugin-loader/src/plugin.rs` (`insert_pack`) and wire `crates/harness-internal/plugin-loader/src/lua.rs` + `pack.rs` (`RV_PACK_OPEN`, `RvLua` vtable, `Arc`-pinned function/userdata drop guards, and loader unit tests). +- **Commit 4 (`harness-test-plugin` 0.10 + end-to-end tests + `decisions/`)**: + - Update `crates/harness-internal/test-plugin/src/lib.rs` to contract `0.10` with a native prelude (installing table functions and a callable userdata whose `drop` increments an atomic counter on VM teardown) plus a `lua_prelude`, and add end-to-end tests in `crates/harness-internal/test-plugin/tests/it/`. + - Update `decisions/tools-and-packs.md` and `decisions/prompt-language.md`. + - Apply `rust-rulebook.md` across all touched files, run full verification (`nextest`, `clippy`, `fmt`, `doc`, `xtask tidy`, `xtask api --check`, `docs-claims.mjs`), push to `origin`, open PR, triage CodeRabbit, and merge to `upstream` -> SHA `H`. + +--- + +## Wave 3: `runvil-workshop` and `runvil` + +- **Wave 3a (`runvil-workshop` -> SHA `K`)**: + - Commit 1: Add `plan/2026-12-02-3-native-preludes.plan.md`. + - Commit 2: Pin `runvil-harness` (`H`), `runvil-plugin-sdk` `0.10.0` (`P`), `std-plugin` (`S`), `bashkit-plugin` (`B`), and `web-plugin` (`W`) in `Cargo.toml`. Verify all checks, push to `origin`, open PR, triage CodeRabbit, and merge to `upstream` -> SHA `K`. +- **Wave 3b (`runvil`)**: + - Commit 1: Add `plan/2026-12-02-3-native-preludes.plan.md`. + - Commit 2: Pin Workshop SHA `K` in `Cargo.toml`, verify `xtask`, push to `origin`, open PR, triage CodeRabbit, and merge to `upstream`. From 33b9e233cf1006ae32698b7b8e740d5f7628fcad Mon Sep 17 00:00:00 2001 From: Vinnie Falco Date: Wed, 2 Dec 2026 18:59:03 -0800 Subject: [PATCH 2/4] Declare RV_PACK_OPEN and RvLua in C contract 0.10.0 Bump unvil-plugin-sys and unvil_plugin.h to version 0.10.0 (RV_API_MINOR = 10) with native prelude verb RV_PACK_OPEN (8), RvPackInfo.lua_prelude, status codes RV_ERR_LUA (1), RV_ERR_FATAL (2), and RV_ERR_TYPE (3), and the handle-based RvLua API table. - Represent RvValue as a flat 16-byte #[repr(C)] struct (kind, eserved, payload) with RvKind constants RV_NIL (0) through RV_OPAQUE (10), including RV_LIGHTUSERDATA (5), so unvil-plugin-sys keeps zero unsafe and cargo xtask header emits the C header without union handling. - Add RvCx, RvMark, RvIter, RvFunctionInfo, RvMethod, RvUserdataType, RvLua, RvPackOpenArgs, RvFunction, and RvDrop, and verify every size, offset, and constant in ests/c-layout. - unvil-plugin-sdk sets an empty lua_prelude in entry/plugin.rs; PackInfo::lua_prelude, Pack::open, and the safe LuaPrelude wrapper follow in the next commit. Plan: /plan/2026-12-02-3-native-preludes.plan.md --- Cargo.lock | 4 +- crates/runvil-plugin-sdk/Cargo.toml | 2 +- crates/runvil-plugin-sdk/src/entry/plugin.rs | 6 +- .../runvil-plugin-sdk/src/testing/fixture.rs | 4 + crates/runvil-plugin-sys/Cargo.toml | 2 +- .../runvil-plugin-sys/include/runvil_plugin.h | 637 ++++++++++++++++- crates/runvil-plugin-sys/src/lib.rs | 657 +++++++++++++++++- tests/c-layout/layout.c | 96 +++ tests/c-layout/layout.cpp | 8 + tests/c-layout/src/lib.rs | 142 +++- 10 files changed, 1478 insertions(+), 80 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5bf84fd..e31b582 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -188,7 +188,7 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "runvil-plugin-sdk" -version = "0.9.0" +version = "0.10.0" dependencies = [ "runvil-plugin-sys", "serde", @@ -197,7 +197,7 @@ dependencies = [ [[package]] name = "runvil-plugin-sys" -version = "0.9.0" +version = "0.10.0" [[package]] name = "rustix" diff --git a/crates/runvil-plugin-sdk/Cargo.toml b/crates/runvil-plugin-sdk/Cargo.toml index e0e01c0..16e1370 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.9.0" +version = "0.10.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/plugin.rs b/crates/runvil-plugin-sdk/src/entry/plugin.rs index 2ecc2e0..b31079d 100644 --- a/crates/runvil-plugin-sdk/src/entry/plugin.rs +++ b/crates/runvil-plugin-sdk/src/entry/plugin.rs @@ -6,7 +6,7 @@ use std::panic; use runvil_plugin_sys::{ RV_API_MAJOR, RV_API_MINOR, RV_ERR_MISUSE, RV_ERR_UNSUPPORTED, RV_OK, RvCall, RvHost, - RvLoadArgs, RvPackInfo, RvPluginInfo, RvStatus, + RvLoadArgs, RvPackInfo, RvPluginInfo, RvStatus, RvStr, }; use super::{args, contain, panic_message, refuse, rv_str, size_field}; @@ -93,6 +93,10 @@ unsafe fn describe(args: &RvLoadArgs) -> RvStatus { reserved: 0, name: rv_str(pack.name), description: rv_str(pack.description), + lua_prelude: RvStr { + ptr: core::ptr::null(), + len: 0, + }, }; // SAFETY: as above. let status = unsafe { (args.insert_pack)(args.ctx, &raw const info) }; diff --git a/crates/runvil-plugin-sdk/src/testing/fixture.rs b/crates/runvil-plugin-sdk/src/testing/fixture.rs index 176311a..94ff765 100644 --- a/crates/runvil-plugin-sdk/src/testing/fixture.rs +++ b/crates/runvil-plugin-sdk/src/testing/fixture.rs @@ -236,6 +236,10 @@ unsafe fn load_verb(call: *mut RvCall, args: &RvLoadArgs, breach: Breach) -> RvS "A fixture Pack", "two\nlines", ), + lua_prelude: RvStr { + ptr: ptr::null(), + len: 0, + }, }; (args.insert_pack)(args.ctx, &raw const pack); if breach == Breach::PackTwice { diff --git a/crates/runvil-plugin-sys/Cargo.toml b/crates/runvil-plugin-sys/Cargo.toml index 57420f3..5c937b6 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.9.0" +version = "0.10.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 beca400..4088e75 100644 --- a/crates/runvil-plugin-sys/include/runvil_plugin.h +++ b/crates/runvil-plugin-sys/include/runvil_plugin.h @@ -58,6 +58,10 @@ * 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`. + * - `RV_PACK_OPEN` (8), with an `RvPackOpenArgs`: runs one Pack + * instance's native prelude in a section VM, setting globals on the + * prelude environment `env` through the `RvLua` table. A Pack with no + * native prelude answers `RV_ERR_UNSUPPORTED`. * * 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,10 +69,19 @@ * * # Packs * - * - A Plugin inserts each of its Packs once, while it loads. The Host + * - A Plugin inserts each of its Packs once, while it loads, with an + * `RvPackInfo` that names the Pack, describes it, and optionally + * supplies `lua_prelude`, Lua source run in each section VM of a prompt + * that declares the Pack. The Host * 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. + * - For each section VM of a prompt that declares a Pack under `uses:`, + * the Host sends `RV_PACK_OPEN` to the run's instance of the Pack, + * passing the Pack's prelude environment `env` and the `RvLua` table. + * When the Pack also has a `lua_prelude`, that Lua chunk runs after + * `RV_PACK_OPEN` in the same environment. Every field set on `env` + * becomes a global in the section VM once both finish. * - 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 @@ -310,23 +323,27 @@ * - A waker belongs to the Host, with what its `ctx` points at. The * Plugin copies the `RvWaker` it keeps and frees nothing of it. * - * # Reserved numbers - * - * 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_LUA` (1) means Lua raised an error, which the call now + * holds. `clear_error` in `RvLua` catches it; returning the status + * from a Pack callback raises it unchanged. + * - `RV_ERR_FATAL` (2) means the VM reached its memory limit or the + * run was canceled. It cannot be cleared, every later `RvLua` call + * with the same context returns it, and the Engine raises it when the + * Pack callback returns. + * - `RV_ERR_TYPE` (3) means a value had the wrong `RvKind` for an + * `RvLua` call; nothing was raised in Lua. * - `RV_ERR_MISUSE` (4) means the caller broke the contract. * - `RV_ERR_REFUSED` (5) means the Plugin declined: to load, to make a - * Pack instance, or to render a Pack's tools. + * Pack instance, to render a Pack's tools, or to open a Pack's native + * prelude. * - `RV_ERR_UNSUPPORTED` (6) means the Plugin cannot answer the call: it - * 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. + * does not know the verb, does not render for `RV_PACK_RENDER`, has + * no native prelude for `RV_PACK_OPEN`, 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. @@ -376,6 +393,15 @@ typedef struct RvPackNewArgs RvPackNewArgs; typedef struct RvPackRenderArgs RvPackRenderArgs; typedef struct RvWaker RvWaker; typedef struct RvToolCallArgs RvToolCallArgs; +typedef struct RvValue RvValue; +typedef struct RvCx RvCx; +typedef struct RvMark RvMark; +typedef struct RvIter RvIter; +typedef struct RvFunctionInfo RvFunctionInfo; +typedef struct RvMethod RvMethod; +typedef struct RvUserdataType RvUserdataType; +typedef struct RvLua RvLua; +typedef struct RvPackOpenArgs RvPackOpenArgs; typedef struct RvCall RvCall; /** @@ -386,7 +412,7 @@ typedef struct RvCall RvCall; /** * The contract's minor version, which `RvHost` reports. */ -#define RV_API_MINOR 9 +#define RV_API_MINOR 10 /** * The most bytes in a name segment, a version, or a wire name. @@ -404,7 +430,7 @@ typedef struct RvCall RvCall; #define RV_MAX_PATH 4096 /** - * The most bytes in a tool's description. + * The most bytes in a tool's description, or in a Pack's `lua_prelude`. */ #define RV_MAX_TOOL_TEXT 65536 @@ -423,6 +449,21 @@ typedef struct RvCall RvCall; */ #define RV_MAX_WRITE 16777216 +/** + * The most `RvValue` items one `RvLua` call passes or returns. + */ +#define RV_MAX_VALUES 255 + +/** + * The most Lua values one userdata instance holds. + */ +#define RV_MAX_USER_VALUES 4 + +/** + * `new_table` flag: mark the new table as a list, as `json.array()` does. + */ +#define RV_TABLE_LIST 1 + /** * What every function in the contract returns, except `wake`, which * returns nothing, and the `status` of an `RvFileAnswer`: zero for @@ -460,6 +501,12 @@ typedef uint32_t RvFileErrorKind; */ typedef uint32_t RvCaller; +/** + * The kind of a Lua value in an `RvValue`. A fixed-width integer, as + * `RvVerb` is. + */ +typedef uint32_t RvKind; + /** * A UTF-8 string that is not NUL-terminated. */ @@ -636,6 +683,12 @@ struct RvPackInfo { * with no control characters. It may be empty. */ struct RvStr description; + /** + * Optional Lua source run after `RV_PACK_OPEN` in the Pack's + * prelude environment, at most `RV_MAX_TOOL_TEXT` bytes of UTF-8. + * Empty (`{NULL, 0}`) when the Pack has no Lua prelude. + */ + struct RvStr lua_prelude; }; /** @@ -990,6 +1043,463 @@ struct RvToolCallArgs { struct RvStr model; }; +/** + * One Lua value. Scalars (`nil`, booleans, integers, floats, `json.null`, + * and light userdata) travel in `payload`. Strings, tables, functions, + * userdata, and opaque values are handles in `payload` that only the + * Engine creates, valid until the call returns or `release_to` releases + * them. + */ +struct RvValue { + /** + * One of the `RV_` kind constants. + */ + RvKind kind; + /** + * Zero. + */ + uint32_t reserved; + /** + * The scalar bits (`0`/`1` for `RV_BOOLEAN`, `i64 as u64` for + * `RV_INTEGER`, `f64::to_bits` for `RV_NUMBER`, pointer address + * for `RV_LIGHTUSERDATA`, `0` for `RV_NIL` and `RV_NULL`), or + * the Engine-issued handle for `RV_STRING` through `RV_OPAQUE`. + */ + uint64_t payload; +}; + +/** + * One active Pack Lua call: one `RV_PACK_OPEN` call, or one call of an + * `RvFunction`. Valid only while that call runs, on its own thread, and + * only as the innermost active call on that thread. + */ +struct RvCx { + /** + * The Engine's call token. + */ + uint64_t bits; +}; + +/** + * A position in a call's handle arena, returned by `mark` and passed to + * `release_to`. + */ +struct RvMark { + /** + * The Engine's arena mark token. + */ + uint64_t bits; +}; + +/** + * A table walk owned by one call, returned by `iter_begin` and stepped by + * `iter_next`. + */ +struct RvIter { + /** + * The Engine's iterator token. + */ + uint64_t bits; +}; + +/** + * One method of an `RvUserdataType`, called from Lua as `u:name(...)`. + */ +struct RvMethod { + /** + * The method's name, at most `RV_MAX_NAME` bytes of UTF-8. + */ + struct RvStr name; + /** + * The callback; `data` is the instance's data and `args[0]` is the + * instance. + */ + RvStatus (*call)(struct RvCx cx, + const struct RvLua *lua, + void *data, + const struct RvValue *args, + size_t nargs); +}; + +/** + * Describes a userdata type passed to `new_userdata`. The `RvUserdataType` + * struct and its `methods` slice must stay valid for the life of the + * Plugin. The Engine builds one protected metatable per type and VM: + * `getmetatable` returns the type `name`, `__gc` calls `drop_fn`, and the + * Pack never sees the metatable. Before every callback below, the Engine + * checks that the receiver operand is an instance of this exact type and + * raises otherwise, so `data` always belongs to this type. + */ +struct RvUserdataType { + /** + * The size of this struct in bytes: `sizeof(RvUserdataType)`. + */ + uint32_t size; + /** + * How many Lua values each instance holds: 0 to + * `RV_MAX_USER_VALUES`. + */ + uint32_t user_values; + /** + * The type's name, such as `url.Url`, at most `RV_MAX_NAME` bytes + * of UTF-8. + */ + struct RvStr name; + /** + * The first of `method_count` methods, or NULL when `method_count` is + * zero. + */ + const struct RvMethod *methods; + /** + * How many methods `methods` points at. + */ + size_t method_count; + /** + * Optional `__index` fallback when `u.key` is not among `methods`; + * receives `(u, key)`. + */ + RvStatus (*index)(struct RvCx cx, + const struct RvLua *lua, + void *data, + const struct RvValue *args, + size_t nargs); + /** + * Optional `__newindex` for `u.key = v`; receives `(u, key, v)`. + * When `None`, assigning a field raises. + */ + RvStatus (*newindex)(struct RvCx cx, + const struct RvLua *lua, + void *data, + const struct RvValue *args, + size_t nargs); + /** + * Optional `__tostring`. When `None`, `tostring(u)` returns the type + * `name`, never a memory address. + */ + RvStatus (*tostring)(struct RvCx cx, + const struct RvLua *lua, + void *data, + const struct RvValue *args, + size_t nargs); + /** + * Optional `__eq` for `u == v` when both operands are userdata of + * this type. When `None`, userdata compare by identity. + */ + RvStatus (*eq)(struct RvCx cx, + const struct RvLua *lua, + void *data, + const struct RvValue *args, + size_t nargs); + /** + * Optional `__lt` for `u < v`. + */ + RvStatus (*lt)(struct RvCx cx, + const struct RvLua *lua, + void *data, + const struct RvValue *args, + size_t nargs); + /** + * Optional `__le` for `u <= v`. + */ + RvStatus (*le)(struct RvCx cx, + const struct RvLua *lua, + void *data, + const struct RvValue *args, + size_t nargs); + /** + * Optional `__len` for `#u`. + */ + RvStatus (*len)(struct RvCx cx, + const struct RvLua *lua, + void *data, + const struct RvValue *args, + size_t nargs); + /** + * Optional `__call` for `u(...)`; `args[0]` is `u`. + */ + RvStatus (*call)(struct RvCx cx, + const struct RvLua *lua, + void *data, + const struct RvValue *args, + size_t nargs); + /** + * Frees an instance's `data` when Lua collects it or the VM closes. + */ + void (*drop_fn)(void *data); +}; + +/** + * The Lua API table the Host lends to `RV_PACK_OPEN` and to every + * `RvFunction`. The Engine implements every entry with its own `mlua`. + */ +struct RvLua { + /** + * The size of this struct in bytes: `sizeof(RvLua)`. + */ + uint32_t size; + /** + * Zero. + */ + uint32_t reserved; + /** + * Holds an author error with `message` (UTF-8, at most + * `RV_MAX_LINE` bytes) and returns `RV_ERR_LUA`. + */ + RvStatus (*raise)(struct RvCx cx, struct RvStr message); + /** + * Reads the held error's message into `out`, valid until + * `clear_error` or the end of the call. + */ + RvStatus (*error_message)(struct RvCx cx, struct RvStr *out); + /** + * Drops a held `RV_ERR_LUA`, `RV_ERR_TYPE`, or `RV_ERR_MISUSE`. + * Returns `RV_ERR_FATAL` when a fatal error is held. + */ + RvStatus (*clear_error)(struct RvCx cx); + /** + * Returns `RV_ERR_FATAL` once the run is canceled. + */ + RvStatus (*check_cancel)(struct RvCx cx); + /** + * Records the current position in the call's handle arena. + */ + RvStatus (*mark)(struct RvCx cx, struct RvMark *out); + /** + * Releases every handle created after `mark`. A released handle is + * refused afterward, even if its slot is reused. + */ + RvStatus (*release_to)(struct RvCx cx, struct RvMark mark); + /** + * Copies `bytes` into a new Lua string handle. + */ + RvStatus (*new_string)(struct RvCx cx, struct RvBytes bytes, struct RvValue *out); + /** + * Borrows a Lua string's bytes, valid while `string` is. `RV_STRING` + * only: numbers are never coerced. + */ + RvStatus (*string_bytes)(struct RvCx cx, struct RvValue string, struct RvBytes *out); + /** + * Creates a new Lua table; `flags` may hold `RV_TABLE_LIST`. + */ + RvStatus (*new_table)(struct RvCx cx, + uint32_t list_hint, + uint32_t field_hint, + uint32_t flags, + struct RvValue *out); + /** + * Marks `table` as a list with `json.array(t)`'s rules: a table with + * any other metatable is refused. + */ + RvStatus (*mark_list)(struct RvCx cx, struct RvValue table); + /** + * Writes `1` to `out` when `value` is a table with the list marker, + * and `0` otherwise. + */ + RvStatus (*is_list)(struct RvCx cx, struct RvValue value, uint32_t *out); + /** + * `object[key]`, running `__index` as Lua does. `object` is a table + * or userdata. + */ + RvStatus (*get)(struct RvCx cx, struct RvValue object, struct RvValue key, struct RvValue *out); + /** + * `object[name]`, running `__index` as Lua does. + */ + RvStatus (*get_field)(struct RvCx cx, + struct RvValue object, + struct RvStr name, + struct RvValue *out); + /** + * `table[key]` without metamethods. + */ + RvStatus (*raw_get)(struct RvCx cx, struct RvValue table, struct RvValue key, struct RvValue *out); + /** + * `object[key] = value`, running `__newindex` as Lua does, so `var` + * validation and every read-only refusal apply. + */ + RvStatus (*set)(struct RvCx cx, struct RvValue object, struct RvValue key, struct RvValue value); + /** + * `object[name] = value`, running `__newindex` as Lua does. + */ + RvStatus (*set_field)(struct RvCx cx, + struct RvValue object, + struct RvStr name, + struct RvValue value); + /** + * A table's border length, without `__len`, unsealing table-backed + * Engine views. + */ + RvStatus (*raw_len)(struct RvCx cx, struct RvValue table, int64_t *out); + /** + * `setmetatable(table, metatable)` with Lua's protection rules, + * refusing any metatable holding `__gc`, `__mode`, or `__close`. + */ + RvStatus (*set_metatable)(struct RvCx cx, struct RvValue table, struct RvValue metatable); + /** + * `rawequal(a, b)`: identity for handles, value for scalars. + */ + RvStatus (*raw_equal)(struct RvCx cx, struct RvValue a, struct RvValue b, uint32_t *out); + /** + * Captures a table's keys once in the Engine's deterministic `pairs` + * order (unsealing table-backed Engine views). + */ + RvStatus (*iter_begin)(struct RvCx cx, struct RvValue table, struct RvIter *out); + /** + * Advances `iter` to the next live entry. At the end, writes `1` to + * `done` and `nil` to `key` and `value`. + */ + RvStatus (*iter_next)(struct RvCx cx, + struct RvIter iter, + struct RvValue *key, + struct RvValue *value, + uint32_t *done); + /** + * Creates a Lua function backed by `info->call`. Ownership of `data` + * passes to the Engine on every path (freed via `info->drop_fn` on + * failure or when Lua collects the function). + */ + RvStatus (*new_function)(struct RvCx cx, + const struct RvFunctionInfo *info, + void *data, + struct RvValue *out); + /** + * Calls `callee(args...)`, keeping `nresults` results and filling + * missing ones with `nil`. A yield inside fails as `RV_ERR_LUA`. + */ + RvStatus (*call)(struct RvCx cx, + struct RvValue callee, + const struct RvValue *args, + size_t nargs, + struct RvValue *results, + size_t nresults); + /** + * Sets the current `RvFunction`'s return values; a second call + * replaces the first. Refused inside `RV_PACK_OPEN`. + */ + RvStatus (*return_values)(struct RvCx cx, const struct RvValue *values, size_t count); + /** + * Creates a new userdata instance of `ty`. Ownership of `data` passes + * to the Engine on every path and is freed with `ty->drop_fn`. + */ + RvStatus (*new_userdata)(struct RvCx cx, + const struct RvUserdataType *ty, + void *data, + struct RvValue *out); + /** + * Reads the `data` pointer of an instance of `ty`, or returns + * `RV_ERR_TYPE` for any other value. + */ + RvStatus (*userdata_data)(struct RvCx cx, + struct RvValue value, + const struct RvUserdataType *ty, + void **out); + /** + * Reads user value slot `index` (below `ty->user_values`) on an + * instance of `ty`. + */ + RvStatus (*get_user_value)(struct RvCx cx, + struct RvValue value, + const struct RvUserdataType *ty, + uint32_t index, + struct RvValue *out); + /** + * Writes `item` to user value slot `index` (below `ty->user_values`) + * on an instance of `ty`. + */ + RvStatus (*set_user_value)(struct RvCx cx, + struct RvValue value, + const struct RvUserdataType *ty, + uint32_t index, + struct RvValue item); + /** + * Parses `json` as `json.decode` does (lists marked, `null` as + * `json.null`, up to 8,388,608 bytes and 127 levels), prefixing + * errors with `who`. + */ + RvStatus (*from_json)(struct RvCx cx, struct RvStr who, struct RvStr json, struct RvValue *out); + /** + * Encodes `value` as `json.encode` does, reading through Engine views, + * and returns a Lua string in `out`, prefixing errors with `who`. + */ + RvStatus (*to_json)(struct RvCx cx, struct RvStr who, struct RvValue value, struct RvValue *out); +}; + +/** + * Describes a Pack function passed to `new_function`. The Engine copies + * the name, so the struct need not outlive `new_function`. + */ +struct RvFunctionInfo { + /** + * The size of this struct in bytes: `sizeof(RvFunctionInfo)`. + */ + uint32_t size; + /** + * Zero. + */ + uint32_t reserved; + /** + * The function's name, such as `url.parse`, for error messages: at + * most `RV_MAX_LINE` bytes of UTF-8. + */ + struct RvStr name; + /** + * The callback invoked when Lua calls the function. + */ + RvStatus (*call)(struct RvCx cx, + const struct RvLua *lua, + void *data, + const struct RvValue *args, + size_t nargs); + /** + * Optional destructor for `data`; `None` (NULL in C) when `data` + * needs no freeing. + */ + void (*drop_fn)(void *data); +}; + +/** + * The arguments of `RV_PACK_OPEN`: the Pack's id, its prelude + * environment table `env`, the `RvLua` call context and function table, + * and `refuse`. + */ +struct RvPackOpenArgs { + /** + * The size of this struct in bytes: `sizeof(RvPackOpenArgs)`. + */ + uint32_t size; + /** + * Zero. + */ + uint32_t reserved; + /** + * The Host's context for `refuse`. The Plugin never reads through it. + */ + void *ctx; + /** + * The `RvLua` context for this `open` call. + */ + struct RvCx lua_cx; + /** + * The Pack's id, the second segment of its name, such as `url`. + */ + struct RvStr pack_id; + /** + * The Pack's prelude environment table (`RV_TABLE`): every field set + * on it becomes a global in the section VM once `open` and any + * `lua_prelude` return. + */ + struct RvValue env; + /** + * The Engine's Lua API table, valid for the life of the process. + */ + const struct RvLua *lua; + /** + * Declines to open the prelude, 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 section entry fails. + */ + RvStatus (*refuse)(void *ctx, struct RvStr reason); +}; + /** * One call into a Plugin's entry point. */ @@ -1014,15 +1524,16 @@ 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_PACK_RENDER`, `RV_TOOL_CALL`, and `RV_TOOL_CANCEL`, and - * NULL otherwise. + * `RV_PACK_RENDER`, `RV_PACK_OPEN`, `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 `RvPackRenderArgs` - * for `RV_PACK_RENDER`, an `RvToolCallArgs` for `RV_TOOL_CALL`, - * and NULL for every other verb. + * for `RV_PACK_RENDER`, an `RvPackOpenArgs` for `RV_PACK_OPEN`, + * an `RvToolCallArgs` for `RV_TOOL_CALL`, and NULL for every other + * verb. */ const void *args; /** @@ -1038,21 +1549,41 @@ struct RvCall { */ #define RV_OK 0 +/** + * Lua raised an error, which the call now holds. `clear_error` in + * `RvLua` catches it; returning the status from a Pack callback raises + * it unchanged. + */ +#define RV_ERR_LUA 1 + +/** + * The VM reached its memory limit or the run was canceled. It cannot be + * cleared, every later `RvLua` call with the same context returns it, + * and the Engine raises it when the Pack callback returns. + */ +#define RV_ERR_FATAL 2 + +/** + * A value had the wrong `RvKind` for an `RvLua` call; nothing was + * raised in Lua. + */ +#define RV_ERR_TYPE 3 + /** * The caller broke the contract. */ #define RV_ERR_MISUSE 4 /** - * The Plugin declined to load, to make a Pack instance, or to render a - * Pack's tools; `refuse` returns it. + * The Plugin declined to load, to make a Pack instance, to render a + * Pack's tools, or to open a Pack's native prelude; `refuse` returns it. */ #define RV_ERR_REFUSED 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 - * expects. + * The Plugin cannot answer the call: it does not know the verb, it has + * no native prelude for `RV_PACK_OPEN`, it was not built for the Host's + * version, or a struct is shorter than it expects. */ #define RV_ERR_UNSUPPORTED 6 @@ -1108,6 +1639,11 @@ struct RvCall { */ #define RV_PACK_RENDER 7 +/** + * Run a Pack instance's native prelude in a section VM. + */ +#define RV_PACK_OPEN 8 + /** * 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 @@ -1222,6 +1758,61 @@ struct RvCall { */ #define RV_CALLER_SCRIPT 1 +/** + * `nil`. + */ +#define RV_NIL 0 + +/** + * A boolean: `0` for `false` and `1` for `true` in `payload`. + */ +#define RV_BOOLEAN 1 + +/** + * A 64-bit signed integer (`payload as i64`). + */ +#define RV_INTEGER 2 + +/** + * A 64-bit IEEE-754 float (`f64::from_bits(payload)`). + */ +#define RV_NUMBER 3 + +/** + * `json.null`. + */ +#define RV_NULL 4 + +/** + * A light userdata pointer (`payload as usize as *mut c_void`). + */ +#define RV_LIGHTUSERDATA 5 + +/** + * A Lua string handle. + */ +#define RV_STRING 6 + +/** + * A Lua table handle. + */ +#define RV_TABLE 7 + +/** + * A Lua function handle. + */ +#define RV_FUNCTION 8 + +/** + * A Lua userdata handle. + */ +#define RV_USERDATA 9 + +/** + * A coroutine or any other Lua value handle: pass it on, never inspect it. + */ +#define RV_OPAQUE 10 + #ifdef __cplusplus extern "C" { #endif diff --git a/crates/runvil-plugin-sys/src/lib.rs b/crates/runvil-plugin-sys/src/lib.rs index a870d51..cd8b429 100644 --- a/crates/runvil-plugin-sys/src/lib.rs +++ b/crates/runvil-plugin-sys/src/lib.rs @@ -53,6 +53,10 @@ //! 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`. +//! - [`RV_PACK_OPEN`] (8), with an [`RvPackOpenArgs`]: runs one Pack +//! instance's native prelude in a section VM, setting globals on the +//! prelude environment `env` through the [`RvLua`] table. A Pack with no +//! native prelude answers [`RV_ERR_UNSUPPORTED`]. //! //! 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,10 +64,19 @@ //! //! # Packs //! -//! - A Plugin inserts each of its Packs once, while it loads. The Host +//! - A Plugin inserts each of its Packs once, while it loads, with an +//! [`RvPackInfo`] that names the Pack, describes it, and optionally +//! supplies `lua_prelude`, Lua source run in each section VM of a prompt +//! that declares the Pack. The Host //! 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. +//! - For each section VM of a prompt that declares a Pack under `uses:`, +//! the Host sends [`RV_PACK_OPEN`] to the run's instance of the Pack, +//! passing the Pack's prelude environment `env` and the [`RvLua`] table. +//! When the Pack also has a `lua_prelude`, that Lua chunk runs after +//! [`RV_PACK_OPEN`] in the same environment. Every field set on `env` +//! becomes a global in the section VM once both finish. //! - 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 @@ -305,23 +318,27 @@ //! - A waker belongs to the Host, with what its `ctx` points at. The //! Plugin copies the [`RvWaker`] it keeps and frees nothing of it. //! -//! # Reserved numbers -//! -//! 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_LUA`] (1) means Lua raised an error, which the call now +//! holds. `clear_error` in [`RvLua`] catches it; returning the status +//! from a Pack callback raises it unchanged. +//! - [`RV_ERR_FATAL`] (2) means the VM reached its memory limit or the +//! run was canceled. It cannot be cleared, every later [`RvLua`] call +//! with the same context returns it, and the Engine raises it when the +//! Pack callback returns. +//! - [`RV_ERR_TYPE`] (3) means a value had the wrong [`RvKind`] for an +//! [`RvLua`] call; nothing was raised in Lua. //! - [`RV_ERR_MISUSE`] (4) means the caller broke the contract. //! - [`RV_ERR_REFUSED`] (5) means the Plugin declined: to load, to make a -//! Pack instance, or to render a Pack's tools. +//! Pack instance, to render a Pack's tools, or to open a Pack's native +//! prelude. //! - [`RV_ERR_UNSUPPORTED`] (6) means the Plugin cannot answer the call: it -//! 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. +//! does not know the verb, does not render for [`RV_PACK_RENDER`], has +//! no native prelude for [`RV_PACK_OPEN`], 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. @@ -371,14 +388,25 @@ use core::ffi::{c_char, c_void}; pub type RvStatus = u32; /// Success. pub const RV_OK: RvStatus = 0; +/// Lua raised an error, which the call now holds. `clear_error` in +/// [`RvLua`] catches it; returning the status from a Pack callback raises +/// it unchanged. +pub const RV_ERR_LUA: RvStatus = 1; +/// The VM reached its memory limit or the run was canceled. It cannot be +/// cleared, every later [`RvLua`] call with the same context returns it, +/// and the Engine raises it when the Pack callback returns. +pub const RV_ERR_FATAL: RvStatus = 2; +/// A value had the wrong [`RvKind`] for an [`RvLua`] call; nothing was +/// raised in Lua. +pub const RV_ERR_TYPE: RvStatus = 3; /// The caller broke the contract. pub const RV_ERR_MISUSE: RvStatus = 4; -/// The Plugin declined to load, to make a Pack instance, or to render a -/// Pack's tools; `refuse` returns it. +/// The Plugin declined to load, to make a Pack instance, to render a +/// Pack's tools, or to open a Pack's native prelude; `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 -/// expects. +/// The Plugin cannot answer the call: it does not know the verb, it has +/// no native prelude for [`RV_PACK_OPEN`], it was not built for the Host's +/// version, or a struct is shorter than it expects. pub const RV_ERR_UNSUPPORTED: RvStatus = 6; /// The tool call is parked. The Host sends its next step after the /// Plugin wakes the call, or, when the step made a file request, when @@ -409,6 +437,8 @@ 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; +/// Run a Pack instance's native prelude in a section VM. +pub const RV_PACK_OPEN: RvVerb = 8; /// How a tool call ended, in an [`RvToolResult`]. A fixed-width integer, /// as [`RvVerb`] is. @@ -477,10 +507,36 @@ 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 kind of a Lua value in an [`RvValue`]. A fixed-width integer, as +/// [`RvVerb`] is. +pub type RvKind = u32; +/// `nil`. +pub const RV_NIL: RvKind = 0; +/// A boolean: `0` for `false` and `1` for `true` in `payload`. +pub const RV_BOOLEAN: RvKind = 1; +/// A 64-bit signed integer (`payload as i64`). +pub const RV_INTEGER: RvKind = 2; +/// A 64-bit IEEE-754 float (`f64::from_bits(payload)`). +pub const RV_NUMBER: RvKind = 3; +/// `json.null`. +pub const RV_NULL: RvKind = 4; +/// A light userdata pointer (`payload as usize as *mut c_void`). +pub const RV_LIGHTUSERDATA: RvKind = 5; +/// A Lua string handle. +pub const RV_STRING: RvKind = 6; +/// A Lua table handle. +pub const RV_TABLE: RvKind = 7; +/// A Lua function handle. +pub const RV_FUNCTION: RvKind = 8; +/// A Lua userdata handle. +pub const RV_USERDATA: RvKind = 9; +/// A coroutine or any other Lua value handle: pass it on, never inspect it. +pub const RV_OPAQUE: RvKind = 10; + /// 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 = 9; +pub const RV_API_MINOR: u32 = 10; /// The most bytes in a name segment, a version, or a wire name. pub const RV_MAX_NAME: usize = 64; @@ -488,7 +544,7 @@ pub const RV_MAX_NAME: usize = 64; pub const RV_MAX_LINE: usize = 1024; /// The most bytes in a path a file function takes. pub const RV_MAX_PATH: usize = 4096; -/// The most bytes in a tool's description. +/// The most bytes in a tool's description, or in a Pack's `lua_prelude`. pub const RV_MAX_TOOL_TEXT: usize = 65536; /// The most bytes in the JSON text of an [`RvToolInfo`]. pub const RV_MAX_TOOL_JSON: usize = 262_144; @@ -496,6 +552,12 @@ pub const RV_MAX_TOOL_JSON: usize = 262_144; pub const RV_MAX_RESULT: usize = 16_777_216; /// The most bytes `file_write` or `file_append` takes in one request. pub const RV_MAX_WRITE: usize = 16_777_216; +/// The most [`RvValue`] items one [`RvLua`] call passes or returns. +pub const RV_MAX_VALUES: usize = 255; +/// The most Lua values one userdata instance holds. +pub const RV_MAX_USER_VALUES: u32 = 4; +/// `new_table` flag: mark the new table as a list, as `json.array()` does. +pub const RV_TABLE_LIST: u32 = 1; /// A UTF-8 string that is not NUL-terminated. #[repr(C)] @@ -617,6 +679,10 @@ pub struct RvPackInfo { /// One line saying what the Pack offers: at most [`RV_MAX_LINE`] bytes /// with no control characters. It may be empty. pub description: RvStr, + /// Optional Lua source run after [`RV_PACK_OPEN`] in the Pack's + /// prelude environment, at most [`RV_MAX_TOOL_TEXT`] bytes of UTF-8. + /// Empty (`{NULL, 0}`) when the Pack has no Lua prelude. + pub lua_prelude: RvStr, } /// What a Pack instance tells `add_tool` about one of its tools, and what @@ -867,6 +933,408 @@ pub struct RvToolCallArgs { pub model: RvStr, } +/// One Lua value. Scalars (`nil`, booleans, integers, floats, `json.null`, +/// and light userdata) travel in `payload`. Strings, tables, functions, +/// userdata, and opaque values are handles in `payload` that only the +/// Engine creates, valid until the call returns or `release_to` releases +/// them. +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RvValue { + /// One of the `RV_` kind constants. + pub kind: RvKind, + /// Zero. + pub reserved: u32, + /// The scalar bits (`0`/`1` for [`RV_BOOLEAN`], `i64 as u64` for + /// [`RV_INTEGER`], `f64::to_bits` for [`RV_NUMBER`], pointer address + /// for [`RV_LIGHTUSERDATA`], `0` for [`RV_NIL`] and [`RV_NULL`]), or + /// the Engine-issued handle for [`RV_STRING`] through [`RV_OPAQUE`]. + pub payload: u64, +} + +/// One active Pack Lua call: one [`RV_PACK_OPEN`] call, or one call of an +/// [`RvFunction`]. Valid only while that call runs, on its own thread, and +/// only as the innermost active call on that thread. +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RvCx { + /// The Engine's call token. + pub bits: u64, +} + +/// A position in a call's handle arena, returned by `mark` and passed to +/// `release_to`. +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RvMark { + /// The Engine's arena mark token. + pub bits: u64, +} + +/// A table walk owned by one call, returned by `iter_begin` and stepped by +/// `iter_next`. +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RvIter { + /// The Engine's iterator token. + pub bits: u64, +} + +/// Describes a Pack function passed to `new_function`. The Engine copies +/// the name, so the struct need not outlive `new_function`. +#[repr(C)] +#[derive(Debug)] +pub struct RvFunctionInfo { + /// The size of this struct in bytes: `sizeof(RvFunctionInfo)`. + pub size: u32, + /// Zero. + pub reserved: u32, + /// The function's name, such as `url.parse`, for error messages: at + /// most [`RV_MAX_LINE`] bytes of UTF-8. + pub name: RvStr, + /// The callback invoked when Lua calls the function. + pub call: unsafe extern "C" fn( + cx: RvCx, + lua: *const RvLua, + data: *mut c_void, + args: *const RvValue, + nargs: usize, + ) -> RvStatus, + /// Optional destructor for `data`; `None` (NULL in C) when `data` + /// needs no freeing. + pub drop_fn: Option, +} + +/// One method of an [`RvUserdataType`], called from Lua as `u:name(...)`. +#[repr(C)] +#[derive(Debug)] +pub struct RvMethod { + /// The method's name, at most [`RV_MAX_NAME`] bytes of UTF-8. + pub name: RvStr, + /// The callback; `data` is the instance's data and `args[0]` is the + /// instance. + pub call: unsafe extern "C" fn( + cx: RvCx, + lua: *const RvLua, + data: *mut c_void, + args: *const RvValue, + nargs: usize, + ) -> RvStatus, +} + +/// Describes a userdata type passed to `new_userdata`. The [`RvUserdataType`] +/// struct and its `methods` slice must stay valid for the life of the +/// Plugin. The Engine builds one protected metatable per type and VM: +/// `getmetatable` returns the type `name`, `__gc` calls `drop_fn`, and the +/// Pack never sees the metatable. Before every callback below, the Engine +/// checks that the receiver operand is an instance of this exact type and +/// raises otherwise, so `data` always belongs to this type. +#[repr(C)] +#[derive(Debug)] +pub struct RvUserdataType { + /// The size of this struct in bytes: `sizeof(RvUserdataType)`. + pub size: u32, + /// How many Lua values each instance holds: 0 to + /// [`RV_MAX_USER_VALUES`]. + pub user_values: u32, + /// The type's name, such as `url.Url`, at most [`RV_MAX_NAME`] bytes + /// of UTF-8. + pub name: RvStr, + /// The first of `method_count` methods, or NULL when `method_count` is + /// zero. + pub methods: *const RvMethod, + /// How many methods `methods` points at. + pub method_count: usize, + /// Optional `__index` fallback when `u.key` is not among `methods`; + /// receives `(u, key)`. + pub index: Option< + unsafe extern "C" fn( + cx: RvCx, + lua: *const RvLua, + data: *mut c_void, + args: *const RvValue, + nargs: usize, + ) -> RvStatus, + >, + /// Optional `__newindex` for `u.key = v`; receives `(u, key, v)`. + /// When `None`, assigning a field raises. + pub newindex: Option< + unsafe extern "C" fn( + cx: RvCx, + lua: *const RvLua, + data: *mut c_void, + args: *const RvValue, + nargs: usize, + ) -> RvStatus, + >, + /// Optional `__tostring`. When `None`, `tostring(u)` returns the type + /// `name`, never a memory address. + pub tostring: Option< + unsafe extern "C" fn( + cx: RvCx, + lua: *const RvLua, + data: *mut c_void, + args: *const RvValue, + nargs: usize, + ) -> RvStatus, + >, + /// Optional `__eq` for `u == v` when both operands are userdata of + /// this type. When `None`, userdata compare by identity. + pub eq: Option< + unsafe extern "C" fn( + cx: RvCx, + lua: *const RvLua, + data: *mut c_void, + args: *const RvValue, + nargs: usize, + ) -> RvStatus, + >, + /// Optional `__lt` for `u < v`. + pub lt: Option< + unsafe extern "C" fn( + cx: RvCx, + lua: *const RvLua, + data: *mut c_void, + args: *const RvValue, + nargs: usize, + ) -> RvStatus, + >, + /// Optional `__le` for `u <= v`. + pub le: Option< + unsafe extern "C" fn( + cx: RvCx, + lua: *const RvLua, + data: *mut c_void, + args: *const RvValue, + nargs: usize, + ) -> RvStatus, + >, + /// Optional `__len` for `#u`. + pub len: Option< + unsafe extern "C" fn( + cx: RvCx, + lua: *const RvLua, + data: *mut c_void, + args: *const RvValue, + nargs: usize, + ) -> RvStatus, + >, + /// Optional `__call` for `u(...)`; `args[0]` is `u`. + pub call: Option< + unsafe extern "C" fn( + cx: RvCx, + lua: *const RvLua, + data: *mut c_void, + args: *const RvValue, + nargs: usize, + ) -> RvStatus, + >, + /// Frees an instance's `data` when Lua collects it or the VM closes. + pub drop_fn: Option, +} + +/// A Pack function called from Lua. `args` holds `nargs` values, valid for +/// this call only. Results go through `return_values` on `lua`; returning +/// without calling it returns no values. Return [`RV_OK`], or the non-OK +/// status of an [`RvLua`] call to raise the error that call holds. It must +/// not unwind. +pub type RvFunction = unsafe extern "C" fn( + cx: RvCx, + lua: *const RvLua, + data: *mut c_void, + args: *const RvValue, + nargs: usize, +) -> RvStatus; + +/// Frees Pack data attached to a function or userdata instance. It runs +/// once, when Lua collects the owner or the VM closes, and receives no +/// context and may not call [`RvLua`]. It must not unwind. +pub type RvDrop = unsafe extern "C" fn(data: *mut c_void); + +/// The Lua API table the Host lends to [`RV_PACK_OPEN`] and to every +/// [`RvFunction`]. The Engine implements every entry with its own `mlua`. +#[repr(C)] +#[derive(Debug)] +pub struct RvLua { + /// The size of this struct in bytes: `sizeof(RvLua)`. + pub size: u32, + /// Zero. + pub reserved: u32, + /// Holds an author error with `message` (UTF-8, at most + /// [`RV_MAX_LINE`] bytes) and returns [`RV_ERR_LUA`]. + pub raise: unsafe extern "C" fn(cx: RvCx, message: RvStr) -> RvStatus, + /// Reads the held error's message into `out`, valid until + /// `clear_error` or the end of the call. + pub error_message: unsafe extern "C" fn(cx: RvCx, out: *mut RvStr) -> RvStatus, + /// Drops a held [`RV_ERR_LUA`], [`RV_ERR_TYPE`], or [`RV_ERR_MISUSE`]. + /// Returns [`RV_ERR_FATAL`] when a fatal error is held. + pub clear_error: unsafe extern "C" fn(cx: RvCx) -> RvStatus, + /// Returns [`RV_ERR_FATAL`] once the run is canceled. + pub check_cancel: unsafe extern "C" fn(cx: RvCx) -> RvStatus, + /// Records the current position in the call's handle arena. + pub mark: unsafe extern "C" fn(cx: RvCx, out: *mut RvMark) -> RvStatus, + /// Releases every handle created after `mark`. A released handle is + /// refused afterward, even if its slot is reused. + pub release_to: unsafe extern "C" fn(cx: RvCx, mark: RvMark) -> RvStatus, + /// Copies `bytes` into a new Lua string handle. + pub new_string: unsafe extern "C" fn(cx: RvCx, bytes: RvBytes, out: *mut RvValue) -> RvStatus, + /// Borrows a Lua string's bytes, valid while `string` is. [`RV_STRING`] + /// only: numbers are never coerced. + pub string_bytes: + unsafe extern "C" fn(cx: RvCx, string: RvValue, out: *mut RvBytes) -> RvStatus, + /// Creates a new Lua table; `flags` may hold [`RV_TABLE_LIST`]. + pub new_table: unsafe extern "C" fn( + cx: RvCx, + list_hint: u32, + field_hint: u32, + flags: u32, + out: *mut RvValue, + ) -> RvStatus, + /// Marks `table` as a list with `json.array(t)`'s rules: a table with + /// any other metatable is refused. + pub mark_list: unsafe extern "C" fn(cx: RvCx, table: RvValue) -> RvStatus, + /// Writes `1` to `out` when `value` is a table with the list marker, + /// and `0` otherwise. + pub is_list: unsafe extern "C" fn(cx: RvCx, value: RvValue, out: *mut u32) -> RvStatus, + /// `object[key]`, running `__index` as Lua does. `object` is a table + /// or userdata. + pub get: unsafe extern "C" fn( + cx: RvCx, + object: RvValue, + key: RvValue, + out: *mut RvValue, + ) -> RvStatus, + /// `object[name]`, running `__index` as Lua does. + pub get_field: + unsafe extern "C" fn(cx: RvCx, object: RvValue, name: RvStr, out: *mut RvValue) -> RvStatus, + /// `table[key]` without metamethods. + pub raw_get: + unsafe extern "C" fn(cx: RvCx, table: RvValue, key: RvValue, out: *mut RvValue) -> RvStatus, + /// `object[key] = value`, running `__newindex` as Lua does, so `var` + /// validation and every read-only refusal apply. + pub set: + unsafe extern "C" fn(cx: RvCx, object: RvValue, key: RvValue, value: RvValue) -> RvStatus, + /// `object[name] = value`, running `__newindex` as Lua does. + pub set_field: + unsafe extern "C" fn(cx: RvCx, object: RvValue, name: RvStr, value: RvValue) -> RvStatus, + /// A table's border length, without `__len`, unsealing table-backed + /// Engine views. + pub raw_len: unsafe extern "C" fn(cx: RvCx, table: RvValue, out: *mut i64) -> RvStatus, + /// `setmetatable(table, metatable)` with Lua's protection rules, + /// refusing any metatable holding `__gc`, `__mode`, or `__close`. + pub set_metatable: + unsafe extern "C" fn(cx: RvCx, table: RvValue, metatable: RvValue) -> RvStatus, + /// `rawequal(a, b)`: identity for handles, value for scalars. + pub raw_equal: + unsafe extern "C" fn(cx: RvCx, a: RvValue, b: RvValue, out: *mut u32) -> RvStatus, + /// Captures a table's keys once in the Engine's deterministic `pairs` + /// order (unsealing table-backed Engine views). + pub iter_begin: unsafe extern "C" fn(cx: RvCx, table: RvValue, out: *mut RvIter) -> RvStatus, + /// Advances `iter` to the next live entry. At the end, writes `1` to + /// `done` and `nil` to `key` and `value`. + pub iter_next: unsafe extern "C" fn( + cx: RvCx, + iter: RvIter, + key: *mut RvValue, + value: *mut RvValue, + done: *mut u32, + ) -> RvStatus, + /// Creates a Lua function backed by `info->call`. Ownership of `data` + /// passes to the Engine on every path (freed via `info->drop_fn` on + /// failure or when Lua collects the function). + pub new_function: unsafe extern "C" fn( + cx: RvCx, + info: *const RvFunctionInfo, + data: *mut c_void, + out: *mut RvValue, + ) -> RvStatus, + /// Calls `callee(args...)`, keeping `nresults` results and filling + /// missing ones with `nil`. A yield inside fails as [`RV_ERR_LUA`]. + pub call: unsafe extern "C" fn( + cx: RvCx, + callee: RvValue, + args: *const RvValue, + nargs: usize, + results: *mut RvValue, + nresults: usize, + ) -> RvStatus, + /// Sets the current [`RvFunction`]'s return values; a second call + /// replaces the first. Refused inside [`RV_PACK_OPEN`]. + pub return_values: + unsafe extern "C" fn(cx: RvCx, values: *const RvValue, count: usize) -> RvStatus, + /// Creates a new userdata instance of `ty`. Ownership of `data` passes + /// to the Engine on every path and is freed with `ty->drop_fn`. + pub new_userdata: unsafe extern "C" fn( + cx: RvCx, + ty: *const RvUserdataType, + data: *mut c_void, + out: *mut RvValue, + ) -> RvStatus, + /// Reads the `data` pointer of an instance of `ty`, or returns + /// [`RV_ERR_TYPE`] for any other value. + pub userdata_data: unsafe extern "C" fn( + cx: RvCx, + value: RvValue, + ty: *const RvUserdataType, + out: *mut *mut c_void, + ) -> RvStatus, + /// Reads user value slot `index` (below `ty->user_values`) on an + /// instance of `ty`. + pub get_user_value: unsafe extern "C" fn( + cx: RvCx, + value: RvValue, + ty: *const RvUserdataType, + index: u32, + out: *mut RvValue, + ) -> RvStatus, + /// Writes `item` to user value slot `index` (below `ty->user_values`) + /// on an instance of `ty`. + pub set_user_value: unsafe extern "C" fn( + cx: RvCx, + value: RvValue, + ty: *const RvUserdataType, + index: u32, + item: RvValue, + ) -> RvStatus, + /// Parses `json` as `json.decode` does (lists marked, `null` as + /// `json.null`, up to 8,388,608 bytes and 127 levels), prefixing + /// errors with `who`. + pub from_json: + unsafe extern "C" fn(cx: RvCx, who: RvStr, json: RvStr, out: *mut RvValue) -> RvStatus, + /// Encodes `value` as `json.encode` does, reading through Engine views, + /// and returns a Lua string in `out`, prefixing errors with `who`. + pub to_json: + unsafe extern "C" fn(cx: RvCx, who: RvStr, value: RvValue, out: *mut RvValue) -> RvStatus, +} + +/// The arguments of [`RV_PACK_OPEN`]: the Pack's id, its prelude +/// environment table `env`, the [`RvLua`] call context and function table, +/// and `refuse`. +#[repr(C)] +#[derive(Debug)] +pub struct RvPackOpenArgs { + /// The size of this struct in bytes: `sizeof(RvPackOpenArgs)`. + pub size: u32, + /// Zero. + pub reserved: u32, + /// The Host's context for `refuse`. The Plugin never reads through it. + pub ctx: *mut c_void, + /// The [`RvLua`] context for this `open` call. + pub lua_cx: RvCx, + /// The Pack's id, the second segment of its name, such as `url`. + pub pack_id: RvStr, + /// The Pack's prelude environment table (`RV_TABLE`): every field set + /// on it becomes a global in the section VM once `open` and any + /// `lua_prelude` return. + pub env: RvValue, + /// The Engine's Lua API table, valid for the life of the process. + pub lua: *const RvLua, + /// Declines to open the prelude, 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 section entry fails. + pub refuse: unsafe extern "C" fn(ctx: *mut c_void, reason: RvStr) -> RvStatus, +} + /// One call into a Plugin's entry point. #[repr(C)] #[derive(Debug)] @@ -882,13 +1350,14 @@ 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_PACK_RENDER`], [`RV_TOOL_CALL`], and [`RV_TOOL_CANCEL`], and - /// NULL otherwise. + /// [`RV_PACK_RENDER`], [`RV_PACK_OPEN`], [`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 [`RvPackRenderArgs`] - /// for [`RV_PACK_RENDER`], an [`RvToolCallArgs`] for [`RV_TOOL_CALL`], - /// and NULL for every other verb. + /// for [`RV_PACK_RENDER`], an [`RvPackOpenArgs`] for [`RV_PACK_OPEN`], + /// 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 @@ -912,22 +1381,26 @@ mod tests { use core::mem::{offset_of, size_of}; use super::{ - 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_JSON, RV_MAX_TOOL_TEXT, RV_MAX_WRITE, RV_OK, RV_PACK_DELETE, RV_PACK_NEW, - RV_PACK_RENDER, RV_PENDING, RV_PLUGIN_LOAD, RV_PLUGIN_UNLOAD, RV_RESULT_BACKEND, - RV_RESULT_INVALID_ARGUMENTS, RV_RESULT_OTHER, RV_RESULT_TRANSPORT, RV_RESULT_TRUSTED, - RV_RESULT_UNTRUSTED, RV_TOOL_CALL, RV_TOOL_CANCEL, + RV_API_MAJOR, RV_API_MINOR, RV_BOOLEAN, RV_CALLER_MODEL, RV_CALLER_SCRIPT, RV_ERR_FATAL, + RV_ERR_FILE, RV_ERR_LUA, RV_ERR_MISUSE, RV_ERR_REFUSED, RV_ERR_TYPE, 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_FUNCTION, RV_INTEGER, RV_LIGHTUSERDATA, RV_MAX_LINE, RV_MAX_NAME, RV_MAX_PATH, + RV_MAX_RESULT, RV_MAX_TOOL_JSON, RV_MAX_TOOL_TEXT, RV_MAX_USER_VALUES, RV_MAX_VALUES, + RV_MAX_WRITE, RV_NIL, RV_NULL, RV_NUMBER, RV_OK, RV_OPAQUE, RV_PACK_DELETE, RV_PACK_NEW, + RV_PACK_OPEN, 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_STRING, RV_TABLE, RV_TABLE_LIST, RV_TOOL_CALL, + RV_TOOL_CANCEL, RV_USERDATA, }; #[cfg(target_pointer_width = "64")] use super::{ - RvBytes, RvCall, RvDirEntries, RvDirEntry, RvFileAnswer, RvFileError, RvHost, RvLoadArgs, - RvPackInfo, RvPackNewArgs, RvPackRenderArgs, RvPluginInfo, RvStat, RvStr, RvToolCallArgs, - RvToolInfo, RvToolResult, RvWaker, + RvBytes, RvCall, RvCx, RvDirEntries, RvDirEntry, RvFileAnswer, RvFileError, RvFunctionInfo, + RvHost, RvIter, RvLoadArgs, RvLua, RvMark, RvMethod, RvPackInfo, RvPackNewArgs, + RvPackOpenArgs, RvPackRenderArgs, RvPluginInfo, RvStat, RvStr, RvToolCallArgs, RvToolInfo, + RvToolResult, RvUserdataType, RvValue, RvWaker, }; #[test] @@ -951,11 +1424,12 @@ mod tests { #[test] #[cfg(target_pointer_width = "64")] fn the_pack_info_keeps_its_layout() { - assert_eq!(size_of::(), 40); + assert_eq!(size_of::(), 56); assert_eq!(offset_of!(RvPackInfo, size), 0); assert_eq!(offset_of!(RvPackInfo, reserved), 4); assert_eq!(offset_of!(RvPackInfo, name), 8); assert_eq!(offset_of!(RvPackInfo, description), 24); + assert_eq!(offset_of!(RvPackInfo, lua_prelude), 40); } #[test] @@ -1098,6 +1572,93 @@ mod tests { assert_eq!(offset_of!(RvToolCallArgs, model), 200); } + #[test] + #[cfg(target_pointer_width = "64")] + fn the_lua_types_keep_their_layout() { + assert_eq!(size_of::(), 16); + assert_eq!(offset_of!(RvValue, kind), 0); + assert_eq!(offset_of!(RvValue, reserved), 4); + assert_eq!(offset_of!(RvValue, payload), 8); + + assert_eq!(size_of::(), 8); + assert_eq!(offset_of!(RvCx, bits), 0); + assert_eq!(size_of::(), 8); + assert_eq!(offset_of!(RvMark, bits), 0); + assert_eq!(size_of::(), 8); + assert_eq!(offset_of!(RvIter, bits), 0); + + assert_eq!(size_of::(), 40); + assert_eq!(offset_of!(RvFunctionInfo, size), 0); + assert_eq!(offset_of!(RvFunctionInfo, reserved), 4); + assert_eq!(offset_of!(RvFunctionInfo, name), 8); + assert_eq!(offset_of!(RvFunctionInfo, call), 24); + assert_eq!(offset_of!(RvFunctionInfo, drop_fn), 32); + + assert_eq!(size_of::(), 24); + assert_eq!(offset_of!(RvMethod, name), 0); + assert_eq!(offset_of!(RvMethod, call), 16); + + assert_eq!(size_of::(), 112); + assert_eq!(offset_of!(RvUserdataType, size), 0); + assert_eq!(offset_of!(RvUserdataType, user_values), 4); + assert_eq!(offset_of!(RvUserdataType, name), 8); + assert_eq!(offset_of!(RvUserdataType, methods), 24); + assert_eq!(offset_of!(RvUserdataType, method_count), 32); + assert_eq!(offset_of!(RvUserdataType, index), 40); + assert_eq!(offset_of!(RvUserdataType, newindex), 48); + assert_eq!(offset_of!(RvUserdataType, tostring), 56); + assert_eq!(offset_of!(RvUserdataType, eq), 64); + assert_eq!(offset_of!(RvUserdataType, lt), 72); + assert_eq!(offset_of!(RvUserdataType, le), 80); + assert_eq!(offset_of!(RvUserdataType, len), 88); + assert_eq!(offset_of!(RvUserdataType, call), 96); + assert_eq!(offset_of!(RvUserdataType, drop_fn), 104); + + assert_eq!(size_of::(), 248); + assert_eq!(offset_of!(RvLua, size), 0); + assert_eq!(offset_of!(RvLua, reserved), 4); + assert_eq!(offset_of!(RvLua, raise), 8); + assert_eq!(offset_of!(RvLua, error_message), 16); + assert_eq!(offset_of!(RvLua, clear_error), 24); + assert_eq!(offset_of!(RvLua, check_cancel), 32); + assert_eq!(offset_of!(RvLua, mark), 40); + assert_eq!(offset_of!(RvLua, release_to), 48); + assert_eq!(offset_of!(RvLua, new_string), 56); + assert_eq!(offset_of!(RvLua, string_bytes), 64); + assert_eq!(offset_of!(RvLua, new_table), 72); + assert_eq!(offset_of!(RvLua, mark_list), 80); + assert_eq!(offset_of!(RvLua, is_list), 88); + assert_eq!(offset_of!(RvLua, get), 96); + assert_eq!(offset_of!(RvLua, get_field), 104); + assert_eq!(offset_of!(RvLua, raw_get), 112); + assert_eq!(offset_of!(RvLua, set), 120); + assert_eq!(offset_of!(RvLua, set_field), 128); + assert_eq!(offset_of!(RvLua, raw_len), 136); + assert_eq!(offset_of!(RvLua, set_metatable), 144); + assert_eq!(offset_of!(RvLua, raw_equal), 152); + assert_eq!(offset_of!(RvLua, iter_begin), 160); + assert_eq!(offset_of!(RvLua, iter_next), 168); + assert_eq!(offset_of!(RvLua, new_function), 176); + assert_eq!(offset_of!(RvLua, call), 184); + assert_eq!(offset_of!(RvLua, return_values), 192); + assert_eq!(offset_of!(RvLua, new_userdata), 200); + assert_eq!(offset_of!(RvLua, userdata_data), 208); + assert_eq!(offset_of!(RvLua, get_user_value), 216); + assert_eq!(offset_of!(RvLua, set_user_value), 224); + assert_eq!(offset_of!(RvLua, from_json), 232); + assert_eq!(offset_of!(RvLua, to_json), 240); + + assert_eq!(size_of::(), 72); + assert_eq!(offset_of!(RvPackOpenArgs, size), 0); + assert_eq!(offset_of!(RvPackOpenArgs, reserved), 4); + assert_eq!(offset_of!(RvPackOpenArgs, ctx), 8); + assert_eq!(offset_of!(RvPackOpenArgs, lua_cx), 16); + assert_eq!(offset_of!(RvPackOpenArgs, pack_id), 24); + assert_eq!(offset_of!(RvPackOpenArgs, env), 40); + assert_eq!(offset_of!(RvPackOpenArgs, lua), 56); + assert_eq!(offset_of!(RvPackOpenArgs, refuse), 64); + } + #[test] #[cfg(target_pointer_width = "64")] fn the_call_keeps_its_layout() { @@ -1114,6 +1675,9 @@ mod tests { #[test] fn the_status_codes_keep_their_numbers() { assert_eq!(RV_OK, 0); + assert_eq!(RV_ERR_LUA, 1); + assert_eq!(RV_ERR_FATAL, 2); + assert_eq!(RV_ERR_TYPE, 3); assert_eq!(RV_ERR_MISUSE, 4); assert_eq!(RV_ERR_REFUSED, 5); assert_eq!(RV_ERR_UNSUPPORTED, 6); @@ -1130,6 +1694,24 @@ mod tests { assert_eq!(RV_MAX_TOOL_JSON, 262_144); assert_eq!(RV_MAX_RESULT, 16_777_216); assert_eq!(RV_MAX_WRITE, 16_777_216); + assert_eq!(RV_MAX_VALUES, 255); + assert_eq!(RV_MAX_USER_VALUES, 4); + assert_eq!(RV_TABLE_LIST, 1); + } + + #[test] + fn the_lua_kinds_keep_their_numbers() { + assert_eq!(RV_NIL, 0); + assert_eq!(RV_BOOLEAN, 1); + assert_eq!(RV_INTEGER, 2); + assert_eq!(RV_NUMBER, 3); + assert_eq!(RV_NULL, 4); + assert_eq!(RV_LIGHTUSERDATA, 5); + assert_eq!(RV_STRING, 6); + assert_eq!(RV_TABLE, 7); + assert_eq!(RV_FUNCTION, 8); + assert_eq!(RV_USERDATA, 9); + assert_eq!(RV_OPAQUE, 10); } #[test] @@ -1164,6 +1746,7 @@ mod tests { assert_eq!(RV_TOOL_CALL, 5); assert_eq!(RV_TOOL_CANCEL, 6); assert_eq!(RV_PACK_RENDER, 7); + assert_eq!(RV_PACK_OPEN, 8); } #[test] diff --git a/tests/c-layout/layout.c b/tests/c-layout/layout.c index 0516865..0cf3582 100644 --- a/tests/c-layout/layout.c +++ b/tests/c-layout/layout.c @@ -57,6 +57,7 @@ static const RvLayoutEntry ENTRIES[] = { OFFSET(RvPackInfo, reserved), OFFSET(RvPackInfo, name), OFFSET(RvPackInfo, description), + OFFSET(RvPackInfo, lua_prelude), SIZE(RvToolInfo), OFFSET(RvToolInfo, size), OFFSET(RvToolInfo, reserved), @@ -121,6 +122,83 @@ static const RvLayoutEntry ENTRIES[] = { OFFSET(RvToolCallArgs, section), OFFSET(RvToolCallArgs, entry), OFFSET(RvToolCallArgs, model), + SIZE(RvKind), + SIZE(RvValue), + OFFSET(RvValue, kind), + OFFSET(RvValue, reserved), + OFFSET(RvValue, payload), + SIZE(RvCx), + OFFSET(RvCx, bits), + SIZE(RvMark), + OFFSET(RvMark, bits), + SIZE(RvIter), + OFFSET(RvIter, bits), + SIZE(RvFunctionInfo), + OFFSET(RvFunctionInfo, size), + OFFSET(RvFunctionInfo, reserved), + OFFSET(RvFunctionInfo, name), + OFFSET(RvFunctionInfo, call), + OFFSET(RvFunctionInfo, drop_fn), + SIZE(RvMethod), + OFFSET(RvMethod, name), + OFFSET(RvMethod, call), + SIZE(RvUserdataType), + OFFSET(RvUserdataType, size), + OFFSET(RvUserdataType, user_values), + OFFSET(RvUserdataType, name), + OFFSET(RvUserdataType, methods), + OFFSET(RvUserdataType, method_count), + OFFSET(RvUserdataType, index), + OFFSET(RvUserdataType, newindex), + OFFSET(RvUserdataType, tostring), + OFFSET(RvUserdataType, eq), + OFFSET(RvUserdataType, lt), + OFFSET(RvUserdataType, le), + OFFSET(RvUserdataType, len), + OFFSET(RvUserdataType, call), + OFFSET(RvUserdataType, drop_fn), + SIZE(RvLua), + OFFSET(RvLua, size), + OFFSET(RvLua, reserved), + OFFSET(RvLua, raise), + OFFSET(RvLua, error_message), + OFFSET(RvLua, clear_error), + OFFSET(RvLua, check_cancel), + OFFSET(RvLua, mark), + OFFSET(RvLua, release_to), + OFFSET(RvLua, new_string), + OFFSET(RvLua, string_bytes), + OFFSET(RvLua, new_table), + OFFSET(RvLua, mark_list), + OFFSET(RvLua, is_list), + OFFSET(RvLua, get), + OFFSET(RvLua, get_field), + OFFSET(RvLua, raw_get), + OFFSET(RvLua, set), + OFFSET(RvLua, set_field), + OFFSET(RvLua, raw_len), + OFFSET(RvLua, set_metatable), + OFFSET(RvLua, raw_equal), + OFFSET(RvLua, iter_begin), + OFFSET(RvLua, iter_next), + OFFSET(RvLua, new_function), + OFFSET(RvLua, call), + OFFSET(RvLua, return_values), + OFFSET(RvLua, new_userdata), + OFFSET(RvLua, userdata_data), + OFFSET(RvLua, get_user_value), + OFFSET(RvLua, set_user_value), + OFFSET(RvLua, from_json), + OFFSET(RvLua, to_json), + SIZE(RvPackOpenArgs), + OFFSET(RvPackOpenArgs, size), + OFFSET(RvPackOpenArgs, reserved), + OFFSET(RvPackOpenArgs, ctx), + OFFSET(RvPackOpenArgs, lua_cx), + OFFSET(RvPackOpenArgs, pack_id), + OFFSET(RvPackOpenArgs, env), + OFFSET(RvPackOpenArgs, lua), + OFFSET(RvPackOpenArgs, refuse), SIZE(RvCall), OFFSET(RvCall, size), OFFSET(RvCall, verb), @@ -130,6 +208,9 @@ static const RvLayoutEntry ENTRIES[] = { OFFSET(RvCall, args), OFFSET(RvCall, tool_call), VALUE(RV_OK), + VALUE(RV_ERR_LUA), + VALUE(RV_ERR_FATAL), + VALUE(RV_ERR_TYPE), VALUE(RV_ERR_MISUSE), VALUE(RV_ERR_REFUSED), VALUE(RV_ERR_UNSUPPORTED), @@ -142,6 +223,7 @@ static const RvLayoutEntry ENTRIES[] = { VALUE(RV_TOOL_CALL), VALUE(RV_TOOL_CANCEL), VALUE(RV_PACK_RENDER), + VALUE(RV_PACK_OPEN), VALUE(RV_RESULT_UNTRUSTED), VALUE(RV_RESULT_TRUSTED), VALUE(RV_RESULT_INVALID_ARGUMENTS), @@ -163,6 +245,17 @@ static const RvLayoutEntry ENTRIES[] = { VALUE(RV_FILE_ERROR_NOT_EMPTY), VALUE(RV_CALLER_MODEL), VALUE(RV_CALLER_SCRIPT), + VALUE(RV_NIL), + VALUE(RV_BOOLEAN), + VALUE(RV_INTEGER), + VALUE(RV_NUMBER), + VALUE(RV_NULL), + VALUE(RV_LIGHTUSERDATA), + VALUE(RV_STRING), + VALUE(RV_TABLE), + VALUE(RV_FUNCTION), + VALUE(RV_USERDATA), + VALUE(RV_OPAQUE), VALUE(RV_API_MAJOR), VALUE(RV_API_MINOR), VALUE(RV_MAX_NAME), @@ -172,6 +265,9 @@ static const RvLayoutEntry ENTRIES[] = { VALUE(RV_MAX_TOOL_JSON), VALUE(RV_MAX_RESULT), VALUE(RV_MAX_WRITE), + VALUE(RV_MAX_VALUES), + VALUE(RV_MAX_USER_VALUES), + VALUE(RV_TABLE_LIST), }; /* The table above, and its length through `count`. */ diff --git a/tests/c-layout/layout.cpp b/tests/c-layout/layout.cpp index ca00458..290b299 100644 --- a/tests/c-layout/layout.cpp +++ b/tests/c-layout/layout.cpp @@ -29,6 +29,14 @@ extern "C" std::size_t rv_cpp_offset_of_tool_call_model(void) { return offsetof(RvToolCallArgs, model); } +extern "C" std::size_t rv_cpp_size_of_lua(void) { + return sizeof(RvLua); +} + +extern "C" std::size_t rv_cpp_size_of_pack_open_args(void) { + return sizeof(RvPackOpenArgs); +} + 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 0ef146f..77cc076 100644 --- a/tests/c-layout/src/lib.rs +++ b/tests/c-layout/src/lib.rs @@ -21,19 +21,23 @@ mod tests { use std::{ptr, slice}; use runvil_plugin_sys::{ - 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_JSON, RV_MAX_TOOL_TEXT, RV_MAX_WRITE, RV_OK, RV_PACK_DELETE, RV_PACK_NEW, - RV_PACK_RENDER, RV_PENDING, RV_PLUGIN_LOAD, RV_PLUGIN_UNLOAD, RV_RESULT_BACKEND, - RV_RESULT_INVALID_ARGUMENTS, RV_RESULT_OTHER, RV_RESULT_TRANSPORT, RV_RESULT_TRUSTED, - RV_RESULT_UNTRUSTED, RV_TOOL_CALL, RV_TOOL_CANCEL, RvBytes, RvCall, RvCaller, RvDirEntries, - RvDirEntry, RvFileAnswer, RvFileError, RvFileErrorKind, RvFileType, RvHost, RvLoadArgs, - RvPackInfo, RvPackNewArgs, RvPackRenderArgs, RvPluginInfo, RvResultKind, RvStat, RvStatus, - RvStr, RvToolCallArgs, RvToolInfo, RvToolResult, RvVerb, RvWaker, + RV_API_MAJOR, RV_API_MINOR, RV_BOOLEAN, RV_CALLER_MODEL, RV_CALLER_SCRIPT, RV_ERR_FATAL, + RV_ERR_FILE, RV_ERR_LUA, RV_ERR_MISUSE, RV_ERR_REFUSED, RV_ERR_TYPE, 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_FUNCTION, RV_INTEGER, RV_LIGHTUSERDATA, RV_MAX_LINE, RV_MAX_NAME, RV_MAX_PATH, + RV_MAX_RESULT, RV_MAX_TOOL_JSON, RV_MAX_TOOL_TEXT, RV_MAX_USER_VALUES, RV_MAX_VALUES, + RV_MAX_WRITE, RV_NIL, RV_NULL, RV_NUMBER, RV_OK, RV_OPAQUE, RV_PACK_DELETE, RV_PACK_NEW, + RV_PACK_OPEN, 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_STRING, RV_TABLE, RV_TABLE_LIST, RV_TOOL_CALL, + RV_TOOL_CANCEL, RV_USERDATA, RvBytes, RvCall, RvCaller, RvCx, RvDirEntries, RvDirEntry, + RvFileAnswer, RvFileError, RvFileErrorKind, RvFileType, RvFunctionInfo, RvHost, RvIter, + RvKind, RvLoadArgs, RvLua, RvMark, RvMethod, RvPackInfo, RvPackNewArgs, RvPackOpenArgs, + RvPackRenderArgs, RvPluginInfo, RvResultKind, RvStat, RvStatus, RvStr, RvToolCallArgs, + RvToolInfo, RvToolResult, RvUserdataType, RvValue, RvVerb, RvWaker, }; /// One entry of the table in `layout.c`. @@ -56,8 +60,12 @@ mod tests { 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. + /// `offsetof(RvToolCallArgs, model)` as C++ sees it. safe fn rv_cpp_offset_of_tool_call_model() -> usize; + /// `sizeof(RvLua)` as C++ sees it. + safe fn rv_cpp_size_of_lua() -> usize; + /// `sizeof(RvPackOpenArgs)` as C++ sees it. + safe fn rv_cpp_size_of_pack_open_args() -> usize; /// `runvil_plugin` as C++ names it. safe fn rv_cpp_entry() -> unsafe extern "C" fn(*mut RvCall) -> RvStatus; } @@ -113,7 +121,7 @@ mod tests { /// What Rust sees, in the order of the table in `layout.c`. fn rust_layout() -> BTreeMap { - [data_structs(), call_structs(), constants()] + [data_structs(), call_structs(), lua_structs(), constants()] .into_iter() .flatten() .map(|(what, value)| (what.to_owned(), value)) @@ -165,6 +173,7 @@ mod tests { offset!(RvPackInfo, reserved), offset!(RvPackInfo, name), offset!(RvPackInfo, description), + offset!(RvPackInfo, lua_prelude), size!(RvToolInfo), offset!(RvToolInfo, size), offset!(RvToolInfo, reserved), @@ -236,6 +245,89 @@ mod tests { offset!(RvToolCallArgs, section), offset!(RvToolCallArgs, entry), offset!(RvToolCallArgs, model), + ] + } + + /// The Lua native prelude structs, `RvPackOpenArgs`, and `RvCall`. + fn lua_structs() -> Vec<(&'static str, usize)> { + vec![ + size!(RvKind), + size!(RvValue), + offset!(RvValue, kind), + offset!(RvValue, reserved), + offset!(RvValue, payload), + size!(RvCx), + offset!(RvCx, bits), + size!(RvMark), + offset!(RvMark, bits), + size!(RvIter), + offset!(RvIter, bits), + size!(RvFunctionInfo), + offset!(RvFunctionInfo, size), + offset!(RvFunctionInfo, reserved), + offset!(RvFunctionInfo, name), + offset!(RvFunctionInfo, call), + offset!(RvFunctionInfo, drop_fn), + size!(RvMethod), + offset!(RvMethod, name), + offset!(RvMethod, call), + size!(RvUserdataType), + offset!(RvUserdataType, size), + offset!(RvUserdataType, user_values), + offset!(RvUserdataType, name), + offset!(RvUserdataType, methods), + offset!(RvUserdataType, method_count), + offset!(RvUserdataType, index), + offset!(RvUserdataType, newindex), + offset!(RvUserdataType, tostring), + offset!(RvUserdataType, eq), + offset!(RvUserdataType, lt), + offset!(RvUserdataType, le), + offset!(RvUserdataType, len), + offset!(RvUserdataType, call), + offset!(RvUserdataType, drop_fn), + size!(RvLua), + offset!(RvLua, size), + offset!(RvLua, reserved), + offset!(RvLua, raise), + offset!(RvLua, error_message), + offset!(RvLua, clear_error), + offset!(RvLua, check_cancel), + offset!(RvLua, mark), + offset!(RvLua, release_to), + offset!(RvLua, new_string), + offset!(RvLua, string_bytes), + offset!(RvLua, new_table), + offset!(RvLua, mark_list), + offset!(RvLua, is_list), + offset!(RvLua, get), + offset!(RvLua, get_field), + offset!(RvLua, raw_get), + offset!(RvLua, set), + offset!(RvLua, set_field), + offset!(RvLua, raw_len), + offset!(RvLua, set_metatable), + offset!(RvLua, raw_equal), + offset!(RvLua, iter_begin), + offset!(RvLua, iter_next), + offset!(RvLua, new_function), + offset!(RvLua, call), + offset!(RvLua, return_values), + offset!(RvLua, new_userdata), + offset!(RvLua, userdata_data), + offset!(RvLua, get_user_value), + offset!(RvLua, set_user_value), + offset!(RvLua, from_json), + offset!(RvLua, to_json), + size!(RvPackOpenArgs), + offset!(RvPackOpenArgs, size), + offset!(RvPackOpenArgs, reserved), + offset!(RvPackOpenArgs, ctx), + offset!(RvPackOpenArgs, lua_cx), + offset!(RvPackOpenArgs, pack_id), + offset!(RvPackOpenArgs, env), + offset!(RvPackOpenArgs, lua), + offset!(RvPackOpenArgs, refuse), size!(RvCall), offset!(RvCall, size), offset!(RvCall, verb), @@ -251,6 +343,9 @@ mod tests { fn constants() -> Vec<(&'static str, usize)> { vec![ value!(RV_OK), + value!(RV_ERR_LUA), + value!(RV_ERR_FATAL), + value!(RV_ERR_TYPE), value!(RV_ERR_MISUSE), value!(RV_ERR_REFUSED), value!(RV_ERR_UNSUPPORTED), @@ -263,6 +358,7 @@ mod tests { value!(RV_TOOL_CALL), value!(RV_TOOL_CANCEL), value!(RV_PACK_RENDER), + value!(RV_PACK_OPEN), value!(RV_RESULT_UNTRUSTED), value!(RV_RESULT_TRUSTED), value!(RV_RESULT_INVALID_ARGUMENTS), @@ -284,6 +380,17 @@ mod tests { value!(RV_FILE_ERROR_NOT_EMPTY), value!(RV_CALLER_MODEL), value!(RV_CALLER_SCRIPT), + value!(RV_NIL), + value!(RV_BOOLEAN), + value!(RV_INTEGER), + value!(RV_NUMBER), + value!(RV_NULL), + value!(RV_LIGHTUSERDATA), + value!(RV_STRING), + value!(RV_TABLE), + value!(RV_FUNCTION), + value!(RV_USERDATA), + value!(RV_OPAQUE), value!(RV_API_MAJOR), value!(RV_API_MINOR), value!(RV_MAX_NAME), @@ -293,6 +400,9 @@ mod tests { value!(RV_MAX_TOOL_JSON), value!(RV_MAX_RESULT), value!(RV_MAX_WRITE), + value!(RV_MAX_VALUES), + value!(RV_MAX_USER_VALUES), + value!(RV_TABLE_LIST), ] } @@ -332,6 +442,8 @@ mod tests { #[test] fn cpp_sees_the_same_call_and_reaches_the_c_entry_point() { assert_eq!(rv_cpp_size_of_call(), size_of::()); + assert_eq!(rv_cpp_size_of_lua(), size_of::()); + assert_eq!(rv_cpp_size_of_pack_open_args(), size_of::()); // SAFETY: the address is the C entry point, which never reads its // argument. let status = unsafe { rv_cpp_entry()(ptr::null_mut()) }; From 59de10d20da52f9ed402564afd7cfd4f2014c533 Mon Sep 17 00:00:00 2001 From: Vinnie Falco Date: Wed, 2 Dec 2026 19:07:41 -0800 Subject: [PATCH 3/4] Add LuaPrelude, Pack::open, and lua_prelude in SDK 0.10.0 Expose LuaPrelude, LuaValue, LuaKind, LuaError, drop_userdata, Pack::open, and PackInfo::lua_prelude in unvil-plugin-sdk 0.10.0, and wire RV_PACK_OPEN in entry::pack::open. - Validate PackInfo::lua_prelude length at compile time in check_constants, and validate InsertedPack::lua_prelude in esting::load::insert_pack. - Catch panics in Pack::open, LuaPrelude::new_function closures, and drop_userdata so no panic unwinds across the C boundary. Plan: /plan/2026-12-02-3-native-preludes.plan.md --- crates/runvil-plugin-sdk/src/entry.rs | 16 +- crates/runvil-plugin-sdk/src/entry/pack.rs | 405 +++++++- crates/runvil-plugin-sdk/src/entry/plugin.rs | 29 +- crates/runvil-plugin-sdk/src/lib.rs | 2 + crates/runvil-plugin-sdk/src/lua.rs | 992 +++++++++++++++++++ crates/runvil-plugin-sdk/src/names.rs | 7 +- crates/runvil-plugin-sdk/src/pack.rs | 37 +- crates/runvil-plugin-sdk/src/testing.rs | 2 + crates/runvil-plugin-sdk/src/testing/load.rs | 11 +- 9 files changed, 1480 insertions(+), 21 deletions(-) create mode 100644 crates/runvil-plugin-sdk/src/lua.rs diff --git a/crates/runvil-plugin-sdk/src/entry.rs b/crates/runvil-plugin-sdk/src/entry.rs index 8563798..4ef2d7e 100644 --- a/crates/runvil-plugin-sdk/src/entry.rs +++ b/crates/runvil-plugin-sdk/src/entry.rs @@ -15,12 +15,13 @@ 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_PACK_RENDER, RV_PLUGIN_LOAD, - RV_PLUGIN_UNLOAD, RV_TOOL_CALL, RV_TOOL_CANCEL, RvCall, RvStatus, RvStr, + RV_ERR_MISUSE, RV_ERR_UNSUPPORTED, RV_PACK_DELETE, RV_PACK_NEW, RV_PACK_OPEN, RV_PACK_RENDER, + RV_PLUGIN_LOAD, RV_PLUGIN_UNLOAD, RV_TOOL_CALL, RV_TOOL_CANCEL, RvCall, RvStatus, RvStr, }; use crate::names::{ - is_valid_description, is_valid_name, is_valid_pack_name, is_valid_version, same, + is_valid_description, is_valid_lua_prelude, is_valid_name, is_valid_pack_name, + is_valid_version, same, }; use crate::{Plugin, Refusal}; @@ -86,6 +87,7 @@ pub unsafe extern "C" fn entry(call: *mut RvCall) -> RvStatus { RV_PACK_NEW => pack::new::

(call), RV_PACK_DELETE => pack::delete(call), RV_PACK_RENDER => pack::render(call), + RV_PACK_OPEN => pack::open(call), RV_TOOL_CALL => tool::step(call), RV_TOOL_CANCEL => tool::cancel(call), _ => RV_ERR_UNSUPPORTED, @@ -115,6 +117,10 @@ const fn check_constants() { is_valid_description(pack.description), "each description in Plugin::PACKS must be at most 1024 bytes with no control characters" ); + assert!( + is_valid_lua_prelude(pack.lua_prelude), + "each lua_prelude in Plugin::PACKS must be at most 65536 bytes" + ); let mut earlier = 0; while earlier < at { assert!( @@ -190,12 +196,12 @@ unsafe fn refuse( /// Runs `f`, which drops something the Plugin owns, and keeps a panic in /// it from unwinding across the C boundary. -fn contain(f: impl FnOnce()) { +pub(crate) fn contain(f: impl FnOnce()) { let _panicked = panic::catch_unwind(AssertUnwindSafe(f)); } /// The text of a panic's payload, when it has one. -fn panic_message(payload: &(dyn Any + Send)) -> &str { +pub(crate) fn panic_message(payload: &(dyn Any + Send)) -> &str { if let Some(message) = payload.downcast_ref::<&str>() { message } else if let Some(message) = payload.downcast_ref::() { diff --git a/crates/runvil-plugin-sdk/src/entry/pack.rs b/crates/runvil-plugin-sdk/src/entry/pack.rs index 6062c31..61c12ae 100644 --- a/crates/runvil-plugin-sdk/src/entry/pack.rs +++ b/crates/runvil-plugin-sdk/src/entry/pack.rs @@ -8,11 +8,12 @@ use std::panic::{self, AssertUnwindSafe}; use std::slice; use runvil_plugin_sys::{ - RV_ERR_MISUSE, RV_ERR_UNSUPPORTED, RV_OK, RvCall, RvPackNewArgs, RvPackRenderArgs, RvStatus, - RvToolInfo, + RV_ERR_MISUSE, RV_ERR_UNSUPPORTED, RV_OK, RV_TABLE, RvCall, RvLua, RvPackNewArgs, + RvPackOpenArgs, RvPackRenderArgs, RvStatus, RvToolInfo, }; use super::{args, contain, panic_message, read_str, refuse, rv_str, size_field}; +use crate::lua::{LuaPrelude, LuaValue}; use crate::pack::PackRun; use crate::{Pack, Plugin, Refusal, RenderContext, ToolInfo}; @@ -196,6 +197,58 @@ unsafe fn copy_tool(info: &RvToolInfo) -> Result { serde_json::from_str::(json).map_err(|_| RV_ERR_MISUSE) } +/// Answers `RV_PACK_OPEN`: checks the Pack instance, the arguments, and +/// the `RvLua` table, and calls [`Pack::open`]. A panic becomes a refusal +/// through `args.refuse`. +/// +/// # 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 +/// `RvPackOpenArgs` that follows the contract. +pub(super) unsafe fn open(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 `RvPackOpenArgs`. + let args = match unsafe { args::(call) } { + Ok(args) => args, + Err(status) => return status, + }; + if args.lua.is_null() || !args.lua.is_aligned() { + return RV_ERR_MISUSE; + } + // SAFETY: `args.lua` is non-NULL and aligned; `size` is its first field. + let lua_size = unsafe { args.lua.cast::().read() }; + if (lua_size as usize) < size_of::() { + return RV_ERR_UNSUPPORTED; + } + if args.env.kind != RV_TABLE { + return RV_ERR_MISUSE; + } + // SAFETY: the Host keeps `pack_id` valid for the call. + let Some(pack_id) = (unsafe { read_str(args.pack_id) }) else { + return RV_ERR_MISUSE; + }; + // SAFETY: `args.lua` is whole and valid for the call. + let lua = unsafe { LuaPrelude::from_raw(args.lua_cx, args.lua) }; + let env = LuaValue::from_raw(args.env); + let opened = panic::catch_unwind(AssertUnwindSafe(|| pack.open(&lua, env, pack_id))); + match opened { + Ok(result) => lua.finish(result), + Err(payload) => { + let refusal = Refusal::new(format!( + "the Pack panicked while opening its prelude: {}", + panic_message(&*payload) + )); + contain(move || drop(payload)); + // SAFETY: `args` belongs to the open call. + unsafe { refuse(args.refuse, args.ctx, &refusal) } + } + } +} + /// Answers `RV_PACK_DELETE`: drops the instance `RV_PACK_NEW` set, /// containing a panic in its `Drop`. /// @@ -237,13 +290,16 @@ mod tests { use std::sync::atomic::{AtomicIsize, Ordering}; use runvil_plugin_sys::{ - RV_ERR_MISUSE, RV_ERR_REFUSED, RV_ERR_UNSUPPORTED, RV_OK, RV_PACK_DELETE, RV_PACK_NEW, - RV_PACK_RENDER, RvCall, RvPackRenderArgs, RvStatus, RvStr, RvToolInfo, + RV_ERR_LUA, RV_ERR_MISUSE, RV_ERR_REFUSED, RV_ERR_UNSUPPORTED, RV_OK, RV_PACK_DELETE, + RV_PACK_NEW, RV_PACK_OPEN, RV_PACK_RENDER, RV_STRING, RV_TABLE, RvBytes, RvCall, RvCx, + RvIter, RvLua, RvMark, RvPackOpenArgs, RvPackRenderArgs, RvStatus, RvStr, RvToolInfo, + RvUserdataType, RvValue, }; use serde_json::{Value, json}; use super::PackRun; use crate::entry::{entry, read_str, rv_str, size_field}; + use crate::lua::{LuaError, LuaPrelude, LuaValue}; use crate::testing::{self, Failure}; use crate::{ BoxFuture, Pack, PackInfo, Plugin, Refusal, RenderContext, ToolCall, ToolError, ToolInfo, @@ -746,7 +802,7 @@ mod tests { #[test] fn a_pack_verb_without_its_instance_is_a_misuse() { - for verb in [RV_PACK_NEW, RV_PACK_DELETE] { + for verb in [RV_PACK_NEW, RV_PACK_DELETE, RV_PACK_OPEN] { let mut call = RvCall { size: size_field::(), verb, @@ -761,4 +817,343 @@ mod tests { assert_eq!(unsafe { entry::(&raw mut call) }, RV_ERR_MISUSE); } } + + /// What a Pack's `open` does in the `RV_PACK_OPEN` tests. + #[derive(Clone, Copy)] + enum Opens { + Default, + SetsField, + RaisesError, + Panics, + } + + impl Pack for Opens { + fn tools(&self) -> Vec { + Vec::new() + } + + fn call<'a>(&'a self, _call: ToolCall<'a>) -> BoxFuture<'a, Result> { + uncalled() + } + + fn open<'a>( + &self, + lua: &LuaPrelude<'a>, + env: LuaValue<'a>, + pack_id: &str, + ) -> Result<(), LuaError> { + match self { + Opens::Default => Ok(()), + Opens::SetsField => { + let s = lua.new_string(pack_id.as_bytes())?; + lua.set_field(env, "id", s) + } + Opens::RaisesError => Err(LuaError::new("bad prelude setup")), + Opens::Panics => panic!("open boom"), + } + } + } + + unsafe extern "C" fn stub_raise(_cx: RvCx, _msg: RvStr) -> RvStatus { + RV_ERR_LUA + } + unsafe extern "C" fn stub_error_message(_cx: RvCx, out: *mut RvStr) -> RvStatus { + // SAFETY: `out` is a writable pointer in the caller's stack frame. + unsafe { *out = rv_str("stub error") }; + RV_OK + } + unsafe extern "C" fn stub_clear(_cx: RvCx) -> RvStatus { + RV_OK + } + unsafe extern "C" fn stub_mark(_cx: RvCx, out: *mut RvMark) -> RvStatus { + // SAFETY: `out` is a writable pointer in the caller's stack frame. + unsafe { *out = RvMark { bits: 1 } }; + RV_OK + } + unsafe extern "C" fn stub_release(_cx: RvCx, _mark: RvMark) -> RvStatus { + RV_OK + } + unsafe extern "C" fn stub_new_string( + _cx: RvCx, + _bytes: RvBytes, + out: *mut RvValue, + ) -> RvStatus { + // SAFETY: `out` is a writable pointer in the caller's stack frame. + unsafe { + *out = RvValue { + kind: RV_STRING, + reserved: 0, + payload: 10, + }; + } + RV_OK + } + unsafe extern "C" fn stub_string_bytes( + _cx: RvCx, + _string: RvValue, + _out: *mut RvBytes, + ) -> RvStatus { + RV_OK + } + unsafe extern "C" fn stub_new_table( + _cx: RvCx, + _l: u32, + _f: u32, + _flags: u32, + out: *mut RvValue, + ) -> RvStatus { + // SAFETY: `out` is a writable pointer in the caller's stack frame. + unsafe { + *out = RvValue { + kind: RV_TABLE, + reserved: 0, + payload: 20, + }; + } + RV_OK + } + unsafe extern "C" fn stub_table_op(_cx: RvCx, _t: RvValue) -> RvStatus { + RV_OK + } + unsafe extern "C" fn stub_is_list(_cx: RvCx, _v: RvValue, out: *mut u32) -> RvStatus { + // SAFETY: `out` is a writable pointer in the caller's stack frame. + unsafe { *out = 0 }; + RV_OK + } + unsafe extern "C" fn stub_get( + _cx: RvCx, + _o: RvValue, + _k: RvValue, + out: *mut RvValue, + ) -> RvStatus { + // SAFETY: `out` is a writable pointer in the caller's stack frame. + unsafe { *out = LuaValue::nil().raw() }; + RV_OK + } + unsafe extern "C" fn stub_get_field( + _cx: RvCx, + _o: RvValue, + _n: RvStr, + out: *mut RvValue, + ) -> RvStatus { + // SAFETY: `out` is a writable pointer in the caller's stack frame. + unsafe { *out = LuaValue::nil().raw() }; + RV_OK + } + unsafe extern "C" fn stub_set(_cx: RvCx, _o: RvValue, _k: RvValue, _v: RvValue) -> RvStatus { + RV_OK + } + unsafe extern "C" fn stub_set_field( + _cx: RvCx, + _o: RvValue, + _n: RvStr, + _v: RvValue, + ) -> RvStatus { + RV_OK + } + unsafe extern "C" fn stub_raw_len(_cx: RvCx, _t: RvValue, out: *mut i64) -> RvStatus { + // SAFETY: `out` is a writable pointer in the caller's stack frame. + unsafe { *out = 0 }; + RV_OK + } + unsafe extern "C" fn stub_set_mt(_cx: RvCx, _t: RvValue, _mt: RvValue) -> RvStatus { + RV_OK + } + unsafe extern "C" fn stub_raw_eq( + _cx: RvCx, + _a: RvValue, + _b: RvValue, + out: *mut u32, + ) -> RvStatus { + // SAFETY: `out` is a writable pointer in the caller's stack frame. + unsafe { *out = 0 }; + RV_OK + } + unsafe extern "C" fn stub_iter_begin(_cx: RvCx, _t: RvValue, out: *mut RvIter) -> RvStatus { + // SAFETY: `out` is a writable pointer in the caller's stack frame. + unsafe { *out = RvIter { bits: 1 } }; + RV_OK + } + unsafe extern "C" fn stub_iter_next( + _cx: RvCx, + _i: RvIter, + _k: *mut RvValue, + _v: *mut RvValue, + done: *mut u32, + ) -> RvStatus { + // SAFETY: `done` is a writable pointer in the caller's stack frame. + unsafe { *done = 1 }; + RV_OK + } + unsafe extern "C" fn stub_new_fn( + _cx: RvCx, + _info: *const runvil_plugin_sys::RvFunctionInfo, + _data: *mut c_void, + out: *mut RvValue, + ) -> RvStatus { + // SAFETY: `out` is a writable pointer in the caller's stack frame. + unsafe { *out = LuaValue::nil().raw() }; + RV_OK + } + unsafe extern "C" fn stub_call( + _cx: RvCx, + _c: RvValue, + _a: *const RvValue, + _na: usize, + _r: *mut RvValue, + _nr: usize, + ) -> RvStatus { + RV_OK + } + unsafe extern "C" fn stub_return_values( + _cx: RvCx, + _v: *const RvValue, + _count: usize, + ) -> RvStatus { + RV_OK + } + unsafe extern "C" fn stub_new_ud( + _cx: RvCx, + _ty: *const RvUserdataType, + _data: *mut c_void, + out: *mut RvValue, + ) -> RvStatus { + // SAFETY: `out` is a writable pointer in the caller's stack frame. + unsafe { *out = LuaValue::nil().raw() }; + RV_OK + } + unsafe extern "C" fn stub_ud_data( + _cx: RvCx, + _v: RvValue, + _ty: *const RvUserdataType, + out: *mut *mut c_void, + ) -> RvStatus { + // SAFETY: `out` is a writable pointer in the caller's stack frame. + unsafe { *out = ptr::null_mut() }; + RV_OK + } + unsafe extern "C" fn stub_get_uv( + _cx: RvCx, + _v: RvValue, + _ty: *const RvUserdataType, + _idx: u32, + out: *mut RvValue, + ) -> RvStatus { + // SAFETY: `out` is a writable pointer in the caller's stack frame. + unsafe { *out = LuaValue::nil().raw() }; + RV_OK + } + unsafe extern "C" fn stub_set_uv( + _cx: RvCx, + _v: RvValue, + _ty: *const RvUserdataType, + _idx: u32, + _item: RvValue, + ) -> RvStatus { + RV_OK + } + unsafe extern "C" fn stub_from_json( + _cx: RvCx, + _who: RvStr, + _json: RvStr, + out: *mut RvValue, + ) -> RvStatus { + // SAFETY: `out` is a writable pointer in the caller's stack frame. + unsafe { *out = LuaValue::nil().raw() }; + RV_OK + } + unsafe extern "C" fn stub_to_json( + _cx: RvCx, + _who: RvStr, + _val: RvValue, + out: *mut RvValue, + ) -> RvStatus { + // SAFETY: `out` is a writable pointer in the caller's stack frame. + unsafe { *out = LuaValue::nil().raw() }; + RV_OK + } + + static STUB_LUA: RvLua = RvLua { + size: size_field::(), + reserved: 0, + raise: stub_raise, + error_message: stub_error_message, + clear_error: stub_clear, + check_cancel: stub_clear, + mark: stub_mark, + release_to: stub_release, + new_string: stub_new_string, + string_bytes: stub_string_bytes, + new_table: stub_new_table, + mark_list: stub_table_op, + is_list: stub_is_list, + get: stub_get, + get_field: stub_get_field, + raw_get: stub_get, + set: stub_set, + set_field: stub_set_field, + raw_len: stub_raw_len, + set_metatable: stub_set_mt, + raw_equal: stub_raw_eq, + iter_begin: stub_iter_begin, + iter_next: stub_iter_next, + new_function: stub_new_fn, + call: stub_call, + return_values: stub_return_values, + new_userdata: stub_new_ud, + userdata_data: stub_ud_data, + get_user_value: stub_get_uv, + set_user_value: stub_set_uv, + from_json: stub_from_json, + to_json: stub_to_json, + }; + + #[test] + fn open_runs_sets_fields_raises_errors_and_contains_panics() { + for (pack, expected) in [ + (Opens::Default, RV_OK), + (Opens::SetsField, RV_OK), + (Opens::RaisesError, RV_ERR_LUA), + (Opens::Panics, RV_ERR_REFUSED), + ] { + let mut recorder = Recorder::default(); + let args = RvPackOpenArgs { + size: size_field::(), + reserved: 0, + ctx: (&raw mut recorder).cast(), + lua_cx: RvCx { bits: 1 }, + pack_id: rv_str("url"), + env: RvValue { + kind: RV_TABLE, + reserved: 0, + payload: 1, + }, + lua: &raw const STUB_LUA, + refuse: record_refusal, + }; + let pack_run = Box::into_raw(Box::new(PackRun { + pack: Box::new(pack), + })); + let mut call = RvCall { + size: size_field::(), + verb: RV_PACK_OPEN, + 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 and arguments follow the contract. + let status = unsafe { entry::(&raw mut call) }; + // SAFETY: `pack_run` was leaked above and is freed once here. + drop(unsafe { Box::from_raw(pack_run) }); + assert_eq!(status, expected); + if matches!(pack, Opens::Panics) { + assert_eq!( + recorder.refusals, + ["the Pack panicked while opening its prelude: open boom"] + ); + } + } + } } diff --git a/crates/runvil-plugin-sdk/src/entry/plugin.rs b/crates/runvil-plugin-sdk/src/entry/plugin.rs index b31079d..ed26aa5 100644 --- a/crates/runvil-plugin-sdk/src/entry/plugin.rs +++ b/crates/runvil-plugin-sdk/src/entry/plugin.rs @@ -93,9 +93,13 @@ unsafe fn describe(args: &RvLoadArgs) -> RvStatus { reserved: 0, name: rv_str(pack.name), description: rv_str(pack.description), - lua_prelude: RvStr { - ptr: core::ptr::null(), - len: 0, + lua_prelude: if pack.lua_prelude.is_empty() { + RvStr { + ptr: core::ptr::null(), + len: 0, + } + } else { + rv_str(pack.lua_prelude) }, }; // SAFETY: as above. @@ -228,7 +232,9 @@ mod tests { const NAME: &'static str = "two-packs"; const VERSION: &'static str = "1"; const PACKS: &'static [PackInfo] = &[ - PackInfo::new("acme/url").description("Fetch and search the web"), + PackInfo::new("acme/url") + .description("Fetch and search the web") + .lua_prelude("url = {}"), PackInfo::new("acme/mail"), ]; @@ -355,14 +361,23 @@ mod tests { #[test] fn a_plugin_inserts_each_of_its_packs_in_order() { let loaded = testing::load::().unwrap(); - let packs: Vec<(&str, &str)> = loaded + let packs: Vec<(&str, &str, &str)> = loaded .packs() .iter() - .map(|pack| (pack.name.as_str(), pack.description.as_str())) + .map(|pack| { + ( + pack.name.as_str(), + pack.description.as_str(), + pack.lua_prelude.as_str(), + ) + }) .collect(); assert_eq!( packs, - [("acme/url", "Fetch and search the web"), ("acme/mail", "")] + [ + ("acme/url", "Fetch and search the web", "url = {}"), + ("acme/mail", "", "") + ] ); } diff --git a/crates/runvil-plugin-sdk/src/lib.rs b/crates/runvil-plugin-sdk/src/lib.rs index 9c9ef8d..b5e24cb 100644 --- a/crates/runvil-plugin-sdk/src/lib.rs +++ b/crates/runvil-plugin-sdk/src/lib.rs @@ -139,6 +139,7 @@ mod entry; mod file; +mod lua; mod names; mod pack; #[cfg(any(test, feature = "test-support"))] @@ -148,6 +149,7 @@ mod tool_info; pub use entry::entry; pub use file::{DirEntry, FileError, FileErrorKind, FileFuture, FileType, Stat}; +pub use lua::{LuaError, LuaKind, LuaPrelude, LuaValue, drop_userdata}; pub use pack::{BoxFuture, Pack, PackInfo, RenderContext}; pub use runvil_plugin_sys as sys; pub use tool::{Caller, NextStep, ToolCall, ToolError, ToolErrorKind, ToolOutput, next_step}; diff --git a/crates/runvil-plugin-sdk/src/lua.rs b/crates/runvil-plugin-sdk/src/lua.rs new file mode 100644 index 0000000..ddff3e4 --- /dev/null +++ b/crates/runvil-plugin-sdk/src/lua.rs @@ -0,0 +1,992 @@ +//! Safe Rust wrappers over [`RvLua`] and [`RvCx`] for a Pack's native +//! prelude ([`Pack::open`](crate::Pack::open)) and the functions and +//! userdata it installs into a section VM. + +use std::ffi::c_void; +use std::marker::PhantomData; +use std::panic::{self, AssertUnwindSafe}; +use std::{fmt, ptr, slice}; + +use runvil_plugin_sys::{ + RV_BOOLEAN, RV_ERR_FATAL, RV_ERR_LUA, RV_ERR_MISUSE, RV_ERR_TYPE, RV_FUNCTION, RV_INTEGER, + RV_LIGHTUSERDATA, RV_MAX_VALUES, RV_NIL, RV_NULL, RV_NUMBER, RV_OK, RV_STRING, RV_TABLE, + RV_TABLE_LIST, RV_USERDATA, RvBytes, RvCx, RvIter, RvKind, RvLua, RvMark, RvStatus, RvStr, + RvUserdataType, RvValue, +}; + +use crate::entry::{contain, panic_message, rv_str, size_field}; + +/// The kind of a [`LuaValue`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum LuaKind { + /// `nil`. + Nil, + /// A boolean (`true` or `false`). + Boolean, + /// A 64-bit signed integer. + Integer, + /// A 64-bit floating-point number. + Number, + /// `json.null`. + Null, + /// A raw light userdata pointer (`*mut c_void`). + LightUserData, + /// A Lua string handle. + String, + /// A Lua table handle. + Table, + /// A Lua function handle. + Function, + /// A Lua userdata handle. + UserData, + /// A coroutine or any other Lua value handle. + Opaque, +} + +impl LuaKind { + /// Converts the contract's `raw` kind number into [`LuaKind`]. + #[must_use] + pub const fn from_raw(raw: RvKind) -> LuaKind { + match raw { + RV_NIL => LuaKind::Nil, + RV_BOOLEAN => LuaKind::Boolean, + RV_INTEGER => LuaKind::Integer, + RV_NUMBER => LuaKind::Number, + RV_NULL => LuaKind::Null, + RV_LIGHTUSERDATA => LuaKind::LightUserData, + RV_STRING => LuaKind::String, + RV_TABLE => LuaKind::Table, + RV_FUNCTION => LuaKind::Function, + RV_USERDATA => LuaKind::UserData, + _ => LuaKind::Opaque, + } + } + + /// Returns the type name the Engine's messages use for this kind, such + /// as `"string"` or `"integer"`. + #[must_use] + pub const fn type_name(self) -> &'static str { + match self { + LuaKind::Nil => "nil", + LuaKind::Boolean => "boolean", + LuaKind::Integer => "integer", + LuaKind::Number => "number", + LuaKind::Null | LuaKind::LightUserData => "lightuserdata", + LuaKind::String => "string", + LuaKind::Table => "table", + LuaKind::Function => "function", + LuaKind::UserData => "userdata", + LuaKind::Opaque => "other", + } + } +} + +/// One Lua value bound to the active [`LuaPrelude`] call `'a`. +/// +/// Scalars (`nil`, booleans, integers, floats, `json.null`, and light +/// userdata) sit in place. Strings, tables, functions, and userdata hold +/// an Engine-checked handle valid until the call returns or +/// [`LuaPrelude::release_to`] releases it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct LuaValue<'a> { + raw: RvValue, + _call: PhantomData<&'a ()>, +} + +impl<'a> LuaValue<'a> { + /// Wraps a raw [`RvValue`] for the active call `'a`. + #[must_use] + pub const fn from_raw(raw: RvValue) -> LuaValue<'a> { + LuaValue { + raw, + _call: PhantomData, + } + } + + /// Returns the underlying [`RvValue`]. + #[must_use] + pub const fn raw(self) -> RvValue { + self.raw + } + + /// `nil`. + #[must_use] + pub const fn nil() -> LuaValue<'a> { + LuaValue::from_raw(RvValue { + kind: RV_NIL, + reserved: 0, + payload: 0, + }) + } + + /// `json.null`. + #[must_use] + pub const fn null() -> LuaValue<'a> { + LuaValue::from_raw(RvValue { + kind: RV_NULL, + reserved: 0, + payload: 0, + }) + } + + /// A boolean value. + #[must_use] + pub const fn boolean(value: bool) -> LuaValue<'a> { + LuaValue::from_raw(RvValue { + kind: RV_BOOLEAN, + reserved: 0, + payload: value as u64, + }) + } + + /// A 64-bit integer value. + #[must_use] + #[expect( + clippy::cast_sign_loss, + reason = "the bit pattern of i64 is stored losslessly in u64" + )] + pub const fn integer(value: i64) -> LuaValue<'a> { + LuaValue::from_raw(RvValue { + kind: RV_INTEGER, + reserved: 0, + payload: value as u64, + }) + } + + /// A 64-bit floating-point number value. + #[must_use] + pub const fn number(value: f64) -> LuaValue<'a> { + LuaValue::from_raw(RvValue { + kind: RV_NUMBER, + reserved: 0, + payload: value.to_bits(), + }) + } + + /// A raw light userdata pointer value. + #[must_use] + pub fn light_userdata(ptr: *mut c_void) -> LuaValue<'a> { + LuaValue::from_raw(RvValue { + kind: RV_LIGHTUSERDATA, + reserved: 0, + payload: ptr.expose_provenance() as u64, + }) + } + + /// Returns this value's [`LuaKind`]. + #[must_use] + pub const fn kind(self) -> LuaKind { + LuaKind::from_raw(self.raw.kind) + } + + /// Returns `true` when this value is `nil`. + #[must_use] + pub const fn is_nil(self) -> bool { + self.raw.kind == RV_NIL + } + + /// Returns `true` when this value is `json.null`. + #[must_use] + pub const fn is_null(self) -> bool { + self.raw.kind == RV_NULL + } + + /// Returns the boolean when `kind` is [`LuaKind::Boolean`]. + #[must_use] + pub const fn as_boolean(self) -> Option { + if self.raw.kind == RV_BOOLEAN { + Some(self.raw.payload != 0) + } else { + None + } + } + + /// Returns the integer when `kind` is [`LuaKind::Integer`]. + #[must_use] + #[expect( + clippy::cast_possible_wrap, + reason = "restores the i64 bit pattern stored in payload" + )] + pub const fn as_integer(self) -> Option { + if self.raw.kind == RV_INTEGER { + Some(self.raw.payload as i64) + } else { + None + } + } + + /// Returns the float when `kind` is [`LuaKind::Number`]. + #[must_use] + pub const fn as_number(self) -> Option { + if self.raw.kind == RV_NUMBER { + Some(f64::from_bits(self.raw.payload)) + } else { + None + } + } + + /// Returns the light userdata pointer when `kind` is + /// [`LuaKind::LightUserData`]. + #[must_use] + #[expect( + clippy::cast_possible_truncation, + reason = "pointer provenance fits in usize on target platforms" + )] + pub fn as_light_userdata(self) -> Option<*mut c_void> { + if self.raw.kind == RV_LIGHTUSERDATA { + Some(ptr::with_exposed_provenance_mut(self.raw.payload as usize)) + } else { + None + } + } +} + +/// Why an [`RvLua`] operation failed. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LuaError { + status: RvStatus, + message: String, +} + +impl LuaError { + /// Creates an author error that raises `message` in Lua (`RV_ERR_LUA`). + #[must_use] + pub fn new(message: impl Into) -> LuaError { + LuaError { + status: RV_ERR_LUA, + message: message.into(), + } + } + + /// Creates an error from a non-OK `status` and `message`. + #[must_use] + pub fn from_status(status: RvStatus, message: impl Into) -> LuaError { + LuaError { + status, + message: message.into(), + } + } + + /// Returns the contract status code (`RV_ERR_LUA`, `RV_ERR_FATAL`, + /// `RV_ERR_TYPE`, or `RV_ERR_MISUSE`). + #[must_use] + pub const fn status(&self) -> RvStatus { + self.status + } + + /// Returns `true` when the failure is a sticky fatal error + /// (`RV_ERR_FATAL`, memory limit or run cancellation). + #[must_use] + pub const fn is_fatal(&self) -> bool { + self.status == RV_ERR_FATAL + } + + /// Returns the error message. + #[must_use] + pub fn message(&self) -> &str { + &self.message + } +} + +impl fmt::Display for LuaError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for LuaError {} + +/// One active Lua call context: lends safe methods over the Engine's +/// [`RvLua`] table during [`Pack::open`](crate::Pack::open) or an +/// installed function or userdata callback. +#[derive(Clone, Copy)] +pub struct LuaPrelude<'a> { + cx: RvCx, + lua: &'a RvLua, +} + +impl fmt::Debug for LuaPrelude<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("LuaPrelude") + .field("cx", &self.cx) + .finish_non_exhaustive() + } +} + +impl<'a> LuaPrelude<'a> { + /// Wraps the call context `cx` and the Host's `lua` table. + /// + /// # Safety + /// `lua` must point to a valid [`RvLua`] table for `'a`, and `cx` must + /// be the active call context on the current thread. + #[must_use] + pub unsafe fn from_raw(cx: RvCx, lua: *const RvLua) -> LuaPrelude<'a> { + LuaPrelude { + cx, + // SAFETY: the caller guarantees `lua` is valid for `'a`. + lua: unsafe { &*lua }, + } + } + + /// Returns the raw [`RvCx`] token of this call. + #[must_use] + pub const fn raw_cx(&self) -> RvCx { + self.cx + } + + /// Returns the raw [`RvLua`] table of this call. + #[must_use] + pub const fn raw_lua(&self) -> &'a RvLua { + self.lua + } + + /// Raises `error` on this call context and returns its [`RvStatus`] + /// for an `extern "C"` callback to return to the Engine. + #[must_use] + pub fn finish(&self, result: Result<(), LuaError>) -> RvStatus { + match result { + Ok(()) => RV_OK, + Err(error) => { + if !error.message.is_empty() && error.status == RV_ERR_LUA { + // SAFETY: `self.cx` is the active call and the string + // outlives `raise`. + let status = unsafe { (self.lua.raise)(self.cx, rv_str(&error.message)) }; + if status != RV_OK { + return status; + } + } + if error.status == RV_OK { + RV_ERR_LUA + } else { + error.status + } + } + } + } + + /// Checks `status`, reading the held `error_message` on failure. + fn check(&self, status: RvStatus) -> Result<(), LuaError> { + if status == RV_OK { + return Ok(()); + } + let mut msg = RvStr { + ptr: ptr::null(), + len: 0, + }; + // SAFETY: `self.cx` is active and `msg` is writable. + let text = if unsafe { (self.lua.error_message)(self.cx, &raw mut msg) } == RV_OK + && msg.len > 0 + && !msg.ptr.is_null() + { + // SAFETY: the Engine keeps the error message bytes valid until + // `clear_error` or the end of the call. + let bytes = unsafe { slice::from_raw_parts(msg.ptr.cast::(), msg.len) }; + String::from_utf8_lossy(bytes).into_owned() + } else { + format!("lua status {status}") + }; + Err(LuaError::from_status(status, text)) + } + + /// Clears a held non-fatal error on this context so later calls can + /// proceed. + /// + /// # Errors + /// Returns [`LuaError`] with `RV_ERR_FATAL` when a fatal error is held. + pub fn clear_error(&self) -> Result<(), LuaError> { + // SAFETY: `self.cx` is the active call context. + let status = unsafe { (self.lua.clear_error)(self.cx) }; + self.check(status) + } + + /// Polls whether the run has been canceled. + /// + /// # Errors + /// Returns [`LuaError`] with `RV_ERR_FATAL` when the run is canceled. + pub fn check_cancel(&self) -> Result<(), LuaError> { + // SAFETY: `self.cx` is the active call context. + let status = unsafe { (self.lua.check_cancel)(self.cx) }; + self.check(status) + } + + /// Marks the current position in the call's handle arena. + /// + /// # Errors + /// Returns [`LuaError`] if the arena mark fails. + pub fn mark(&self) -> Result { + let mut out = RvMark { bits: 0 }; + // SAFETY: `self.cx` is active and `out` is writable. + let status = unsafe { (self.lua.mark)(self.cx, &raw mut out) }; + self.check(status)?; + Ok(out) + } + + /// Releases every handle created after `mark`. + /// + /// # Errors + /// Returns [`LuaError`] if `mark` does not belong to this call. + pub fn release_to(&self, mark: RvMark) -> Result<(), LuaError> { + // SAFETY: `self.cx` is the active call context. + let status = unsafe { (self.lua.release_to)(self.cx, mark) }; + self.check(status) + } + + /// Copies `bytes` into a new Lua string. + /// + /// # Errors + /// Returns [`LuaError`] if the allocation fails. + pub fn new_string(&self, bytes: impl AsRef<[u8]>) -> Result, LuaError> { + let slice = bytes.as_ref(); + let raw_bytes = RvBytes { + ptr: slice.as_ptr(), + len: slice.len(), + }; + let mut out = LuaValue::nil().raw(); + // SAFETY: `self.cx` is active and `slice` outlives `new_string`. + let status = unsafe { (self.lua.new_string)(self.cx, raw_bytes, &raw mut out) }; + self.check(status)?; + Ok(LuaValue::from_raw(out)) + } + + /// Borrows the byte slice of a Lua string handle, valid while `string` + /// remains live in this call's arena. + /// + /// # Errors + /// Returns [`LuaError`] (`RV_ERR_TYPE`) when `string` is not an + /// `RV_STRING`. + pub fn string_bytes(&self, string: LuaValue<'a>) -> Result<&'a [u8], LuaError> { + let mut out = RvBytes { + ptr: ptr::null(), + len: 0, + }; + // SAFETY: `self.cx` is active and `out` is writable. + let status = unsafe { (self.lua.string_bytes)(self.cx, string.raw(), &raw mut out) }; + self.check(status)?; + if out.len == 0 || out.ptr.is_null() { + return Ok(&[]); + } + // SAFETY: the Engine keeps the string's bytes valid while its + // handle is live in `'a`. + Ok(unsafe { slice::from_raw_parts(out.ptr, out.len) }) + } + + /// Borrows a Lua string as UTF-8 text. + /// + /// # Errors + /// Returns [`LuaError`] when `string` is not a string or is not valid + /// UTF-8. + pub fn string_str(&self, string: LuaValue<'a>) -> Result<&'a str, LuaError> { + let bytes = self.string_bytes(string)?; + std::str::from_utf8(bytes).map_err(|_| LuaError::new("string is not valid UTF-8")) + } + + /// Creates a new Lua table, marking it as a list when `is_list` is + /// `true`. + /// + /// # Errors + /// Returns [`LuaError`] if the allocation fails. + pub fn new_table( + &self, + list_hint: u32, + field_hint: u32, + is_list: bool, + ) -> Result, LuaError> { + let flags = if is_list { RV_TABLE_LIST } else { 0 }; + let mut out = LuaValue::nil().raw(); + // SAFETY: `self.cx` is active and `out` is writable. + let status = + unsafe { (self.lua.new_table)(self.cx, list_hint, field_hint, flags, &raw mut out) }; + self.check(status)?; + Ok(LuaValue::from_raw(out)) + } + + /// Marks `table` as a list with `json.array(t)`'s rules. + /// + /// # Errors + /// Returns [`LuaError`] if `table` is not a table or already has + /// another metatable. + pub fn mark_list(&self, table: LuaValue<'a>) -> Result<(), LuaError> { + // SAFETY: `self.cx` is active. + let status = unsafe { (self.lua.mark_list)(self.cx, table.raw()) }; + self.check(status) + } + + /// Returns whether `value` is a table marked as a list. + /// + /// # Errors + /// Returns [`LuaError`] if the call fails. + pub fn is_list(&self, value: LuaValue<'a>) -> Result { + let mut out = 0_u32; + // SAFETY: `self.cx` is active and `out` is writable. + let status = unsafe { (self.lua.is_list)(self.cx, value.raw(), &raw mut out) }; + self.check(status)?; + Ok(out != 0) + } + + /// Reads `object[key]`, running `__index` as Lua does. + /// + /// # Errors + /// Returns [`LuaError`] if `object` cannot be indexed or `__index` + /// raises. + pub fn get(&self, object: LuaValue<'a>, key: LuaValue<'a>) -> Result, LuaError> { + let mut out = LuaValue::nil().raw(); + // SAFETY: `self.cx` is active and `out` is writable. + let status = unsafe { (self.lua.get)(self.cx, object.raw(), key.raw(), &raw mut out) }; + self.check(status)?; + Ok(LuaValue::from_raw(out)) + } + + /// Reads `object[name]`, running `__index` as Lua does. + /// + /// # Errors + /// Returns [`LuaError`] if `object` cannot be indexed or `__index` + /// raises. + pub fn get_field(&self, object: LuaValue<'a>, name: &str) -> Result, LuaError> { + let mut out = LuaValue::nil().raw(); + // SAFETY: `self.cx` is active and `name` outlives `get_field`. + let status = + unsafe { (self.lua.get_field)(self.cx, object.raw(), rv_str(name), &raw mut out) }; + self.check(status)?; + Ok(LuaValue::from_raw(out)) + } + + /// Reads `table[key]` without metamethods. + /// + /// # Errors + /// Returns [`LuaError`] if `table` is not a table. + pub fn raw_get( + &self, + table: LuaValue<'a>, + key: LuaValue<'a>, + ) -> Result, LuaError> { + let mut out = LuaValue::nil().raw(); + // SAFETY: `self.cx` is active and `out` is writable. + let status = unsafe { (self.lua.raw_get)(self.cx, table.raw(), key.raw(), &raw mut out) }; + self.check(status)?; + Ok(LuaValue::from_raw(out)) + } + + /// Sets `object[key] = value`, running `__newindex` as Lua does. + /// + /// # Errors + /// Returns [`LuaError`] if the assignment is refused or raises. + pub fn set( + &self, + object: LuaValue<'a>, + key: LuaValue<'a>, + value: LuaValue<'a>, + ) -> Result<(), LuaError> { + // SAFETY: `self.cx` is active. + let status = unsafe { (self.lua.set)(self.cx, object.raw(), key.raw(), value.raw()) }; + self.check(status) + } + + /// Sets `object[name] = value`, running `__newindex` as Lua does. + /// + /// # Errors + /// Returns [`LuaError`] if the assignment is refused or raises. + pub fn set_field( + &self, + object: LuaValue<'a>, + name: &str, + value: LuaValue<'a>, + ) -> Result<(), LuaError> { + // SAFETY: `self.cx` is active and `name` outlives `set_field`. + let status = + unsafe { (self.lua.set_field)(self.cx, object.raw(), rv_str(name), value.raw()) }; + self.check(status) + } + + /// Returns `table`'s raw border length without running `__len`. + /// + /// # Errors + /// Returns [`LuaError`] if `table` is not a table. + pub fn raw_len(&self, table: LuaValue<'a>) -> Result { + let mut out = 0_i64; + // SAFETY: `self.cx` is active and `out` is writable. + let status = unsafe { (self.lua.raw_len)(self.cx, table.raw(), &raw mut out) }; + self.check(status)?; + Ok(out) + } + + /// Sets `metatable` (`RV_TABLE` or `RV_NIL`) on `table`. + /// + /// # Errors + /// Returns [`LuaError`] if `table`'s metatable is protected or + /// `metatable` contains `__gc`, `__mode`, or `__close`. + pub fn set_metatable( + &self, + table: LuaValue<'a>, + metatable: LuaValue<'a>, + ) -> Result<(), LuaError> { + // SAFETY: `self.cx` is active. + let status = unsafe { (self.lua.set_metatable)(self.cx, table.raw(), metatable.raw()) }; + self.check(status) + } + + /// Compares `a` and `b` without running `__eq`. + /// + /// # Errors + /// Returns [`LuaError`] if either handle is invalid. + pub fn raw_equal(&self, a: LuaValue<'a>, b: LuaValue<'a>) -> Result { + let mut out = 0_u32; + // SAFETY: `self.cx` is active and `out` is writable. + let status = unsafe { (self.lua.raw_equal)(self.cx, a.raw(), b.raw(), &raw mut out) }; + self.check(status)?; + Ok(out != 0) + } + + /// Starts a deterministic walk of `table`'s keys in the Engine's + /// `pairs` order. + /// + /// # Errors + /// Returns [`LuaError`] if `table` is not a table or holds an + /// unorderable key (`table`, `function`, `userdata`, or `thread`). + pub fn iter_begin(&self, table: LuaValue<'a>) -> Result { + let mut out = RvIter { bits: 0 }; + // SAFETY: `self.cx` is active and `out` is writable. + let status = unsafe { (self.lua.iter_begin)(self.cx, table.raw(), &raw mut out) }; + self.check(status)?; + Ok(out) + } + + /// Advances `iter` to the next live `(key, value)` pair, or returns + /// `Ok(None)` at the end of the walk. + /// + /// # Errors + /// Returns [`LuaError`] if `iter` is invalid. + pub fn iter_next( + &self, + iter: RvIter, + ) -> Result, LuaValue<'a>)>, LuaError> { + let mut key = LuaValue::nil().raw(); + let mut value = LuaValue::nil().raw(); + let mut done = 0_u32; + // SAFETY: `self.cx` is active and the out-pointers are writable. + let status = unsafe { + (self.lua.iter_next)(self.cx, iter, &raw mut key, &raw mut value, &raw mut done) + }; + self.check(status)?; + if done != 0 { + Ok(None) + } else { + Ok(Some((LuaValue::from_raw(key), LuaValue::from_raw(value)))) + } + } + + /// Creates a Lua function named `name` backed by the closure `f`, which + /// is dropped when Lua collects the function or the VM closes. + /// + /// # Errors + /// Returns [`LuaError`] if `name` is invalid or the allocation fails. + pub fn new_function(&self, name: &str, f: F) -> Result, LuaError> + where + F: for<'c> Fn(&LuaPrelude<'c>, &[LuaValue<'c>]) -> Result>, LuaError> + + Send + + Sync + + 'static, + { + unsafe extern "C" fn trampoline( + cx: RvCx, + lua: *const RvLua, + data: *mut c_void, + args: *const RvValue, + nargs: usize, + ) -> RvStatus + where + F: for<'c> Fn(&LuaPrelude<'c>, &[LuaValue<'c>]) -> Result>, LuaError> + + Send + + Sync + + 'static, + { + // SAFETY: the Engine passes a valid `cx`, `lua`, `data`, and + // `args` slice for the duration of this call. + let prelude = unsafe { LuaPrelude::from_raw(cx, lua) }; + // SAFETY: `data` is the `Box` leaked in `new_function`. + let closure = unsafe { &*data.cast::() }; + let slice = if nargs == 0 || args.is_null() { + &[] + } else { + // SAFETY: `LuaValue` is `#[repr(transparent)]`-layout-identical + // to `RvValue` (`PhantomData` is zero-sized). + unsafe { slice::from_raw_parts(args.cast::>(), nargs) } + }; + let outcome = panic::catch_unwind(AssertUnwindSafe(|| closure(&prelude, slice))); + match outcome { + Ok(Ok(values)) => { + if values.is_empty() { + return RV_OK; + } + prelude.finish(prelude.return_values(&values)) + } + Ok(Err(err)) => prelude.finish(Err(err)), + Err(payload) => { + let message = format!("Pack function panicked: {}", panic_message(&*payload)); + contain(move || drop(payload)); + prelude.finish(Err(LuaError::new(message))) + } + } + } + + unsafe extern "C" fn drop_box(data: *mut c_void) { + if !data.is_null() { + // SAFETY: `data` came from `Box::into_raw` below and is + // freed once by the Engine. + let boxed = unsafe { Box::from_raw(data.cast::()) }; + contain(move || drop(boxed)); + } + } + + let info = runvil_plugin_sys::RvFunctionInfo { + size: size_field::(), + reserved: 0, + name: rv_str(name), + call: trampoline::, + drop_fn: Some(drop_box::), + }; + let data = Box::into_raw(Box::new(f)).cast::(); + let mut out = LuaValue::nil().raw(); + // SAFETY: `self.cx` is active, `info` is live for the call, and + // ownership of `data` transfers to `new_function` on every path. + let status = + unsafe { (self.lua.new_function)(self.cx, &raw const info, data, &raw mut out) }; + self.check(status)?; + Ok(LuaValue::from_raw(out)) + } + + /// Calls `callee` with `args` and returns `nresults` results. + /// + /// # Errors + /// Returns [`LuaError`] if `callee` raises, yields, or `args` / + /// `nresults` exceeds [`RV_MAX_VALUES`]. + pub fn call( + &self, + callee: LuaValue<'a>, + args: &[LuaValue<'a>], + nresults: usize, + ) -> Result>, LuaError> { + if args.len() > RV_MAX_VALUES || nresults > RV_MAX_VALUES { + return Err(LuaError::from_status( + RV_ERR_MISUSE, + "more than 255 values passed or requested", + )); + } + let mut results = vec![LuaValue::nil().raw(); nresults]; + let args_ptr = if args.is_empty() { + ptr::null() + } else { + args.as_ptr().cast::() + }; + let results_ptr = if nresults == 0 { + ptr::null_mut() + } else { + results.as_mut_ptr() + }; + // SAFETY: `self.cx` is active and both slices are valid for the + // call. + let status = unsafe { + (self.lua.call)( + self.cx, + callee.raw(), + args_ptr, + args.len(), + results_ptr, + nresults, + ) + }; + self.check(status)?; + Ok(results.into_iter().map(LuaValue::from_raw).collect()) + } + + /// Sets the return values of the current Pack function call. + /// + /// # Errors + /// Returns [`LuaError`] if called inside `open` or with more than + /// [`RV_MAX_VALUES`] values. + pub fn return_values(&self, values: &[LuaValue<'a>]) -> Result<(), LuaError> { + let ptr = if values.is_empty() { + ptr::null() + } else { + values.as_ptr().cast::() + }; + // SAFETY: `self.cx` is active and `values` is valid for the call. + let status = unsafe { (self.lua.return_values)(self.cx, ptr, values.len()) }; + self.check(status) + } + + /// Creates a new userdata instance of `ty` owning `value` (allocated on + /// the heap and freed by `ty->drop_fn`). + /// + /// # Safety + /// `ty` must point to a static [`RvUserdataType`] whose `drop_fn` + /// frees a `Box` (or is `Some(drop_userdata::)`) and whose + /// callbacks expect `data` to be `*mut T`. + /// + /// # Errors + /// Returns [`LuaError`] if the allocation fails. + pub unsafe fn new_userdata( + &self, + ty: &'static RvUserdataType, + value: T, + ) -> Result, LuaError> { + let data = Box::into_raw(Box::new(value)).cast::(); + let mut out = LuaValue::nil().raw(); + // SAFETY: `self.cx` is active, `ty` is `'static`, and ownership of + // `data` passes to the Engine on every path. + let status = + unsafe { (self.lua.new_userdata)(self.cx, ptr::from_ref(ty), data, &raw mut out) }; + self.check(status)?; + Ok(LuaValue::from_raw(out)) + } + + /// Borrows the `T` inside a userdata `value` of type `ty`. + /// + /// # Safety + /// `ty` must be the exact [`RvUserdataType`] used to create `T` + /// instances with [`new_userdata`](Self::new_userdata), and no mutable + /// reference to the same instance may be live at the same time. + /// + /// # Errors + /// Returns [`LuaError`] (`RV_ERR_TYPE`) if `value` is not an instance + /// of `ty`. + pub unsafe fn userdata_ref( + &self, + value: LuaValue<'a>, + ty: &'static RvUserdataType, + ) -> Result<&'a T, LuaError> { + let mut ptr: *mut c_void = ptr::null_mut(); + // SAFETY: `self.cx` is active and `ptr` is writable. + let status = unsafe { + (self.lua.userdata_data)(self.cx, value.raw(), ptr::from_ref(ty), &raw mut ptr) + }; + self.check(status)?; + if ptr.is_null() { + return Err(LuaError::from_status( + RV_ERR_TYPE, + "userdata pointer is NULL", + )); + } + // SAFETY: the caller guarantees `ty` holds a boxed `T` valid for `'a`. + Ok(unsafe { &*ptr.cast::() }) + } + + /// Reads user-value slot `index` on a userdata `value` of type `ty`. + /// + /// # Errors + /// Returns [`LuaError`] if `value` is not an instance of `ty` or + /// `index >= ty.user_values`. + pub fn user_value( + &self, + value: LuaValue<'a>, + ty: &'static RvUserdataType, + index: u32, + ) -> Result, LuaError> { + let mut out = LuaValue::nil().raw(); + // SAFETY: `self.cx` is active and `out` is writable. + let status = unsafe { + (self.lua.get_user_value)(self.cx, value.raw(), ptr::from_ref(ty), index, &raw mut out) + }; + self.check(status)?; + Ok(LuaValue::from_raw(out)) + } + + /// Sets user-value slot `index` on a userdata `value` of type `ty` to + /// `item`. + /// + /// # Errors + /// Returns [`LuaError`] if `value` is not an instance of `ty` or + /// `index >= ty.user_values`. + pub fn set_user_value( + &self, + value: LuaValue<'a>, + ty: &'static RvUserdataType, + index: u32, + item: LuaValue<'a>, + ) -> Result<(), LuaError> { + // SAFETY: `self.cx` is active. + let status = unsafe { + (self.lua.set_user_value)(self.cx, value.raw(), ptr::from_ref(ty), index, item.raw()) + }; + self.check(status) + } + + /// Parses `json` into a Lua value using the Engine's `json.decode` + /// rules, prefixing any error with `who`. + /// + /// # Errors + /// Returns [`LuaError`] if `json` is invalid or exceeds the Engine's + /// limits. + pub fn from_json(&self, who: &str, json: &str) -> Result, LuaError> { + let mut out = LuaValue::nil().raw(); + // SAFETY: `self.cx` is active and `who`/`json` outlive `from_json`. + let status = + unsafe { (self.lua.from_json)(self.cx, rv_str(who), rv_str(json), &raw mut out) }; + self.check(status)?; + Ok(LuaValue::from_raw(out)) + } + + /// Encodes `value` as a JSON Lua string using the Engine's + /// `json.encode` rules (reading through Engine views), prefixing any + /// error with `who`. + /// + /// # Errors + /// Returns [`LuaError`] if `value` cannot be encoded as JSON. + pub fn to_json(&self, who: &str, value: LuaValue<'a>) -> Result, LuaError> { + let mut out = LuaValue::nil().raw(); + // SAFETY: `self.cx` is active and `who` outlives `to_json`. + let status = unsafe { (self.lua.to_json)(self.cx, rv_str(who), value.raw(), &raw mut out) }; + self.check(status)?; + Ok(LuaValue::from_raw(out)) + } +} + +/// Drops a `Box` userdata payload allocated by +/// [`LuaPrelude::new_userdata`], catching any panic in `T`'s `Drop`. +/// +/// # Safety +/// `data` must be NULL or a pointer returned by `Box::into_raw(Box::::new(...))`, +/// called at most once. +pub unsafe extern "C" fn drop_userdata(data: *mut c_void) { + if !data.is_null() { + // SAFETY: the caller guarantees `data` came from `Box::into_raw` + // for `T` and is freed once. + let boxed = unsafe { Box::from_raw(data.cast::()) }; + contain(move || drop(boxed)); + } +} + +#[cfg(test)] +mod tests { + use std::ffi::c_void; + + use super::{LuaError, LuaKind, LuaValue}; + use runvil_plugin_sys::{RV_ERR_FATAL, RV_ERR_LUA}; + + #[test] + fn scalar_values_round_trip_their_kinds_and_payloads() { + assert!(LuaValue::nil().is_nil()); + assert_eq!(LuaValue::nil().kind(), LuaKind::Nil); + assert!(LuaValue::null().is_null()); + assert_eq!(LuaValue::null().kind(), LuaKind::Null); + assert_eq!(LuaValue::boolean(true).as_boolean(), Some(true)); + assert_eq!(LuaValue::boolean(false).as_boolean(), Some(false)); + assert_eq!(LuaValue::integer(-42).as_integer(), Some(-42)); + assert_eq!(LuaValue::number(3.25).as_number(), Some(3.25)); + let anchor = 7_u32; + let ptr = (&raw const anchor).cast_mut().cast::(); + assert_eq!(LuaValue::light_userdata(ptr).as_light_userdata(), Some(ptr)); + assert_eq!(LuaKind::Integer.type_name(), "integer"); + assert_eq!(LuaKind::LightUserData.type_name(), "lightuserdata"); + } + + #[test] + fn lua_error_tracks_its_status_and_fatal_flag() { + let err = LuaError::new("bad input"); + assert_eq!(err.status(), RV_ERR_LUA); + assert!(!err.is_fatal()); + assert_eq!(err.to_string(), "bad input"); + let fatal = LuaError::from_status(RV_ERR_FATAL, "out of memory"); + assert!(fatal.is_fatal()); + } +} diff --git a/crates/runvil-plugin-sdk/src/names.rs b/crates/runvil-plugin-sdk/src/names.rs index 6d00caf..1383dab 100644 --- a/crates/runvil-plugin-sdk/src/names.rs +++ b/crates/runvil-plugin-sdk/src/names.rs @@ -3,7 +3,7 @@ //! [`entry`](crate::entry) can check a Plugin's constants when it is //! compiled. -use runvil_plugin_sys::{RV_MAX_LINE, RV_MAX_NAME}; +use runvil_plugin_sys::{RV_MAX_LINE, RV_MAX_NAME, RV_MAX_TOOL_TEXT}; /// Whether `name` is one name segment the Harness accepts: 1 to 64 bytes /// of lowercase ASCII letters, digits, `-`, `_`, and `.`. @@ -68,6 +68,11 @@ pub(crate) const fn is_valid_description(description: &str) -> bool { description.len() <= RV_MAX_LINE && !has_control(description) } +/// Whether `lua_prelude` fits within the contract's 65536-byte limit. +pub(crate) const fn is_valid_lua_prelude(lua_prelude: &str) -> bool { + lua_prelude.len() <= RV_MAX_TOOL_TEXT +} + /// Whether `text` holds a control character, which `char::is_control` /// defines as U+0000 to U+001F and U+007F to U+009F. In UTF-8 those are /// the bytes below 0x20, 0x7F, and 0xC2 followed by 0x80 to 0x9F. diff --git a/crates/runvil-plugin-sdk/src/pack.rs b/crates/runvil-plugin-sdk/src/pack.rs index 3fd7ee4..db018cd 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::lua::{LuaError, LuaPrelude, LuaValue}; use crate::tool::{ToolCall, ToolError, ToolOutput}; use crate::{Refusal, ToolInfo}; @@ -29,15 +30,19 @@ pub struct PackInfo { /// One line saying what the Pack offers: at most 1024 bytes with no /// control characters. Empty unless set. pub description: &'static str, + /// Optional Lua source run after [`Pack::open`] in the Pack's prelude + /// environment, at most 65536 bytes. Empty unless set. + pub lua_prelude: &'static str, } impl PackInfo { - /// Names the Pack `name`, with an empty description. + /// Names the Pack `name`, with an empty description and no Lua prelude. #[must_use] pub const fn new(name: &'static str) -> PackInfo { PackInfo { name, description: "", + lua_prelude: "", } } @@ -49,6 +54,16 @@ impl PackInfo { ..self } } + + /// Sets the Lua source run after [`Pack::open`] in each section VM of a + /// prompt that declares the Pack. + #[must_use] + pub const fn lua_prelude(self, lua_prelude: &'static str) -> PackInfo { + PackInfo { + lua_prelude, + ..self + } + } } /// One run's instance of a Pack: the tools it offers and the calls it @@ -151,6 +166,26 @@ pub trait Pack: Send + Sync + 'static { let _ = cx; Ok(offered) } + + /// Runs the Pack's native prelude in a section VM of a prompt that + /// declares the Pack under `uses:`. + /// + /// Every field set on `env` (the Pack's prelude environment table) + /// becomes a global in the section VM once this method and any + /// [`PackInfo::lua_prelude`] finish. The default does nothing. + /// + /// # Errors + /// Returns a [`LuaError`] when a Lua operation fails or the prelude + /// raises an error. + fn open<'a>( + &self, + lua: &LuaPrelude<'a>, + env: LuaValue<'a>, + pack_id: &str, + ) -> Result<(), LuaError> { + let _ = (lua, env, pack_id); + Ok(()) + } } /// What a [`Pack`] learns about the section entry it renders for, in diff --git a/crates/runvil-plugin-sdk/src/testing.rs b/crates/runvil-plugin-sdk/src/testing.rs index 0c31200..2da7d6e 100644 --- a/crates/runvil-plugin-sdk/src/testing.rs +++ b/crates/runvil-plugin-sdk/src/testing.rs @@ -286,6 +286,8 @@ pub struct InsertedPack { pub name: String, /// The line saying what the Pack offers. pub description: String, + /// The optional Lua source run after `RV_PACK_OPEN`, empty when unset. + pub lua_prelude: String, } /// One run's instance of a Pack. Dropping it sends `RV_PACK_DELETE`. It diff --git a/crates/runvil-plugin-sdk/src/testing/load.rs b/crates/runvil-plugin-sdk/src/testing/load.rs index 30a9aec..733b4ea 100644 --- a/crates/runvil-plugin-sdk/src/testing/load.rs +++ b/crates/runvil-plugin-sdk/src/testing/load.rs @@ -5,7 +5,7 @@ use std::ffi::c_void; use runvil_plugin_sys::{ - RV_MAX_LINE, RV_MAX_NAME, RV_OK, RvPackInfo, RvPluginInfo, RvStatus, RvStr, + RV_MAX_LINE, RV_MAX_NAME, RV_MAX_TOOL_TEXT, RV_OK, RvPackInfo, RvPluginInfo, RvStatus, RvStr, }; use super::InsertedPack; @@ -20,6 +20,7 @@ const PACK_INFO: Shape = shape!("insert_pack", "info", "RvPackInfo"); /// Two name segments and the `/` between them. const PACK_NAME: Field = field!("the Pack's name", 129, 2 * RV_MAX_NAME + 1); const PACK_DESCRIPTION: Field = field!("the Pack's description", 1024, RV_MAX_LINE); +const PACK_LUA_PRELUDE: Field = field!("the Pack's Lua prelude", 65536, RV_MAX_TOOL_TEXT); /// What a zero `reserved` field holding anything else is called. const RESERVED: &str = "the info's reserved field is not zero"; @@ -88,7 +89,13 @@ pub(super) unsafe extern "C" fn insert_pack(ctx: *mut c_void, info: *const RvPac if has_control(&description) { return Err("the Pack's description has a control character"); } - session.packs.push(InsertedPack { name, description }); + // SAFETY: as above. + let lua_prelude = unsafe { PACK_LUA_PRELUDE.read(info.lua_prelude) }?; + session.packs.push(InsertedPack { + name, + description, + lua_prelude, + }); Ok(RV_OK) }) } From f9d1ecf284d873d8306544e756653b6852dc4249 Mon Sep 17 00:00:00 2001 From: Vinnie Falco Date: Wed, 2 Dec 2026 19:20:24 -0800 Subject: [PATCH 4/4] Address PR review findings in LuaPrelude and contract docs Tighten LuaPrelude memory safety, panic containment, and RV_PACK_OPEN default handling across unvil-plugin-sdk and unvil-plugin-sys. - Mark LuaValue #[repr(transparent)] over RvValue, and return owned Vec and String from LuaPrelude::string_bytes and LuaPrelude::string_str so elease_to cannot invalidate a borrowed string slice. - Forget secondary panic payloads caught inside contain so a panicking destructor on a panic payload cannot unwind across the C boundary. - Default Pack::open to RV_ERR_UNSUPPORTED when a Pack defines no native prelude, and clarify RV_ERR_TYPE, RvDrop, and aw_equal in unvil-plugin-sys and unvil_plugin.h. Plan: /plan/2026-12-02-3-native-preludes.plan.md --- crates/runvil-plugin-sdk/src/entry.rs | 8 ++++-- crates/runvil-plugin-sdk/src/entry/pack.rs | 26 +++++++++++++++++-- crates/runvil-plugin-sdk/src/lua.rs | 20 +++++++------- crates/runvil-plugin-sdk/src/pack.rs | 9 +++++-- .../runvil-plugin-sys/include/runvil_plugin.h | 12 +++++---- crates/runvil-plugin-sys/src/lib.rs | 17 +++++++----- plan/2026-12-02-3-native-preludes.plan.md | 2 +- 7 files changed, 65 insertions(+), 29 deletions(-) diff --git a/crates/runvil-plugin-sdk/src/entry.rs b/crates/runvil-plugin-sdk/src/entry.rs index 4ef2d7e..5e6cdac 100644 --- a/crates/runvil-plugin-sdk/src/entry.rs +++ b/crates/runvil-plugin-sdk/src/entry.rs @@ -195,9 +195,13 @@ unsafe fn refuse( } /// Runs `f`, which drops something the Plugin owns, and keeps a panic in -/// it from unwinding across the C boundary. +/// it from unwinding across the C boundary. If `f` panics, the panic +/// payload itself is forgotten so a destructor on the payload that also +/// panics cannot unwind out of `contain`. pub(crate) fn contain(f: impl FnOnce()) { - let _panicked = panic::catch_unwind(AssertUnwindSafe(f)); + if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(f)) { + std::mem::forget(payload); + } } /// The text of a panic's payload, when it has one. diff --git a/crates/runvil-plugin-sdk/src/entry/pack.rs b/crates/runvil-plugin-sdk/src/entry/pack.rs index 61c12ae..44073c9 100644 --- a/crates/runvil-plugin-sdk/src/entry/pack.rs +++ b/crates/runvil-plugin-sdk/src/entry/pack.rs @@ -825,6 +825,15 @@ mod tests { SetsField, RaisesError, Panics, + PanicsWithRecursiveBomb, + } + + struct RecursiveBomb; + + impl Drop for RecursiveBomb { + fn drop(&mut self) { + std::panic::panic_any(RecursiveBomb); + } } impl Pack for Opens { @@ -843,13 +852,17 @@ mod tests { pack_id: &str, ) -> Result<(), LuaError> { match self { - Opens::Default => Ok(()), + Opens::Default => { + let _ = (lua, env, pack_id); + Err(LuaError::from_status(RV_ERR_UNSUPPORTED, "")) + } Opens::SetsField => { let s = lua.new_string(pack_id.as_bytes())?; lua.set_field(env, "id", s) } Opens::RaisesError => Err(LuaError::new("bad prelude setup")), Opens::Panics => panic!("open boom"), + Opens::PanicsWithRecursiveBomb => std::panic::panic_any(RecursiveBomb), } } } @@ -1111,10 +1124,11 @@ mod tests { #[test] fn open_runs_sets_fields_raises_errors_and_contains_panics() { for (pack, expected) in [ - (Opens::Default, RV_OK), + (Opens::Default, RV_ERR_UNSUPPORTED), (Opens::SetsField, RV_OK), (Opens::RaisesError, RV_ERR_LUA), (Opens::Panics, RV_ERR_REFUSED), + (Opens::PanicsWithRecursiveBomb, RV_ERR_REFUSED), ] { let mut recorder = Recorder::default(); let args = RvPackOpenArgs { @@ -1154,6 +1168,14 @@ mod tests { ["the Pack panicked while opening its prelude: open boom"] ); } + if matches!(pack, Opens::PanicsWithRecursiveBomb) { + assert_eq!( + recorder.refusals, + [ + "the Pack panicked while opening its prelude: a panic payload that is not text" + ] + ); + } } } } diff --git a/crates/runvil-plugin-sdk/src/lua.rs b/crates/runvil-plugin-sdk/src/lua.rs index ddff3e4..dabd49a 100644 --- a/crates/runvil-plugin-sdk/src/lua.rs +++ b/crates/runvil-plugin-sdk/src/lua.rs @@ -88,6 +88,7 @@ impl LuaKind { /// userdata) sit in place. Strings, tables, functions, and userdata hold /// an Engine-checked handle valid until the call returns or /// [`LuaPrelude::release_to`] releases it. +#[repr(transparent)] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct LuaValue<'a> { raw: RvValue, @@ -449,13 +450,12 @@ impl<'a> LuaPrelude<'a> { Ok(LuaValue::from_raw(out)) } - /// Borrows the byte slice of a Lua string handle, valid while `string` - /// remains live in this call's arena. + /// Copies the bytes of a Lua string handle into an owned `Vec`. /// /// # Errors /// Returns [`LuaError`] (`RV_ERR_TYPE`) when `string` is not an /// `RV_STRING`. - pub fn string_bytes(&self, string: LuaValue<'a>) -> Result<&'a [u8], LuaError> { + pub fn string_bytes(&self, string: LuaValue<'a>) -> Result, LuaError> { let mut out = RvBytes { ptr: ptr::null(), len: 0, @@ -464,21 +464,21 @@ impl<'a> LuaPrelude<'a> { let status = unsafe { (self.lua.string_bytes)(self.cx, string.raw(), &raw mut out) }; self.check(status)?; if out.len == 0 || out.ptr.is_null() { - return Ok(&[]); + return Ok(Vec::new()); } - // SAFETY: the Engine keeps the string's bytes valid while its - // handle is live in `'a`. - Ok(unsafe { slice::from_raw_parts(out.ptr, out.len) }) + // SAFETY: the Engine keeps the string's bytes valid for the + // duration of this call while `string` is live. + Ok(unsafe { slice::from_raw_parts(out.ptr, out.len) }.to_vec()) } - /// Borrows a Lua string as UTF-8 text. + /// Copies a Lua string handle as an owned UTF-8 `String`. /// /// # Errors /// Returns [`LuaError`] when `string` is not a string or is not valid /// UTF-8. - pub fn string_str(&self, string: LuaValue<'a>) -> Result<&'a str, LuaError> { + pub fn string_str(&self, string: LuaValue<'a>) -> Result { let bytes = self.string_bytes(string)?; - std::str::from_utf8(bytes).map_err(|_| LuaError::new("string is not valid UTF-8")) + String::from_utf8(bytes).map_err(|_| LuaError::new("string is not valid UTF-8")) } /// Creates a new Lua table, marking it as a list when `is_list` is diff --git a/crates/runvil-plugin-sdk/src/pack.rs b/crates/runvil-plugin-sdk/src/pack.rs index db018cd..a54a459 100644 --- a/crates/runvil-plugin-sdk/src/pack.rs +++ b/crates/runvil-plugin-sdk/src/pack.rs @@ -172,7 +172,9 @@ pub trait Pack: Send + Sync + 'static { /// /// Every field set on `env` (the Pack's prelude environment table) /// becomes a global in the section VM once this method and any - /// [`PackInfo::lua_prelude`] finish. The default does nothing. + /// [`PackInfo::lua_prelude`] finish. The default returns + /// `RV_ERR_UNSUPPORTED`, which tells the Host the Pack has no native + /// prelude. /// /// # Errors /// Returns a [`LuaError`] when a Lua operation fails or the prelude @@ -184,7 +186,10 @@ pub trait Pack: Send + Sync + 'static { pack_id: &str, ) -> Result<(), LuaError> { let _ = (lua, env, pack_id); - Ok(()) + Err(LuaError::from_status( + runvil_plugin_sys::RV_ERR_UNSUPPORTED, + "", + )) } } diff --git a/crates/runvil-plugin-sys/include/runvil_plugin.h b/crates/runvil-plugin-sys/include/runvil_plugin.h index 4088e75..224cdd5 100644 --- a/crates/runvil-plugin-sys/include/runvil_plugin.h +++ b/crates/runvil-plugin-sys/include/runvil_plugin.h @@ -333,8 +333,8 @@ * run was canceled. It cannot be cleared, every later `RvLua` call * with the same context returns it, and the Engine raises it when the * Pack callback returns. - * - `RV_ERR_TYPE` (3) means a value had the wrong `RvKind` for an - * `RvLua` call; nothing was raised in Lua. + * - `RV_ERR_TYPE` (3) means a value had the wrong `RvKind` or + * `RvUserdataType` for an `RvLua` call; nothing was raised in Lua. * - `RV_ERR_MISUSE` (4) means the caller broke the contract. * - `RV_ERR_REFUSED` (5) means the Plugin declined: to load, to make a * Pack instance, to render a Pack's tools, or to open a Pack's native @@ -1335,7 +1335,9 @@ struct RvLua { */ RvStatus (*set_metatable)(struct RvCx cx, struct RvValue table, struct RvValue metatable); /** - * `rawequal(a, b)`: identity for handles, value for scalars. + * `rawequal(a, b)` without metamethods: byte equality for strings, + * value equality for scalars, and object identity for tables, + * functions, userdata, and opaque handles. */ RvStatus (*raw_equal)(struct RvCx cx, struct RvValue a, struct RvValue b, uint32_t *out); /** @@ -1564,8 +1566,8 @@ struct RvCall { #define RV_ERR_FATAL 2 /** - * A value had the wrong `RvKind` for an `RvLua` call; nothing was - * raised in Lua. + * A value had the wrong `RvKind` or `RvUserdataType` for an `RvLua` + * call; nothing was raised in Lua. */ #define RV_ERR_TYPE 3 diff --git a/crates/runvil-plugin-sys/src/lib.rs b/crates/runvil-plugin-sys/src/lib.rs index cd8b429..07ee834 100644 --- a/crates/runvil-plugin-sys/src/lib.rs +++ b/crates/runvil-plugin-sys/src/lib.rs @@ -328,8 +328,8 @@ //! run was canceled. It cannot be cleared, every later [`RvLua`] call //! with the same context returns it, and the Engine raises it when the //! Pack callback returns. -//! - [`RV_ERR_TYPE`] (3) means a value had the wrong [`RvKind`] for an -//! [`RvLua`] call; nothing was raised in Lua. +//! - [`RV_ERR_TYPE`] (3) means a value had the wrong [`RvKind`] or +//! [`RvUserdataType`] for an [`RvLua`] call; nothing was raised in Lua. //! - [`RV_ERR_MISUSE`] (4) means the caller broke the contract. //! - [`RV_ERR_REFUSED`] (5) means the Plugin declined: to load, to make a //! Pack instance, to render a Pack's tools, or to open a Pack's native @@ -396,8 +396,8 @@ pub const RV_ERR_LUA: RvStatus = 1; /// cleared, every later [`RvLua`] call with the same context returns it, /// and the Engine raises it when the Pack callback returns. pub const RV_ERR_FATAL: RvStatus = 2; -/// A value had the wrong [`RvKind`] for an [`RvLua`] call; nothing was -/// raised in Lua. +/// A value had the wrong [`RvKind`] or [`RvUserdataType`] for an [`RvLua`] +/// call; nothing was raised in Lua. pub const RV_ERR_TYPE: RvStatus = 3; /// The caller broke the contract. pub const RV_ERR_MISUSE: RvStatus = 4; @@ -1147,8 +1147,9 @@ pub type RvFunction = unsafe extern "C" fn( ) -> RvStatus; /// Frees Pack data attached to a function or userdata instance. It runs -/// once, when Lua collects the owner or the VM closes, and receives no -/// context and may not call [`RvLua`]. It must not unwind. +/// once: if `new_function` or `new_userdata` registration fails, or, after +/// successful registration, when Lua collects the owner or the VM closes. +/// It receives no context, may not call [`RvLua`], and must not unwind. pub type RvDrop = unsafe extern "C" fn(data: *mut c_void); /// The Lua API table the Host lends to [`RV_PACK_OPEN`] and to every @@ -1224,7 +1225,9 @@ pub struct RvLua { /// refusing any metatable holding `__gc`, `__mode`, or `__close`. pub set_metatable: unsafe extern "C" fn(cx: RvCx, table: RvValue, metatable: RvValue) -> RvStatus, - /// `rawequal(a, b)`: identity for handles, value for scalars. + /// `rawequal(a, b)` without metamethods: byte equality for strings, + /// value equality for scalars, and object identity for tables, + /// functions, userdata, and opaque handles. pub raw_equal: unsafe extern "C" fn(cx: RvCx, a: RvValue, b: RvValue, out: *mut u32) -> RvStatus, /// Captures a table's keys once in the Engine's deterministic `pairs` diff --git a/plan/2026-12-02-3-native-preludes.plan.md b/plan/2026-12-02-3-native-preludes.plan.md index e0492b4..33fb3c6 100644 --- a/plan/2026-12-02-3-native-preludes.plan.md +++ b/plan/2026-12-02-3-native-preludes.plan.md @@ -67,7 +67,7 @@ flowchart TD - A Pack with no native prelude answers `RV_PACK_OPEN` with `RV_ERR_UNSUPPORTED` (matching `RV_PACK_RENDER`), which the loader treats as a no-op. - **`RvPackInfo` & `RvPackOpenArgs`**: - Append `pub lua_prelude: RvStr` to `RvPackInfo` (empty `{NULL, 0}` when unset, capped at `RV_MAX_TOOL_TEXT = 65_536` bytes of UTF-8; size grows from 40 to 56 bytes on 64-bit). - - `RvPackOpenArgs { size: u32, reserved: u32, ctx: *mut c_void, pack_id: RvStr, env: RvValue, lua: *const RvLua, refuse: unsafe extern "C" fn(ctx: *mut c_void, reason: RvStr) -> RvStatus }`. + - `RvPackOpenArgs { size: u32, reserved: u32, ctx: *mut c_void, lua_cx: RvCx, pack_id: RvStr, env: RvValue, lua: *const RvLua, refuse: unsafe extern "C" fn(ctx: *mut c_void, reason: RvStr) -> RvStatus }`. - **Flat 16-byte `RvValue` (zero `union` / zero `unsafe` in `runvil-plugin-sys`)**: - `#[repr(C)] pub struct RvValue { pub kind: RvKind, pub reserved: u32, pub payload: u64 }`. - `RvKind`: `RV_NIL = 0`, `RV_BOOLEAN = 1` (`0` or `1`), `RV_INTEGER = 2` (`payload as i64`), `RV_NUMBER = 3` (`f64::from_bits(payload)`), `RV_NULL = 4` (`json.null`), `RV_LIGHTUSERDATA = 5` (`payload as usize as *mut c_void`), `RV_STRING = 6`, `RV_TABLE = 7`, `RV_FUNCTION = 8`, `RV_USERDATA = 9`, `RV_OPAQUE = 10`.