From fb8643081370f15bf6ca0695d3cb41df0d9e658a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:30:23 +0100 Subject: [PATCH] mods: command.run-quiet (API level 3), a batch of commands with nothing in the chat A mod hands `run-quiet` a list of lines (at most 256 a call). In single player they run as the player typing them would, with the player's source made silent; on a Horizon server (it announces horizon:quiet_commands) they go as one payload that the server runs the same way; on any other server they fall back to chat commands, whose feedback shows. command.run is unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/cargo-horizon-mod/src/check.rs | 3 + crates/horizon-client/src/game/mods.rs | 56 +++++++++++++++++++ crates/horizon-client/src/game/remote.rs | 8 +++ crates/horizon-client/src/net.rs | 4 ++ crates/horizon-mod-sdk/wit/horizon.wit | 8 +++ crates/horizon-mods/src/api_level.rs | 5 +- crates/horizon-mods/src/runtime.rs | 23 ++++++++ crates/horizon-mods/tests/sandbox.rs | 28 +++++++++- crates/horizon-mods/tests/ui_guest/src/lib.rs | 16 +++++- docs/api/mods-reference.md | 1 + docs/api/stability.md | 2 +- docs/mods.md | 2 +- 12 files changed, 149 insertions(+), 7 deletions(-) diff --git a/crates/cargo-horizon-mod/src/check.rs b/crates/cargo-horizon-mod/src/check.rs index f42674da8..33095a115 100644 --- a/crates/cargo-horizon-mod/src/check.rs +++ b/crates/cargo-horizon-mod/src/check.rs @@ -262,6 +262,9 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> { format!("{}: {text}", if error { "error" } else { "feedback" }) } Output::Command { line } => format!("command: /{line}"), + Output::QuietCommands { lines, .. } => { + format!("{} quiet command(s)", lines.len()) + } Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")), Output::OpenScreen { .. } => "opened a screen".to_string(), Output::CloseScreen { .. } => "closed its screen".to_string(), diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 1752dec91..12deb61fc 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -57,6 +57,10 @@ pub(super) struct ModsState { /// is still being shown, and a mod answering its own lines would recurse. #[cfg(feature = "mods")] commands: Vec, + /// `command.run-quiet` batches for this window's own world, by mod id, + /// run on the next tick as `commands` are. + #[cfg(feature = "mods")] + quiet: Vec<(String, Vec)>, /// The server's command tree with the running mods' commands added. #[cfg(feature = "mods")] remote_tree: Option, @@ -474,6 +478,51 @@ impl Game<'_> { } None } + /// A mod's `command.run-quiet` lines (vanilla's commands only, as + /// `command.run`): to a server that runs them quietly as one payload + /// (`horizon_protocol::quiet`), to any other as chat commands, or for this + /// window's own world next tick. + fn mod_quiet_commands(&mut self, mod_id: String, lines: Vec) { + let lines: Vec = lines + .into_iter() + .filter(|l| vanilla_command(l.split(' ').next().unwrap_or_default())) + .collect(); + match self.remote.as_ref().map(|r| r.quiet_commands) { + Some(true) => { + for data in horizon_protocol::quiet::encode(&mod_id, &lines) { + self.send(horizon_protocol::packets::play::Serverbound::CustomPayload( + horizon_protocol::packets::configuration::CustomPayload { + channel: horizon_protocol::quiet::CHANNEL.into(), + data, + }, + )); + } + } + // The server checks the player's permissions; its feedback shows. + Some(false) => { + for line in lines { + self.send_chat(&format!("/{line}")); + } + } + None => self.mods.quiet.push((mod_id, lines)), + } + } + /// A quiet batch in this window's own world, as a server runs one + /// (game/lan_quiet.rs): each line as the player typing it, no chat, a + /// chat message refused; one line in the log. + fn run_quiet_batch(&mut self, mod_id: &str, lines: &[String]) { + let permission = self.ui.registries.permission; + let mut failed = 0; + for line in lines { + let ok = self.signable_arguments(permission, line).is_empty() + && self.run_command_quietly(line); + failed += usize::from(!ok); + } + log::info!( + "[mod {mod_id}] ran {} quiet command(s): {failed} failed", + lines.len() + ); + } /// A game tick. pub(super) fn tick_mods(&mut self) { // Here, at the player's level: shown inside a console call (a control @@ -481,6 +530,9 @@ impl Game<'_> { for line in std::mem::take(&mut self.mods.commands) { self.run_command(&line); } + for (mod_id, lines) in std::mem::take(&mut self.mods.quiet) { + self.run_quiet_batch(&mod_id, &lines); + } if !self.mods.mods.is_running() { return; } @@ -561,6 +613,10 @@ impl Game<'_> { } continue; } + Output::QuietCommands { mod_id, lines } => { + self.mod_quiet_commands(mod_id, lines); + continue; + } Output::Stopped { name, reason } => { // Its screen goes with it: the entry's run is gone, so // `mod_ui_view` finds no widgets and the screen closes. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 1474858b8..1459c8dd6 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -109,6 +109,8 @@ enum Received { pub(super) struct Remote { pub session: Session, pub brand: String, + /// The server announced it runs mods' quiet commands. + pub quiet_commands: bool, pub(super) builtin: Arc, lang: Arc, pub(super) registries: Arc, @@ -419,6 +421,7 @@ impl Game<'_> { self.remote = Some(Remote { session, brand: "unknown".into(), + quiet_commands: false, builtin: Arc::new(builtin), lang, registries: Arc::new(Dynamic::default()), @@ -839,6 +842,11 @@ impl Game<'_> { remote.brand = brand; } } + Event::QuietCommands => { + if let Some(remote) = &mut self.remote { + remote.quiet_commands = true; + } + } Event::Reconfigured(registries) => self.set_registries(registries), // handleTransfer: "Cannot transfer to server from // singleplayer" (no ServerData), so the world just closes. diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index 0eb260477..34daaf85c 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -40,6 +40,8 @@ pub enum Event { Status(String), /// The server's `minecraft:brand` custom payload. Brand(String), + /// The server runs mods' quiet commands (`horizon_protocol::quiet`). + QuietCommands, /// Configuration finished: the play state begins with these registries. Joined { registries: Arc, @@ -668,6 +670,8 @@ fn receive_brand(payload: &cfg::CustomPayload, send: &Sender) { && let Ok(brand) = horizon_protocol::buf::Reader::new(&payload.data).string(32767) { let _ = send.send(Event::Brand(brand)); + } else if payload.channel == horizon_protocol::quiet::CHANNEL { + let _ = send.send(Event::QuietCommands); } } diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 7f8245c48..d9bb9f5c2 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -111,6 +111,14 @@ interface storage { interface command { /// `line` without its slash; its feedback goes to the chat as if typed. run: func(line: string); + /// `lines` (each without its slash, at most 256 a call) as `run` does, + /// but with nothing in the chat: no feedback and no failure. In single + /// player and on Horizon's servers, each runs exactly as the player + /// typing it would (the same rights), in order, 64 a tick, and the + /// server logs one line a batch; one that carries a chat message (`say`, + /// `msg`) is refused. On any other server they go as chat commands, and + /// there their feedback shows: a mod running many should say so. + run-quiet: func(lines: list); } /// Capability `ui`: widgets the game draws with its own menus' widgets, for diff --git a/crates/horizon-mods/src/api_level.rs b/crates/horizon-mods/src/api_level.rs index 785f0e573..bf87d0cfa 100644 --- a/crates/horizon-mods/src/api_level.rs +++ b/crates/horizon-mods/src/api_level.rs @@ -7,13 +7,13 @@ //! version's level so the launcher can tell before it installs. /// The newest level this Horizon serves. -pub const LEVEL: u32 = 2; +pub const LEVEL: u32 = 3; /// Every function the game offers mods, as `interface.function`, with its /// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new /// function takes the next level and raises [`LEVEL`] (the `api_reference` /// test fails until it is listed here). -pub const FUNCTIONS: [(&str, u32); 33] = [ +pub const FUNCTIONS: [(&str, u32); 34] = [ ("log.write", 0), ("game.get-player", 0), ("game.get-clock", 0), @@ -47,6 +47,7 @@ pub const FUNCTIONS: [(&str, u32); 33] = [ ("players.tell", 1), ("players.broadcast", 1), ("game.raycast", 2), + ("command.run-quiet", 3), ]; /// What the game's program carries so the launcher can read its level diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index ea603ee31..ce48f2317 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -89,6 +89,9 @@ const FUEL_FRAME: u64 = 10_000_000; const FUEL_EVENT: u64 = 100_000_000; /// Chat lines a mod may show per call, HUD lines and their length. const CHAT_PER_CALL: usize = 8; +/// `command.run-quiet` lines one call of a mod may queue (a quiet payload's +/// cap, `horizon_protocol::quiet::MAX_LINES`). +const QUIET_PER_CALL: usize = 256; /// How far `game.raycast` sees, in blocks. pub const RAYCAST_MAX: f32 = 1024.0; const HUD_LINES: usize = 16; @@ -160,6 +163,9 @@ pub enum Output { /// `command.run`: a vanilla command line, without its slash, to run as /// the player. Command { line: String }, + /// `command.run-quiet`: vanilla command lines to run as the player with + /// nothing in the chat (`horizon_protocol::quiet` on a server). + QuietCommands { mod_id: String, lines: Vec }, /// The mod was turned off: it trapped, overran or failed to start. Stopped { name: String, reason: String }, /// `players.tell`: a line after the mod's name, to the player with this id. @@ -1408,6 +1414,23 @@ impl command::Host for State { self.out.push(Output::Command { line: clip(line) }); } } + fn run_quiet(&mut self, lines: Vec) { + let queued: usize = self + .out + .iter() + .map(|o| match o { + Output::QuietCommands { lines, .. } => lines.len(), + _ => 0, + }) + .sum(); + let room = QUIET_PER_CALL.saturating_sub(queued); + if room > 0 && !lines.is_empty() { + self.out.push(Output::QuietCommands { + mod_id: self.id.clone(), + lines: lines.into_iter().take(room).map(clip).collect(), + }); + } + } } impl hud::Host for State { fn set_panel(&mut self, corner: Corner, lines: Vec) { diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 5b673583d..c6b835f10 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -26,7 +26,7 @@ id = "test_ui_guest" name = "Test UI Guest" version = "0.1.0" api = "0.1" -capabilities = ["game-read", "chat", "ui", "render", "input"] +capabilities = ["game-read", "chat", "command", "ui", "render", "input"] experimental = ["ui", "render", "input"] "#; @@ -763,6 +763,32 @@ fn game_raycast_sees_the_view_hit_within_its_distance() { assert_eq!(said(&mut mods, "1e9"), [hit]); } +#[test] +fn quiet_commands_come_out_as_one_batch_capped() { + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + let quiet = |mods: &mut Mods, command: &str| -> Vec<(String, Vec)> { + assert!(mods.command(command)); + mods.drain() + .into_iter() + .filter_map(|o| match o { + Output::QuietCommands { mod_id, lines } => Some((mod_id, lines)), + _ => None, + }) + .collect() + }; + assert_eq!( + quiet(&mut mods, "quiet setblock 0 0 0 stone;say hi"), + [( + "test_ui_guest".to_string(), + vec!["setblock 0 0 0 stone".to_string(), "say hi".to_string()] + )] + ); + let batches = quiet(&mut mods, "quiet_many 300"); + assert_eq!(batches.len(), 1); + assert_eq!(batches[0].1.len(), 256); + assert_eq!(batches[0].1[255], "setblock 255 300 0 stone"); +} + #[test] fn corner_panels_text_width_and_readings() { let mut mods = load("horizon_mods_test_ui_guest.hmod"); diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 32e811fc7..74fb64350 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -5,9 +5,10 @@ //! `/input_claim`, `/input_poll`, `/input_held` and `/input_wheel` test //! `input`; `/zoom FACTOR SMOOTH TURN` tests `render.set-zoom`; //! `/corner` and `/readings` the calls the official extras mods use; -//! `/raycast DISTANCE` says what `game.raycast` sees. +//! `/raycast DISTANCE` says what `game.raycast` sees; `/quiet A;B` runs +//! lines with `command.run-quiet` (`/quiet_many N`: N of them). use horizon_mod_sdk::{ - Mod, Registration, chat, game, + Mod, Registration, chat, command, game, input::{self, Event}, render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape}, ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget}, @@ -99,6 +100,8 @@ impl Mod for Guest { "zoom", "minimap", "raycast", + "quiet", + "quiet_many", "corner", "readings", ] @@ -219,6 +222,15 @@ impl Mod for Guest { }); render::set_minimap(map); } + "quiet" => command::run_quiet(&args.split(';').map(str::to_owned).collect::>()), + "quiet_many" => { + let n: usize = args.parse().unwrap_or(0); + command::run_quiet( + &(0..n) + .map(|i| format!("setblock {i} 300 0 stone")) + .collect::>(), + ); + } "raycast" => { let distance = args.parse().unwrap_or(f32::NAN); chat::show(&match game::raycast(distance) { diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index a197b2c04..c44f27576 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -176,6 +176,7 @@ Capability `command`: vanilla commands run as the player, with the player's perm | Function | Signature | What it does | | --- | --- | --- | | `run` | `func(line: string)` | `line` without its slash; its feedback goes to the chat as if typed. | +| `run-quiet` | `func(lines: list)` | `lines` (each without its slash, at most 256 a call) as `run` does, but with nothing in the chat: no feedback and no failure. In single player and on Horizon's servers, each runs exactly as the player typing it would (the same rights), in order, 64 a tick, and the server logs one line a batch; one that carries a chat message (`say`, `msg`) is refused. On any other server they go as chat commands, and there their feedback shows: a mod running many should say so. | ## `ui` diff --git a/docs/api/stability.md b/docs/api/stability.md index f6b40fabe..df2c1aeb3 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -38,7 +38,7 @@ don't import it); faster, or fixing behaviour to what the reference already says A new WIT function doesn't break older mods, but a mod that calls it can't run on a Horizon from before it. So every function the game offers mods has an **API level**, the one it arrived at (`crates/horizon-mods/src/api_level.rs`): -level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`. A mod needs the level of +level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`, level 3 `command.run-quiet`. A mod needs the level of the newest function it imports (a component imports only the functions it calls). The level is read from the file, never declared: diff --git a/docs/mods.md b/docs/mods.md index 0d26978dc..28415d28f 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -87,7 +87,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | `chat` | `chat` | `show(text)`: a line only the local player sees, after the mod's name (8 per call) | | `hud` | `hud` | `set-panel(corner, lines)`, `clear()`: up to 16 lines of 256 characters | | `storage` | `storage` | `get(key)`, `set(key, value)`, `delete(key)`: a per-mod folder of up to 64 files, 4 MiB total, at most 1 MiB written per call | -| `command` | `command` | `run(line)`: a vanilla command run as the player, with the player's permissions, after the hook returns (8 per call); mods' own commands are not run | +| `command` | `command` | `run(line)`: a vanilla command run as the player, with the player's permissions, after the hook returns (8 per call); mods' own commands are not run. `run-quiet(lines)`: up to 256 a call, the same rights, nothing in the chat (single player and Horizon's servers run them 64 a tick and log one line a batch; elsewhere they go as chat commands and their feedback shows) | | `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item and list widgets the game lays out and draws with its own menus' code. **Experimental:** the manifest needs `experimental = ["ui"]` | | `render` | `render` | `set-hud(shapes)`: up to 1024 fills, four-cornered shapes, GUI sprites, items and text, kept on the HUD (over the hotbar, under chat and screens, hidden with F1) until replaced; `set-corner(corner, w, h, shapes)`: a box the game places in a corner, stacked with its overlays and other panels, as `hud`'s panels are; `text-width(text)`; `frame-stats()`: the game's FPS, min and 1% low; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects; `set-zoom(zoom)`: the field of view divided by up to 10, eased or at once, with slower turning, while playing and not through a spyglass (the strongest of several mods' zooms counts); `set-minimap(minimap)`: a map of the world around the player in a corner, as a map item colours it (the floor underground and under roofs), square or round, turning with the player or north up, with the player's arrow; the game keeps its tiles within its own frame budget (one map at a time, the first loaded mod's). The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` | | `input` | `input` | `claim-items(ids)`: the use button on those items is the mod's (`use-start`, `use-stop` with the ticks held; the game doesn't place, eat or swing); `register-key(name, label, key)`: up to 16 keys (`key.keyboard.r`), heard while playing as `key-down` / `key-up` (the game's own mapping on that key still runs; a screen opening lets held keys up), mouse buttons as `key.mouse.4`. The player rebinds them on the mod's page in Options > Mods, where the game lists them first as Key Binds rows (click, then press a key or mouse button; Esc binds none), even for a mod without `ui`; the choice is kept in `horizon-mods.txt` (`key..:key.keyboard.z`) and wins over `register-key`'s default; `claim-wheel(on)`: the wheel's steps become `wheel` events and the hotbar doesn't move (the one input a mod takes from the game; a mod's keys never do); `held()`; `mapping(name)`: a movement or click mapping's key label and whether it is held; `clicks-per-second()`; `poll()` returns the events, at most 256 kept. **Experimental:** `experimental = ["input"]` |