From 2df60cd388661399513bb45d0ae025a43893de4f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 21:57:09 +0200 Subject: [PATCH 1/8] Control socket: a token-guarded localhost TCP transport beside the Unix socket Windows has no Unix domain sockets, so the control endpoint there is a random 127.0.0.1 port described by a JSON file (port and a 128-bit token, readable by the user only); a client's first line is auth TOKEN. Linux and macOS keep the Unix socket, and any endpoint path ending in .json picks the TCP transport, so it is tested on Linux too. control::connect and Stream serve both. Co-Authored-By: Claude Opus 5.5 --- .../{horizon-ctl.rs => horizon-ctl/main.rs} | 0 crates/horizon-client/src/control.rs | 311 +++++++++++++++--- 2 files changed, 259 insertions(+), 52 deletions(-) rename crates/horizon-client/src/bin/{horizon-ctl.rs => horizon-ctl/main.rs} (100%) diff --git a/crates/horizon-client/src/bin/horizon-ctl.rs b/crates/horizon-client/src/bin/horizon-ctl/main.rs similarity index 100% rename from crates/horizon-client/src/bin/horizon-ctl.rs rename to crates/horizon-client/src/bin/horizon-ctl/main.rs diff --git a/crates/horizon-client/src/control.rs b/crates/horizon-client/src/control.rs index 893ffe222..9a670b90b 100644 --- a/crates/horizon-client/src/control.rs +++ b/crates/horizon-client/src/control.rs @@ -3,8 +3,15 @@ //! Each connection sends commands as text lines and receives one JSON line per //! command. Commands are executed on the game thread between frames; replies //! that depend on a later frame (screenshots, benchmarks) arrive when ready. +//! +//! Two transports carry the same lines. On Linux and macOS the endpoint is a +//! Unix domain socket. Where those don't exist (Windows), or when the endpoint +//! path ends in `.json`, the game listens on a random localhost TCP port and +//! writes `{"transport":"tcp","port":N,"token":"..."}` to the path, readable +//! only by its user; a client's first line must then be `auth TOKEN`. use std::{ - io::{BufRead, BufReader, Write}, + io::{self, BufRead, BufReader, Read, Write}, + net::{Ipv4Addr, TcpListener, TcpStream}, path::{Path, PathBuf}, sync::mpsc, thread, @@ -12,54 +19,128 @@ use std::{ #[cfg(unix)] pub use std::os::unix::net::{UnixListener, UnixStream}; -#[cfg(not(unix))] -pub use unsupported::{UnixListener, UnixStream}; -/// Windows' standard library has no Unix domain sockets: there the control -/// socket reports itself unavailable and the game runs without it. -#[cfg(not(unix))] -mod unsupported { - use std::{io, path::Path}; +/// A connection to the control endpoint, over either transport. +pub enum Stream { + #[cfg(unix)] + Unix(UnixStream), + Tcp(TcpStream), +} - fn unavailable() -> io::Error { - io::Error::new( - io::ErrorKind::Unsupported, - "the control socket needs Unix domain sockets (Linux or macOS)", - ) +impl Stream { + pub fn try_clone(&self) -> io::Result { + Ok(match self { + #[cfg(unix)] + Self::Unix(s) => Self::Unix(s.try_clone()?), + Self::Tcp(s) => Self::Tcp(s.try_clone()?), + }) } - pub struct UnixStream; - impl UnixStream { - pub fn connect>(_: P) -> io::Result { - Err(unavailable()) - } - pub fn try_clone(&self) -> io::Result { - Err(unavailable()) + /// A read timeout (None waits forever). + pub fn set_read_timeout(&self, timeout: Option) -> io::Result<()> { + match self { + #[cfg(unix)] + Self::Unix(s) => s.set_read_timeout(timeout), + Self::Tcp(s) => s.set_read_timeout(timeout), } } - impl io::Read for UnixStream { - fn read(&mut self, _: &mut [u8]) -> io::Result { - Err(unavailable()) +} +impl Read for Stream { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match self { + #[cfg(unix)] + Self::Unix(s) => s.read(buf), + Self::Tcp(s) => s.read(buf), } } - impl io::Write for UnixStream { - fn write(&mut self, _: &[u8]) -> io::Result { - Err(unavailable()) - } - fn flush(&mut self) -> io::Result<()> { - Ok(()) +} +impl Write for Stream { + fn write(&mut self, buf: &[u8]) -> io::Result { + match self { + #[cfg(unix)] + Self::Unix(s) => s.write(buf), + Self::Tcp(s) => s.write(buf), } } - pub struct UnixListener; - impl UnixListener { - pub fn bind>(_: P) -> io::Result { - Err(unavailable()) - } - pub fn incoming(&self) -> std::iter::Empty> { - std::iter::empty() + fn flush(&mut self) -> io::Result<()> { + match self { + #[cfg(unix)] + Self::Unix(s) => s.flush(), + Self::Tcp(s) => s.flush(), } } } +/// Whether the endpoint at `path` is a TCP port described by a JSON file. +pub fn uses_tcp(path: &Path) -> bool { + !cfg!(unix) || path.extension().is_some_and(|e| e == "json") +} + +/// The TCP endpoint file: (port, token). +fn read_endpoint(path: &Path) -> io::Result<(u16, String)> { + let text = std::fs::read_to_string(path)?; + let bad = || io::Error::new(io::ErrorKind::InvalidData, "not a control endpoint file"); + let v: serde_json::Value = serde_json::from_str(&text).map_err(|_| bad())?; + let port = v["port"] + .as_u64() + .and_then(|p| u16::try_from(p).ok()) + .ok_or_else(bad)?; + let token = v["token"].as_str().ok_or_else(bad)?.to_owned(); + Ok((port, token)) +} + +/// Connect to a running game's control endpoint (and authenticate over TCP). +pub fn connect(path: &Path) -> io::Result { + #[cfg(unix)] + if !uses_tcp(path) { + return UnixStream::connect(path).map(Stream::Unix); + } + let (port, token) = read_endpoint(path)?; + let mut stream = TcpStream::connect((Ipv4Addr::LOCALHOST, port))?; + stream.set_nodelay(true)?; + writeln!(stream, "auth {token}")?; + let mut reply = String::new(); + BufReader::new(stream.try_clone()?).read_line(&mut reply)?; + if !reply.contains("\"ok\"") { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("the game refused the token: {}", reply.trim()), + )); + } + Ok(Stream::Tcp(stream)) +} + +/// 128 random bits as hex, from the standard library's OS-seeded hasher keys. +fn random_token() -> String { + use std::hash::{BuildHasher, Hasher}; + (0..2) + .map(|i| { + let mut h = std::collections::hash_map::RandomState::new().build_hasher(); + h.write_u64(i); + h.write_u128( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()), + ); + h.write_u32(std::process::id()); + format!("{:016x}", h.finish()) + }) + .collect() +} + +/// Write the endpoint file so that only this user can read it. +fn write_private(path: &Path, text: &str) -> io::Result<()> { + let mut options = std::fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + options.open(path)?.write_all(text.as_bytes()) +} + +/// Constant-time comparison of the presented token. +fn same_token(a: &str, b: &str) -> bool { + a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |d, (x, y)| d | (x ^ y)) == 0 +} + /// One command line from a client, with the channel for its JSON reply. pub struct Request { pub line: String, @@ -71,33 +152,55 @@ pub struct Server { requests: mpsc::Receiver, } -/// `$HORIZON_CONTROL`, else `horizon-control.sock` in the user's runtime directory. +/// `$HORIZON_CONTROL`, else `horizon-control.sock` in the user's runtime +/// directory (`horizon-control.json` in the temporary directory on Windows). pub fn default_path() -> PathBuf { if let Some(path) = std::env::var_os("HORIZON_CONTROL") { return path.into(); } + if !cfg!(unix) { + return std::env::temp_dir().join("horizon-control.json"); + } let dir = std::env::var_os("XDG_RUNTIME_DIR").map_or_else(std::env::temp_dir, PathBuf::from); dir.join("horizon-control.sock") } impl Server { - pub fn start(path: &Path) -> std::io::Result { - // A socket left by a crashed game refuses connections; replace it. - if path.exists() && UnixStream::connect(path).is_err() { + pub fn start(path: &Path) -> io::Result { + // An endpoint left by a crashed game refuses connections; replace it. + if path.exists() && connect(path).is_err() { std::fs::remove_file(path)?; } - let listener = UnixListener::bind(path)?; let (sender, requests) = mpsc::channel(); - thread::Builder::new() - .name("horizon-control".into()) - .spawn(move || { - for stream in listener.incoming().flatten() { - let sender = sender.clone(); - let _ = thread::Builder::new() - .name("horizon-control-client".into()) - .spawn(move || serve(stream, &sender)); - } - })?; + if uses_tcp(path) { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?; + let token = random_token(); + let port = listener.local_addr()?.port(); + write_private( + path, + &serde_json::json!({ "transport": "tcp", "port": port, "token": token }) + .to_string(), + )?; + spawn_listener( + move || listener.accept().map(|(s, _)| s), + sender, + move |stream: TcpStream| { + let _ = stream.set_nodelay(true); + let mut stream = Stream::Tcp(stream); + authenticate(&mut stream, &token).then_some(stream) + }, + )?; + } else { + #[cfg(unix)] + { + let listener = UnixListener::bind(path)?; + spawn_listener( + move || listener.accept().map(|(s, _)| s), + sender, + |s| Some(Stream::Unix(s)), + )?; + } + } Ok(Self { path: path.to_owned(), requests, @@ -111,13 +214,68 @@ impl Server { } } +/// Accept connections on a thread, one more thread per client. +fn spawn_listener( + mut accept_next: impl FnMut() -> io::Result + Send + 'static, + sender: mpsc::Sender, + accept: impl Fn(S) -> Option + Send + Sync + 'static, +) -> io::Result<()> { + let accept = std::sync::Arc::new(accept); + thread::Builder::new() + .name("horizon-control".into()) + .spawn(move || { + loop { + let Ok(stream) = accept_next() else { + thread::sleep(std::time::Duration::from_millis(10)); + continue; + }; + let sender = sender.clone(); + let accept = accept.clone(); + let _ = thread::Builder::new() + .name("horizon-control-client".into()) + .spawn(move || { + if let Some(stream) = accept(stream) { + serve(stream, &sender); + } + }); + } + })?; + Ok(()) +} + +/// The first line of a TCP client must be `auth TOKEN`. +fn authenticate(stream: &mut Stream, token: &str) -> bool { + let mut line = Vec::new(); + let mut byte = [0u8; 1]; + // Read the line byte by byte so nothing after it is buffered away. + while line.len() < 256 { + match stream.read(&mut byte) { + Ok(1) if byte[0] == b'\n' => break, + Ok(1) => line.push(byte[0]), + _ => return false, + } + } + let line = String::from_utf8_lossy(&line); + let ok = line + .trim() + .strip_prefix("auth ") + .is_some_and(|t| same_token(t.trim(), token)); + let reply = if ok { + r#"{"ok":true}"# + } else { + r#"{"error":"bad or missing token: the first line must be auth TOKEN"}"# + }; + let _ = writeln!(stream, "{reply}"); + ok +} + impl Drop for Server { fn drop(&mut self) { let _ = std::fs::remove_file(&self.path); } } -fn serve(stream: UnixStream, sender: &mpsc::Sender) { +fn serve(stream: Stream, sender: &mpsc::Sender) { let Ok(mut writer) = stream.try_clone() else { return; }; @@ -140,6 +298,55 @@ fn serve(stream: UnixStream, sender: &mpsc::Sender) { } } +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tcp_endpoint_round_trip() { + let path = + std::env::temp_dir().join(format!("horizon-ctl-test-{}.json", std::process::id())); + let server = Server::start(&path).unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("\"tcp\"")); + let mut client = connect(&path).unwrap(); + writeln!(client, "status").unwrap(); + let request = loop { + if let Some(r) = server.try_recv() { + break r; + } + thread::sleep(std::time::Duration::from_millis(5)); + }; + assert_eq!(request.line, "status"); + request.reply.send(r#"{"ok":true}"#.into()).unwrap(); + let mut reply = String::new(); + BufReader::new(client).read_line(&mut reply).unwrap(); + assert_eq!(reply.trim(), r#"{"ok":true}"#); + drop(server); + assert!(!path.exists()); + } + + #[test] + fn tcp_refuses_a_wrong_token() { + let path = + std::env::temp_dir().join(format!("horizon-ctl-bad-{}.json", std::process::id())); + let _server = Server::start(&path).unwrap(); + let (port, _) = read_endpoint(&path).unwrap(); + let mut stream = TcpStream::connect((Ipv4Addr::LOCALHOST, port)).unwrap(); + writeln!(stream, "auth nope").unwrap(); + let mut reply = String::new(); + BufReader::new(stream).read_line(&mut reply).unwrap(); + assert!(reply.contains("error")); + } + + #[test] + fn tokens_differ() { + assert_ne!(random_token(), random_token()); + assert_eq!(random_token().len(), 32); + assert!(same_token("abc", "abc") && !same_token("abc", "abd") && !same_token("a", "ab")); + } +} + /// Frame durations since the last reset, summarized like the Java recorder, /// with the CPU part of each frame and GPU times from timestamp queries. #[derive(Default)] From 7bb3347edd6e5035fabd9fd76f7f03cb2c3ad3db Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 21:57:09 +0200 Subject: [PATCH 2/8] Agent control: observe and act from the control socket game/agent.rs adds commands an agent can play with: state, looking-at, entities, block, blocks, find-block, inventory, screen and messages read the game as JSON; move, jump, goto (A* over standable blocks), look-at, attack, break, place, interact, use-item, select, drop, open-inventory, click-button, click-at, command, respawn, pause, wait and stop act like a player. Actions that take time run as a task advanced every frame and reply when done, with what happened (break reports drops and pickups, place the block placed). Buttons are clicked by label: the classic and Horizon button drawers record what they draw each frame (widgets.rs), and a click is a synthesized pointer move and press, so it behaves exactly like the mouse on every screen. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 4 + crates/horizon-client/src/game/agent.rs | 1725 +++++++++++++++++++++ crates/horizon-client/src/game/control.rs | 8 + crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/title.rs | 1 + crates/horizon-client/src/ui.rs | 1 + crates/horizon-client/src/ui_theme.rs | 6 + crates/horizon-client/src/widgets.rs | 120 ++ 8 files changed, 1866 insertions(+) create mode 100644 crates/horizon-client/src/game/agent.rs create mode 100644 crates/horizon-client/src/widgets.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7f02bf53b..d120fb6a2 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2,6 +2,7 @@ //! block interaction, inventory and HUD. mod advancements; mod advancements_screen; +mod agent; mod allays; mod armor_stands; mod backdrop; @@ -806,6 +807,8 @@ struct Game<'a> { view_frustum: Option, /// A scripted flight from the control socket (`fly`). flight: Option, + /// The running agent action from the control socket (game/agent.rs). + agent: agent::Agent, /// The overworld's last `sky_darken` and its inputs (time, rain, thunder). sky_darken_memo: std::cell::Cell>, persist: persist::EntityMemory, @@ -8655,6 +8658,7 @@ pub fn run() -> Result<()> { pending_screenshot: None, pending_bench: None, flight: None, + agent: agent::Agent::default(), view_frustum: None, pending_uploads: Vec::new(), frame_graph: Default::default(), diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs new file mode 100644 index 000000000..e90b73ba8 --- /dev/null +++ b/crates/horizon-client/src/game/agent.rs @@ -0,0 +1,1725 @@ +//! Control-socket commands for agents and scripts that play the game: read +//! the world, the player, the inventory and the open screen as JSON, and act +//! like a player (walk, look, break, place, use, click buttons). Actions that +//! take time run as a task advanced every frame and reply when they finish or +//! time out, so `horizon-ctl break 10 64 3` returns what the block dropped. +use super::{Game, Screen}; +use horizon_client::{Result, items::ItemStack, widgets}; +use horizon_core::geometry::Vec3; +use horizon_world::registry::BlockStateId; +use serde_json::{Value, json}; +use std::{ + collections::{BTreeMap, HashMap, HashSet}, + sync::mpsc::Sender, + time::{Duration, Instant}, +}; +use winit::{ + application::ApplicationHandler, + dpi::PhysicalPosition, + event::{DeviceId, ElementState, MouseButton, WindowEvent}, + event_loop::ActiveEventLoop, + keyboard::KeyCode, +}; + +pub(super) const HELP: &[&str] = &[ + "state player, world, screen and crosshair target in one reply", + "looking-at the block or entity under the crosshair (distance, face)", + "entities [RADIUS] [TYPE] mobs, dropped items and orbs near the player, nearest first", + "block X Y Z the block state at a position", + "blocks X1 Y1 Z1 X2 Y2 Z2 the non-air blocks of a box (at most 32768 blocks)", + "find-block BLOCK [RADIUS] the nearest loaded blocks of a kind (default radius 32)", + "inventory hotbar, main inventory, armor, offhand and carried stack", + "screen the open screen or menu, its slots and its buttons", + "messages [N] recent chat and system messages, title and action bar", + "move DIR SECONDS [--sprint] [--sneak] [--jump] walk forward|back|left|right", + "jump jump once", + "goto X Y Z [--near R] [--sprint] [--direct] [--timeout S] walk to a position along a path", + "look-at X Y Z | look-at block X Y Z [FACE] | look-at entity ID", + "attack [ID] swing at the target (after looking at entity ID)", + "break X Y Z [--timeout S] mine a block until it breaks; reports drops and pickups", + "place X Y Z [--item ITEM] place the held (or given) item at a position", + "interact X Y Z [FACE] right-click a block (open a door, chest, crafting table...)", + "use-item [--hold S] right-click with the held item (eat, drink, throw, draw a bow)", + "select SLOT|ITEM select a hotbar slot (1-9) or the hotbar slot holding ITEM", + "drop [all] drop one of the held item (all: the stack)", + "open-inventory open the inventory screen", + "click-button LABEL click a button of the open screen or menu by its label", + "click-at X Y [right] click at GUI pixel X Y of the window", + "command TEXT run a /command", + "pause open the pause menu", + "wait TICKS wait for game ticks to pass", + "stop cancel the running action and release every key", +]; + +/// Keys the agent holds for a task (the game's movement reads these). +const MOVE_KEYS: [KeyCode; 7] = [ + KeyCode::KeyW, + KeyCode::KeyS, + KeyCode::KeyA, + KeyCode::KeyD, + KeyCode::Space, + KeyCode::ShiftLeft, + KeyCode::ControlLeft, +]; + +/// Words of a command line: positional values and `--flag [value]` options. +#[derive(Debug, Default, PartialEq)] +pub(super) struct Args<'a> { + pub pos: Vec<&'a str>, + pub flags: HashMap<&'a str, Option<&'a str>>, +} +/// Options that take a value (`--timeout 10` or `--timeout=10`). +const VALUE_FLAGS: &[&str] = &["timeout", "near", "item", "radius", "hold", "face"]; + +pub(super) fn parse_args<'a>(words: &[&'a str]) -> Args<'a> { + let mut args = Args::default(); + let mut i = 0; + while i < words.len() { + let w = words[i]; + if let Some(flag) = w.strip_prefix("--") { + if let Some((k, v)) = flag.split_once('=') { + args.flags.insert(k, Some(v)); + } else if VALUE_FLAGS.contains(&flag) && i + 1 < words.len() { + args.flags.insert(flag, Some(words[i + 1])); + i += 1; + } else { + args.flags.insert(flag, None); + } + } else { + args.pos.push(w); + } + i += 1; + } + args +} +impl Args<'_> { + fn has(&self, flag: &str) -> bool { + self.flags.contains_key(flag) + } + fn num(&self, flag: &str, default: f64) -> Result { + match self.flags.get(flag) { + Some(Some(v)) => Ok(v.parse()?), + Some(None) => Err(format!("--{flag} needs a value").into()), + None => Ok(default), + } + } + fn get(&self, i: usize, what: &str) -> Result<&str> { + self.pos + .get(i) + .copied() + .ok_or_else(|| format!("missing {what}").into()) + } + fn f64(&self, i: usize, what: &str) -> Result { + let v = self.get(i, what)?; + v.parse() + .map_err(|_| format!("{what} must be a number, not {v}").into()) + } + fn i32(&self, i: usize, what: &str) -> Result { + let v = self.get(i, what)?; + v.parse() + .map_err(|_| format!("{what} must be an integer, not {v}").into()) + } + fn block_pos(&self, from: usize) -> Result<[i32; 3]> { + Ok([ + self.i32(from, "X")?, + self.i32(from + 1, "Y")?, + self.i32(from + 2, "Z")?, + ]) + } +} + +fn namespaced(name: &str) -> String { + if name.contains(':') { + name.to_owned() + } else { + format!("minecraft:{name}") + } +} + +const FACES: [(&str, [i32; 3]); 6] = [ + ("down", [0, -1, 0]), + ("up", [0, 1, 0]), + ("north", [0, 0, -1]), + ("south", [0, 0, 1]), + ("west", [-1, 0, 0]), + ("east", [1, 0, 0]), +]; +fn face_name(face: [i32; 3]) -> &'static str { + FACES + .iter() + .find(|(_, d)| *d == face) + .map_or("?", |(n, _)| n) +} +fn face_dir(name: &str) -> Result<[i32; 3]> { + FACES + .iter() + .find(|(n, _)| *n == name) + .map(|(_, d)| *d) + .ok_or_else(|| format!("unknown face {name} (down up north south west east)").into()) +} +fn add(a: [i32; 3], b: [i32; 3]) -> [i32; 3] { + [a[0] + b[0], a[1] + b[1], a[2] + b[2]] +} +fn dist(a: [f64; 3], b: [f64; 3]) -> f64 { + ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt() +} +/// Minecraft's yaw and pitch facing from `eye` towards `at` (yaw 0 faces +Z, +/// 90 faces -X; positive pitch looks down). +pub(super) fn yaw_pitch(eye: [f64; 3], at: [f64; 3]) -> (f32, f32) { + let d = [at[0] - eye[0], at[1] - eye[1], at[2] - eye[2]]; + let horizontal = (d[0] * d[0] + d[2] * d[2]).sqrt(); + ( + (-d[0]).atan2(d[2]).to_degrees() as f32, + (-d[1]).atan2(horizontal).to_degrees() as f32, + ) +} + +fn counts(items: impl Iterator) -> BTreeMap { + let mut map = BTreeMap::new(); + for s in items { + *map.entry(s.item.to_string()).or_insert(0) += i64::from(s.count); + } + map +} +/// Item counts that changed between two inventories (positive: gained). +fn delta(before: &BTreeMap, after: &BTreeMap) -> BTreeMap { + let mut out = BTreeMap::new(); + for key in before.keys().chain(after.keys()) { + let d = after.get(key).copied().unwrap_or(0) - before.get(key).copied().unwrap_or(0); + if d != 0 { + out.insert(key.clone(), d); + } + } + out +} + +/// A feet position the A* path walks through. +type Node = [i32; 3]; + +enum TaskKind { + /// Hold keys until a deadline. + Move { + keys: Vec, + until: Instant, + from: Vec3, + }, + Wait { + until_tick: u64, + }, + Jump { + release_tick: u64, + from_y: f64, + }, + Goto(Box), + Break(Box), + /// A right click on a block or a placement: report after a few ticks. + Click { + pos: Option<[i32; 3]>, + before: Option, + inventory: BTreeMap, + report_tick: u64, + release: Option, + place: bool, + }, + Attack { + id: Option, + health: Option, + report_tick: u64, + }, +} +struct Goto { + target: [f64; 3], + near: f64, + sprint: bool, + path: Vec, + next: usize, + /// Tick of the last waypoint reached, and how many replans so far. + progress_tick: u64, + replans: u32, + jump_until: u64, + warning: Option, +} +struct Break { + pos: [i32; 3], + before: BlockStateId, + items_before: HashSet, + inventory: BTreeMap, + started_tick: u64, + /// Set once the block changed: collect drops until this tick. + collect_until: Option, + broke_tick: u64, + drops: BTreeMap, +} +struct Task { + kind: TaskKind, + reply: Sender, + deadline: Instant, + name: &'static str, +} + +#[derive(Default)] +pub(super) struct Agent { + task: Option, +} + +pub(super) enum Handled { + Reply(Value), + /// The reply comes later, from the task. + Deferred, + /// Not an agent command. + No, +} + +impl Game<'_> { + fn state_string(&self, state: BlockStateId) -> String { + let Some(s) = self.res.assets.registry.state(state) else { + return "?".into(); + }; + if s.properties.is_empty() { + return s.name.clone(); + } + let props: Vec = s + .properties + .iter() + .map(|(k, v)| format!("{k}={v}")) + .collect(); + format!("{}[{}]", s.name, props.join(",")) + } + fn block_json(&self, pos: [i32; 3]) -> Value { + let state = self.world.block(pos[0], pos[1], pos[2]); + json!({ + "pos": pos, + "block": &*self.res.facts.get(state).name, + "state": self.state_string(state), + "loaded": self.world.chunks.contains_key(&(pos[0] >> 4, pos[2] >> 4)), + }) + } + fn stack_value(&self, s: &ItemStack) -> Value { + let mut v = json!({ "item": &*s.item, "count": s.count }); + if s.damage > 0 { + v["damage"] = json!(s.damage); + } + if let Some(c) = horizon_client::item_data::encode_components(s) { + v["components"] = json!(horizon_client::snbt::to_snbt(&c)); + } + v + } + fn slot_value(&self, slot: usize, s: &Option) -> Value { + match s { + Some(s) => { + let mut v = self.stack_value(s); + v["slot"] = json!(slot); + v + } + None => json!({ "slot": slot, "item": null }), + } + } + fn need_world(&self) -> Result<()> { + if self.title.is_some() { + return Err("no world open (title screen); use: open WORLD [SEED] [creative]".into()); + } + Ok(()) + } + fn playing(&self) -> Result<()> { + if self.title.is_some() { + return Err("no world open (title screen); use: open WORLD [SEED] [creative]".into()); + } + if self.player.is_none() { + return Err("the player has not spawned yet; try wait-ready".into()); + } + if self.screen != Screen::Playing || self.book.is_some() || self.sign_edit.is_some() { + return Err(format!( + "the {} screen is open; close it first (close, or click-button)", + self.screen_label() + ) + .into()); + } + Ok(()) + } + fn screen_label(&self) -> &'static str { + if self.title.is_some() { + return "title"; + } + if self.book.is_some() { + return "book"; + } + if self.sign_edit.is_some() { + return "sign"; + } + match self.screen { + Screen::Playing => "playing", + Screen::Paused => "paused", + Screen::Options => "options", + Screen::Inventory if self.station.is_some() => "station", + Screen::Inventory if self.container.is_some() => "container", + Screen::Inventory => "inventory", + Screen::Creative => "creative", + Screen::Dead => "dead", + Screen::Chat => "chat", + Screen::Stats => "stats", + Screen::Advancements => "advancements", + Screen::WorldOptions => "world-options", + } + } + fn inventory_counts(&self) -> BTreeMap { + counts( + self.inventory + .iter() + .chain(self.armor.iter()) + .chain(std::iter::once(&self.offhand)) + .chain(std::iter::once(&self.carried)) + .flatten() + .cloned(), + ) + } + + /// The block or entity under the crosshair. + fn looking_at(&self) -> Value { + let Some(eye) = self.eye_position() else { + return Value::Null; + }; + let block = self.pick().map(|hit| { + let mut v = self.block_json(hit.pos); + v["face"] = json!(face_name(hit.face)); + v["point"] = json!(hit.point); + v["distance"] = json!(dist(eye, hit.point)); + v + }); + let entity = self.mob_hit().map(|(i, d)| { + let m = &self.mobs[i]; + json!({ "id": m.id, "type": m.kind.id, "health": m.health, "distance": d, + "pos": [m.position.x, m.position.y, m.position.z] }) + }); + let kind = match (&block, &entity) { + (Some(b), Some(e)) if e["distance"].as_f64() <= b["distance"].as_f64() => "entity", + (_, Some(_)) if block.is_none() => "entity", + (Some(_), _) => "block", + _ => "none", + }; + json!({ "kind": kind, "block": block, "entity": entity }) + } + + fn state_value(&self) -> Value { + let player = self.player.as_ref().map(|p| { + json!({ + "position": [p.position.x, p.position.y, p.position.z], + "block_pos": [p.position.x.floor() as i32, p.position.y.floor() as i32, p.position.z.floor() as i32], + "eye": self.eye_position(), + "yaw": self.yaw, + "pitch": self.pitch, + "velocity": [p.velocity.x, p.velocity.y, p.velocity.z], + "on_ground": p.ground.on_ground, + "flying": p.flying, + "sneaking": self.keys.contains(&KeyCode::ShiftLeft), + "sprinting": self.keys.contains(&KeyCode::ControlLeft), + "health": p.health.health(), + "food": p.health.food.food, + "saturation": p.health.food.saturation, + "xp": { "level": self.experience.level, "progress": self.experience.progress, "total": self.experience.total }, + "effects": self.potions.effects.list.iter().map(|e| json!({ "id": e.id, "duration_ticks": e.duration, "amplifier": e.amplifier })).collect::>(), + }) + }); + json!({ + "screen": self.screen_label(), + "menu": self.title.as_ref().map(|_| self.title_value()), + "world": (self.title.is_none()).then(|| self.level.name.clone()), + "dimension": self.dim.id(), + "gamemode": format!("{:?}", self.mode).to_lowercase(), + "time": { "day_time": self.world.day_time, "day": self.world.day_time.div_euclid(24000), "time_of_day": self.world.day_time.rem_euclid(24000) }, + "weather": { "raining": self.world.weather.raining, "thundering": self.world.weather.thundering }, + "paused": self.pause, + "player": player, + "selected": self.selected + 1, + "held": self.held().map(|s| self.stack_value(s)), + "looking_at": self.looking_at(), + "busy": self.agent.task.as_ref().map(|t| t.name), + "ticks": self.ticks, + }) + } + + fn title_value(&self) -> Value { + use horizon_client::title::Mode; + let Some(title) = &self.title else { + return Value::Null; + }; + let worlds = || { + title + .recent_worlds() + .iter() + .map(|w| json!({ "folder": w.folder, "name": w.name, "creative": w.creative })) + .collect::>() + }; + match &title.mode { + Mode::Main => json!({ "mode": "main", "worlds": worlds() }), + Mode::Select { + worlds: list, + selected, + } => json!({ + "mode": "select-world", + "worlds": list.iter().map(|w| json!({ "folder": w.folder, "name": w.name, "creative": w.creative })).collect::>(), + "selected": selected, + }), + Mode::Create { + name, + seed, + creative, + focus, + } => json!({ + "mode": "create-world", + "fields": { "name": name, "seed": seed }, + "focus": match focus { 0 => "name", 1 => "seed", _ => "none" }, + "creative": creative, + }), + Mode::Multiplayer(_) => json!({ "mode": "multiplayer" }), + } + } + + fn entities_value(&self, radius: f64, kind: Option<&str>) -> Value { + let Some(p) = &self.player else { + return json!({ "entities": [] }); + }; + let me = [p.position.x, p.position.y, p.position.z]; + let want = kind.map(namespaced); + let mut list: Vec<(f64, Value)> = Vec::new(); + let mut push = |pos: [f64; 3], ty: &str, v: Value| { + let d = dist(me, pos); + if d <= radius && want.as_deref().is_none_or(|w| w == ty) { + let mut v = v; + v["type"] = json!(ty); + v["pos"] = json!(pos); + v["distance"] = json!(d); + list.push((d, v)); + } + }; + for m in self.mobs.iter().filter(|m| m.alive()) { + push( + [m.position.x, m.position.y, m.position.z], + m.kind.id.as_ref(), + json!({ "id": m.id, "kind": "mob", "health": m.health, "baby": m.is_baby() }), + ); + } + for item in &self.dropped { + push( + [item.position.x, item.position.y, item.position.z], + "minecraft:item", + json!({ "id": item.id, "kind": "item", "item": self.stack_value(&item.stack) }), + ); + } + for orb in &self.orbs { + push( + [orb.position.x, orb.position.y, orb.position.z], + "minecraft:experience_orb", + json!({ "kind": "orb", "value": orb.value }), + ); + } + list.sort_by(|a, b| a.0.total_cmp(&b.0)); + json!({ "entities": list.into_iter().map(|(_, v)| v).collect::>() }) + } + + fn inventory_value(&self) -> Value { + let armor = ["head", "chest", "legs", "feet"]; + json!({ + "selected": self.selected + 1, + "held": self.held().map(|s| self.stack_value(s)), + "hotbar": (0..9).map(|i| self.slot_value(i, &self.inventory[i])).collect::>(), + "main": (9..36).map(|i| self.slot_value(i, &self.inventory[i])).collect::>(), + "armor": armor.iter().enumerate().map(|(i, name)| { + let mut v = self.slot_value(500 + i, &self.armor[i]); + v["part"] = json!(name); + v + }).collect::>(), + "offhand": self.slot_value(504, &self.offhand), + "carried": self.carried.as_ref().map(|s| self.stack_value(s)), + "counts": self.inventory_counts(), + }) + } + + fn screen_value(&mut self) -> Value { + let buttons: Vec = widgets::last() + .iter() + .map(|w| json!({ "label": w.label, "enabled": w.enabled, "x": w.x, "y": w.y, "w": w.w, "h": w.h })) + .collect(); + let mut v = json!({ + "screen": self.screen_label(), + "buttons": buttons, + }); + if self.title.is_some() { + v["menu"] = self.title_value(); + } + if self.screen == Screen::Inventory && self.title.is_none() { + let mut slots = Vec::new(); + for i in self.slots() { + let stack = if i == 200 { + self.craft_result() + } else { + self.slot_mut(i).clone() + }; + slots.push(self.slot_value(i, &stack)); + } + v["slots"] = json!(slots); + v["carried"] = json!(self.carried.as_ref().map(|s| self.stack_value(s))); + v["craft_size"] = json!(self.craft_size); + v["station"] = json!(self.station.as_ref().map(|s| format!("{:?}", s.kind))); + v["container"] = json!(self.container); + v["slot_ids"] = json!( + "0-8 hotbar, 9-35 inventory, 100+ crafting grid (row-major), 200 crafting result, 300+ container, 500-503 armor, 504 offhand, 600+ station" + ); + } + v + } + + fn messages_value(&self, n: usize) -> Value { + let titles = &self.titles; + json!({ + "chat": self.ui.chat.recent_lines(n), + "order": "newest first", + "title": (titles.time > 0).then(|| titles.title.as_ref().map(|t| t.plain())).flatten(), + "subtitle": (titles.time > 0).then(|| titles.subtitle.as_ref().map(|t| t.plain())).flatten(), + "actionbar": (titles.overlay_time > 0).then(|| titles.overlay.as_ref().map(|t| t.plain())).flatten(), + }) + } + + /// Whether a block stops movement, for the path finder. + fn blocks_motion(&self, pos: [i32; 3]) -> bool { + let f = self.res.facts.get(self.world.block(pos[0], pos[1], pos[2])); + f.full_collision || f.legacy_solid + } + fn walkable(&self, n: Node) -> bool { + let below = self.world.block(n[0], n[1] - 1, n[2]); + let lava = |p: [i32; 3]| { + &*self.res.facts.get(self.world.block(p[0], p[1], p[2])).name == "minecraft:lava" + }; + self.world.chunks.contains_key(&(n[0] >> 4, n[2] >> 4)) + && (self.blocks_motion([n[0], n[1] - 1, n[2]]) + || self.res.facts.get(below).fluid != horizon_client::blocks::Fluid::None) + && !self.blocks_motion(n) + && !self.blocks_motion([n[0], n[1] + 1, n[2]]) + && !lava(n) + && !lava([n[0], n[1] - 1, n[2]]) + } + /// A* over standable feet positions: steps up one block, drops up to three. + fn find_path(&self, from: Node, goal: [f64; 3], near: f64) -> Option> { + use std::{cmp::Reverse, collections::BinaryHeap}; + let reached = |n: Node| { + let c = [ + f64::from(n[0]) + 0.5, + f64::from(n[1]), + f64::from(n[2]) + 0.5, + ]; + ((c[0] - goal[0]).powi(2) + (c[2] - goal[2]).powi(2)).sqrt() <= near.max(0.5) + && (c[1] - goal[1]).abs() <= near.max(1.0) + 0.5 + }; + let h = |n: Node| { + ((f64::from(n[0]) + 0.5 - goal[0]).abs() + + (f64::from(n[1]) - goal[1]).abs() + + (f64::from(n[2]) + 0.5 - goal[2]).abs()) + * 10.0 + }; + let mut open = BinaryHeap::new(); + let mut cost: HashMap = HashMap::new(); + let mut came: HashMap = HashMap::new(); + cost.insert(from, 0); + open.push(Reverse((h(from) as u32, from))); + let mut expanded = 0; + while let Some(Reverse((_, n))) = open.pop() { + if reached(n) { + let mut path = vec![n]; + let mut at = n; + while let Some(&p) = came.get(&at) { + path.push(p); + at = p; + } + path.reverse(); + return Some(path); + } + expanded += 1; + if expanded > 30_000 { + return None; + } + let base = cost[&n]; + for d in [[1, 0], [-1, 0], [0, 1], [0, -1]] { + for dy in [0, 1, -1, -2, -3] { + let m = [n[0] + d[0], n[1] + dy, n[2] + d[1]]; + // A step up needs head room above the start; a drop needs + // the column in front clear down to the landing. + let clear = match dy { + 1 => !self.blocks_motion([n[0], n[1] + 2, n[2]]), + d if d < 0 => { + (m[1]..=n[1] + 1).all(|y| !self.blocks_motion([m[0], y, m[2]])) + } + _ => true, + }; + if !clear || !self.walkable(m) { + continue; + } + let water = self.res.facts.get(self.world.block(m[0], m[1], m[2])).fluid + != horizon_client::blocks::Fluid::None; + let step = 10 + if dy != 0 { 5 } else { 0 } + if water { 30 } else { 0 }; + let c = base + step; + if cost.get(&m).is_none_or(|&old| c < old) { + cost.insert(m, c); + came.insert(m, n); + open.push(Reverse((c + h(m) as u32, m))); + } + break; + } + } + } + None + } + + /// Point the view at `at` from the eye. + fn face_point(&mut self, at: [f64; 3]) -> Result<()> { + let eye = self.eye_position().ok_or("no player")?; + let (yaw, pitch) = yaw_pitch(eye, at); + self.yaw = yaw; + self.pitch = pitch.clamp(-90.0, 90.0); + Ok(()) + } + /// Aim at a face of `pos` the crosshair can reach; the face hit. + fn aim_block(&mut self, pos: [i32; 3], face: Option<[i32; 3]>) -> Result<[i32; 3]> { + let eye = self.eye_position().ok_or("no player")?; + let centre = pos.map(|v| f64::from(v) + 0.5); + let mut faces: Vec<[i32; 3]> = match face { + Some(f) => vec![f], + None => FACES.iter().map(|(_, d)| *d).collect(), + }; + // Faces turned towards the eye first, nearest first. + faces.sort_by(|a, b| { + let point = |f: &[i32; 3]| [0, 1, 2].map(|i| centre[i] + f64::from(f[i]) * 0.45); + dist(eye, point(a)).total_cmp(&dist(eye, point(b))) + }); + for f in faces { + for inset in [0.45, 0.3, 0.0] { + let point = [0, 1, 2].map(|i| centre[i] + f64::from(f[i]) * inset); + let (yaw, pitch) = yaw_pitch(eye, point); + let dir = super::view_vector(yaw, pitch); + if let Some(hit) = self.clip_ray(eye, dir, self.reach()) + && hit.pos == pos + && (face.is_none() || hit.face == f) + { + self.yaw = yaw; + self.pitch = pitch; + return Ok(hit.face); + } + } + } + let d = dist(eye, centre); + if d > self.reach() + 0.9 { + return Err(format!( + "block {pos:?} is {d:.1} blocks away, out of reach ({:.1}); goto it first", + self.reach() + ) + .into()); + } + Err(format!("no face of block {pos:?} is visible from here").into()) + } + + /// A left or right click, as the mouse would. + fn agent_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> { + self.play_mouse(button, pressed) + } + fn release_agent_keys(&mut self) { + for k in MOVE_KEYS { + self.keys.remove(&k); + } + if self.left { + let _ = self.agent_mouse(MouseButton::Left, false); + } + if self.right { + let _ = self.agent_mouse(MouseButton::Right, false); + } + } + + /// Synthesize the pointer moving to GUI pixel (x, y) and a click there. + fn synth_click( + &mut self, + event_loop: &ActiveEventLoop, + x: f32, + y: f32, + button: MouseButton, + ) -> Result<()> { + let id = self.window.as_ref().ok_or("no window yet")?.id(); + let scale = self + .renderer + .as_ref() + .map(|r| horizon_client::hud::HudBatch::new([r.config.width, r.config.height]).scale) + .ok_or("no renderer yet")?; + let device_id = DeviceId::dummy(); + let position = PhysicalPosition::new(f64::from(x * scale), f64::from(y * scale)); + self.window_event( + event_loop, + id, + WindowEvent::CursorMoved { + device_id, + position, + }, + ); + for state in [ElementState::Pressed, ElementState::Released] { + self.window_event( + event_loop, + id, + WindowEvent::MouseInput { + device_id, + state, + button, + }, + ); + } + Ok(()) + } + + fn start_task( + &mut self, + name: &'static str, + kind: TaskKind, + reply: &Sender, + timeout: f64, + ) -> Result { + self.agent.task = Some(Task { + kind, + reply: reply.clone(), + deadline: Instant::now() + Duration::from_secs_f64(timeout.clamp(0.05, 3600.0)), + name, + }); + Ok(Handled::Deferred) + } + + /// Agent commands; `Handled::No` when `words[0]` is not one of them. + pub(super) fn agent_command( + &mut self, + words: &[&str], + line: &str, + reply: &Sender, + event_loop: &ActiveEventLoop, + ) -> Result { + let name = words[0]; + let a = parse_args(&words[1..]); + let ok = |v: Value| Ok(Handled::Reply(v)); + let blocking = matches!( + name, + "move" + | "jump" + | "goto" + | "break" + | "place" + | "interact" + | "use-item" + | "attack" + | "wait" + ); + if blocking && let Some(task) = &self.agent.task { + return Err(format!("busy with {}; wait for it or send stop", task.name).into()); + } + match name { + "state" => ok(self.state_value()), + "looking-at" | "target" => { + self.need_world()?; + ok(self.looking_at()) + } + "entities" => { + self.need_world()?; + let radius = a.pos.first().map_or(Ok(32.0), |r| r.parse::())?; + ok(self.entities_value(radius, a.pos.get(1).copied())) + } + "block" => { + self.need_world()?; + ok(self.block_json(a.block_pos(0)?)) + } + "blocks" => { + self.need_world()?; + let (p, q) = (a.block_pos(0)?, a.block_pos(3)?); + let lo = [0, 1, 2].map(|i| p[i].min(q[i])); + let hi = [0, 1, 2].map(|i| p[i].max(q[i])); + let volume: i64 = (0..3).map(|i| i64::from(hi[i] - lo[i] + 1)).product(); + if volume > 32768 { + return Err(format!("{volume} blocks; at most 32768 per request").into()); + } + let mut list = Vec::new(); + let mut census: BTreeMap = BTreeMap::new(); + for y in lo[1]..=hi[1] { + for z in lo[2]..=hi[2] { + for x in lo[0]..=hi[0] { + let state = self.world.block(x, y, z); + if self.res.facts.is_air(state) { + continue; + } + let name = self.res.facts.get(state).name.to_string(); + *census.entry(name).or_insert(0) += 1; + list.push(json!([x, y, z, self.state_string(state)])); + } + } + } + ok(json!({ "from": lo, "to": hi, "counts": census, "blocks": list })) + } + "find-block" => { + self.need_world()?; + let want = namespaced(a.get(0, "BLOCK")?); + let radius = a + .pos + .get(1) + .map_or(Ok(32), |r| r.parse::())? + .clamp(1, 64); + let eye = self.eye_position().ok_or("no player")?; + let c = eye.map(|v| v.floor() as i32); + let mut found = Vec::new(); + for y in (c[1] - radius).max(-64)..=(c[1] + radius).min(319) { + for z in c[2] - radius..=c[2] + radius { + for x in c[0] - radius..=c[0] + radius { + let state = self.world.block(x, y, z); + if *self.res.facts.get(state).name == *want { + let d = dist(eye, [x, y, z].map(|v| f64::from(v) + 0.5)); + found.push((d, [x, y, z])); + } + } + } + } + found.sort_by(|a, b| a.0.total_cmp(&b.0)); + let total = found.len(); + ok(json!({ + "block": want, + "count": total, + "nearest": found.iter().take(16).map(|(d, p)| json!({ "pos": p, "distance": d })).collect::>(), + })) + } + "inventory" => { + self.need_world()?; + ok(self.inventory_value()) + } + "screen" => ok(self.screen_value()), + "messages" => { + let n = a.pos.first().map_or(Ok(20), |n| n.parse::())?; + ok(self.messages_value(n)) + } + "move" => { + self.playing()?; + let key = match a.get(0, "DIR")? { + "forward" | "w" => KeyCode::KeyW, + "back" | "backward" | "s" => KeyCode::KeyS, + "left" | "a" => KeyCode::KeyA, + "right" | "d" => KeyCode::KeyD, + other => { + return Err( + format!("DIR is forward, back, left or right, not {other}").into() + ); + } + }; + let seconds = a.f64(1, "SECONDS")?.clamp(0.0, 600.0); + let mut keys = vec![key]; + if a.has("sprint") { + keys.push(KeyCode::ControlLeft); + } + if a.has("sneak") { + keys.push(KeyCode::ShiftLeft); + } + if a.has("jump") { + keys.push(KeyCode::Space); + } + for &k in &keys { + self.keys.insert(k); + } + let from = self.player.as_ref().map_or(Vec3::ZERO, |p| p.position); + let until = Instant::now() + Duration::from_secs_f64(seconds); + self.start_task( + "move", + TaskKind::Move { keys, until, from }, + reply, + seconds + 5.0, + ) + } + "jump" => { + self.playing()?; + self.keys.insert(KeyCode::Space); + let from_y = self.player.as_ref().map_or(0.0, |p| p.position.y); + let release_tick = self.ticks + 3; + self.start_task( + "jump", + TaskKind::Jump { + release_tick, + from_y, + }, + reply, + 5.0, + ) + } + "goto" => { + self.playing()?; + let target = [a.f64(0, "X")?, a.f64(1, "Y")?, a.f64(2, "Z")?]; + let near = a.num("near", 0.6)?.max(0.3); + let timeout = a.num("timeout", 60.0)?; + let p = self.player.as_ref().ok_or("no player")?.position; + let from = [p.x.floor() as i32, p.y.round() as i32, p.z.floor() as i32]; + let (path, warning) = match self.find_path(from, target, near) { + Some(path) => (path, None), + None if a.has("direct") => ( + Vec::new(), + Some("no path found through loaded terrain; walking straight".to_owned()), + ), + None => { + return Err(format!( + "no walking path to {target:?} through loaded terrain (climbs of more than one block, drops of more than three, lava and unloaded chunks are avoided); pick a nearer or lower spot, raise --near, or use --direct to walk straight at it" + ) + .into()); + } + }; + let goto = Goto { + target, + near, + sprint: a.has("sprint"), + path, + next: 1, + progress_tick: self.ticks, + replans: 0, + jump_until: 0, + warning, + }; + self.start_task("goto", TaskKind::Goto(Box::new(goto)), reply, timeout) + } + "look-at" => { + self.need_world()?; + match a.pos.first().copied() { + Some("block") => { + let pos = a.block_pos(1)?; + let face = a.pos.get(4).map(|f| face_dir(f)).transpose()?; + let hit = self.aim_block(pos, face)?; + ok( + json!({ "ok": true, "yaw": self.yaw, "pitch": self.pitch, "face": face_name(hit) }), + ) + } + Some("entity") => { + let id: u32 = a.get(1, "ID")?.parse()?; + let m = self + .mobs + .iter() + .find(|m| m.id == id) + .ok_or_else(|| format!("no entity {id}"))?; + let c = m.center(); + self.face_point(c)?; + ok( + json!({ "ok": true, "yaw": self.yaw, "pitch": self.pitch, "target": self.looking_at() }), + ) + } + _ => { + let at = [a.f64(0, "X")?, a.f64(1, "Y")?, a.f64(2, "Z")?]; + self.face_point(at)?; + ok(json!({ "ok": true, "yaw": self.yaw, "pitch": self.pitch })) + } + } + } + "attack" => { + self.playing()?; + let id = a.pos.first().map(|i| i.parse::()).transpose()?; + if let Some(id) = id { + let m = self + .mobs + .iter() + .find(|m| m.id == id) + .ok_or_else(|| format!("no entity {id}"))?; + let c = m.center(); + self.face_point(c)?; + } + let target = self + .mob_hit() + .map(|(i, _)| (self.mobs[i].id, self.mobs[i].health)); + if id.is_some() && target.map(|t| t.0) != id { + return Err("that entity is out of reach or hidden; get closer".into()); + } + self.agent_mouse(MouseButton::Left, true)?; + self.agent_mouse(MouseButton::Left, false)?; + let report_tick = self.ticks + 4; + self.start_task( + "attack", + TaskKind::Attack { + id: target.map(|t| t.0), + health: target.map(|t| t.1), + report_tick, + }, + reply, + 5.0, + ) + } + "break" => { + self.playing()?; + let pos = a.block_pos(0)?; + let before = self.world.block(pos[0], pos[1], pos[2]); + if self.res.facts.is_air(before) { + return Err(format!("there is no block at {pos:?}").into()); + } + self.aim_block(pos, None)?; + let timeout = a.num("timeout", 30.0)?; + let task = Break { + pos, + before, + items_before: self.dropped.iter().map(|i| i.id).collect(), + inventory: self.inventory_counts(), + started_tick: self.ticks, + collect_until: None, + broke_tick: 0, + drops: BTreeMap::new(), + }; + self.agent_mouse(MouseButton::Left, true)?; + self.start_task("break", TaskKind::Break(Box::new(task)), reply, timeout) + } + "place" => { + self.playing()?; + let pos = a.block_pos(0)?; + if let Some(Some(item)) = a.flags.get("item") { + self.select_item(&namespaced(item))?; + } + let held = self + .held() + .ok_or("nothing in hand to place; select an item")?; + let held = held.item.clone(); + let before = self.world.block(pos[0], pos[1], pos[2]); + if !self.res.facts.get(before).replaceable && !self.res.facts.is_air(before) { + return Err(format!( + "{pos:?} holds {}; break it first", + self.res.facts.get(before).name + ) + .into()); + } + // A replaceable block there (grass, snow) is clicked itself, as + // a player would; otherwise the face of a neighbour touching it. + let mut aimed = !self.res.facts.is_air(before) + && !self.res.facts.get(before).outline.is_empty() + && self.aim_block(pos, None).is_ok(); + for (_, d) in FACES.iter().filter(|_| !aimed) { + let d = *d; + let support = add(pos, d); + let state = self.world.block(support[0], support[1], support[2]); + let f = self.res.facts.get(state); + if self.res.facts.is_air(state) + || f.replaceable + || f.fluid != horizon_client::blocks::Fluid::None && !f.waterlogged + { + continue; + } + let face = d.map(|v| -v); + if self.aim_block(support, Some(face)).is_ok() { + aimed = true; + break; + } + } + if !aimed { + return Err(format!( + "no visible face to place {held} against at {pos:?}; it needs a solid neighbour in reach" + ) + .into()); + } + let inventory = self.inventory_counts(); + self.agent_mouse(MouseButton::Right, true)?; + self.agent_mouse(MouseButton::Right, false)?; + let report_tick = self.ticks + 2; + self.start_task( + "place", + TaskKind::Click { + pos: Some(pos), + before: Some(before), + inventory, + report_tick, + release: None, + place: true, + }, + reply, + 5.0, + ) + } + "interact" | "use-item" => { + self.playing()?; + let hold = a.num("hold", 0.0)?; + let pos = if name == "interact" { + let pos = a.block_pos(0)?; + let face = a.pos.get(3).map(|f| face_dir(f)).transpose()?; + self.aim_block(pos, face)?; + Some(pos) + } else { + None + }; + let before = pos.map(|p| self.world.block(p[0], p[1], p[2])); + let inventory = self.inventory_counts(); + self.agent_mouse(MouseButton::Right, true)?; + let release = if hold > 0.0 { + Some(Instant::now() + Duration::from_secs_f64(hold)) + } else { + self.agent_mouse(MouseButton::Right, false)?; + None + }; + let report_tick = self.ticks + 2; + self.start_task( + if name == "interact" { + "interact" + } else { + "use-item" + }, + TaskKind::Click { + pos, + before, + inventory, + report_tick, + release, + place: false, + }, + reply, + hold + 5.0, + ) + } + "select" => { + self.need_world()?; + let what = a.get(0, "SLOT or ITEM")?; + match what.parse::() { + Ok(n) if (1..=9).contains(&n) => self.selected = n - 1, + Ok(_) => return Err("hotbar slots are 1..9".into()), + Err(_) => self.select_item(&namespaced(what))?, + } + ok( + json!({ "ok": true, "selected": self.selected + 1, "held": self.held().map(|s| self.stack_value(s)) }), + ) + } + "drop" => { + self.playing()?; + let all = a.pos.first() == Some(&"all"); + let before = self.held().map(|s| self.stack_value(s)); + if all { + self.keys.insert(KeyCode::ControlLeft); + } + let result = self.key_pressed(KeyCode::KeyQ); + if all { + self.keys.remove(&KeyCode::ControlLeft); + } + result?; + ok( + json!({ "ok": true, "dropped_from": before, "held": self.held().map(|s| self.stack_value(s)) }), + ) + } + "open-inventory" => { + self.playing()?; + self.key_pressed(KeyCode::KeyE)?; + ok(json!({ "ok": true, "screen": self.screen_label() })) + } + "click-button" => { + let label = line + .trim_start() + .strip_prefix("click-button") + .unwrap_or("") + .trim() + .trim_matches('"'); + if label.is_empty() { + return Err("click-button LABEL".into()); + } + let w = widgets::find(&widgets::last(), label)?; + if !w.enabled { + return Err(format!("button {:?} is disabled", w.label).into()); + } + self.synth_click( + event_loop, + w.x + w.w / 2.0, + w.y + w.h / 2.0, + MouseButton::Left, + )?; + ok(json!({ "ok": true, "clicked": w.label, "screen": self.screen_label() })) + } + "click-at" => { + let (x, y) = (a.f64(0, "X")? as f32, a.f64(1, "Y")? as f32); + let button = if a.pos.get(2) == Some(&"right") { + MouseButton::Right + } else { + MouseButton::Left + }; + self.synth_click(event_loop, x, y, button)?; + ok(json!({ "ok": true, "screen": self.screen_label() })) + } + "type" if self.title.is_some() => { + // type [--field name|seed] [--replace] TEXT on the title screens. + let mut text = line + .trim_start() + .strip_prefix("type") + .unwrap_or("") + .strip_prefix(' ') + .unwrap_or(""); + let mut field = None; + let mut replace = false; + loop { + if let Some(rest) = text.strip_prefix("--replace") { + replace = true; + text = rest.trim_start(); + } else if let Some(rest) = text.strip_prefix("--field") { + let rest = rest.trim_start(); + let (name, rest) = rest.split_once(' ').unwrap_or((rest, "")); + field = Some(name.to_owned()); + text = rest; + } else { + break; + } + } + let title = self.title.as_mut().ok_or("no title screen")?; + if let Some(field) = &field { + match &mut title.mode { + horizon_client::title::Mode::Create { focus, .. } => { + *focus = match field.as_str() { + "name" => 0, + "seed" => 1, + other => { + return Err(format!( + "the create-world fields are name and seed, not {other}" + ) + .into()); + } + } + } + _ => return Err("--field works on the create-world screen".into()), + } + } + if replace { + for _ in 0..64 { + title.backspace(); + } + } + if text == "\\b" { + title.backspace(); + } else { + title.type_text(text); + } + ok(json!({ "ok": true, "menu": self.title_value() })) + } + "command" => { + self.need_world()?; + let text = line + .trim_start() + .strip_prefix("command") + .unwrap_or("") + .trim() + .trim_start_matches('/'); + if text.is_empty() { + return Err("command TEXT".into()); + } + let command = format!("/{text}"); + if self.remote.is_some() { + self.send_chat(&command); + return ok(json!({ "ok": true })); + } + self.handle_chat_input(&command); + ok(json!({ "ok": true, "chat": self.ui.chat.recent_lines(5) })) + } + "respawn" if self.remote.is_none() => { + if self.screen != Screen::Dead { + return Err("respawn needs the death screen".into()); + } + let label = + horizon_client::text::Text::translate("deathScreen.respawn", &[]).plain(); + let w = widgets::find(&widgets::last(), &label)?; + self.synth_click( + event_loop, + w.x + w.w / 2.0, + w.y + w.h / 2.0, + MouseButton::Left, + )?; + ok(json!({ "ok": true, "screen": self.screen_label() })) + } + "pause" => { + self.playing()?; + self.key_pressed(KeyCode::Escape)?; + ok(json!({ "ok": true, "screen": self.screen_label() })) + } + "wait" => { + self.need_world()?; + let ticks: u64 = a.get(0, "TICKS")?.parse()?; + let until_tick = self.ticks + ticks; + let timeout = ticks as f64 / 20.0 * 4.0 + 10.0; + self.start_task("wait", TaskKind::Wait { until_tick }, reply, timeout) + } + "stop" => { + let cancelled = self.agent.task.take().map(|t| { + let _ = t.reply.send( + json!({ "error": "cancelled by stop", "cancelled": true }).to_string(), + ); + t.name + }); + self.release_agent_keys(); + ok(json!({ "ok": true, "cancelled": cancelled })) + } + _ => Ok(Handled::No), + } + } + + /// Select the hotbar slot holding `item`. + fn select_item(&mut self, item: &str) -> Result<()> { + if let Some(i) = + (0..9).find(|&i| self.inventory[i].as_ref().is_some_and(|s| &*s.item == item)) + { + self.selected = i; + return Ok(()); + } + if self.inventory.iter().flatten().any(|s| &*s.item == item) { + return Err(format!( + "{item} is in the main inventory, not the hotbar; move it with open-inventory and click-slot" + ) + .into()); + } + Err(format!("no {item} in the inventory").into()) + } + + /// Advance the running agent task; reply when it ends. + pub(super) fn advance_agent(&mut self) { + let Some(mut task) = self.agent.task.take() else { + return; + }; + let timed_out = Instant::now() >= task.deadline; + let result = self.step_task(&mut task.kind, timed_out); + match result { + Some(value) => { + self.release_agent_keys(); + let _ = task.reply.send(value.to_string()); + } + None => self.agent.task = Some(task), + } + } + + fn position(&self) -> [f64; 3] { + self.player + .as_ref() + .map_or([0.0; 3], |p| [p.position.x, p.position.y, p.position.z]) + } + + /// One frame of a task: Some(reply) when it is over. + fn step_task(&mut self, kind: &mut TaskKind, timed_out: bool) -> Option { + // Leaving the world (death, a screen, the title) ends movement tasks. + let interrupted = if self.title.is_some() || self.player.is_none() { + Some("the world closed") + } else if self.screen == Screen::Dead { + Some("the player died") + } else { + None + }; + match kind { + TaskKind::Move { keys, until, from } => { + if let Some(why) = interrupted { + return Some(json!({ "error": why, "position": self.position() })); + } + for &k in keys.iter() { + self.keys.insert(k); + } + if Instant::now() < *until && !timed_out { + return None; + } + let to = self.position(); + Some( + json!({ "ok": true, "from": [from.x, from.y, from.z], "position": to, + "moved": dist([from.x, from.y, from.z], to) }), + ) + } + TaskKind::Wait { until_tick } => { + if self.ticks >= *until_tick { + Some(json!({ "ok": true, "ticks": self.ticks })) + } else if timed_out { + Some( + json!({ "error": "game ticks are not advancing (paused?)", "ticks": self.ticks }), + ) + } else { + None + } + } + TaskKind::Jump { + release_tick, + from_y, + } => { + if self.ticks >= *release_tick || timed_out { + self.keys.remove(&KeyCode::Space); + let on_ground = self.player.as_ref().is_some_and(|p| p.ground.on_ground); + if on_ground || timed_out { + return Some( + json!({ "ok": true, "from_y": from_y, "position": self.position() }), + ); + } + } + None + } + TaskKind::Goto(goto) => { + if let Some(why) = interrupted { + return Some(json!({ "error": why, "position": self.position() })); + } + if self.screen != Screen::Playing { + return Some( + json!({ "error": format!("the {} screen opened", self.screen_label()), "position": self.position() }), + ); + } + self.step_goto(goto, timed_out) + } + TaskKind::Break(b) => self.step_break(b, timed_out, interrupted), + TaskKind::Click { + pos, + before, + inventory, + report_tick, + release, + place, + } => { + if let Some(at) = release { + if Instant::now() < *at && !timed_out && interrupted.is_none() { + return None; + } + let _ = self.agent_mouse(MouseButton::Right, false); + *release = None; + *report_tick = self.ticks + 2; + } + if self.ticks < *report_tick && !timed_out { + return None; + } + let after = pos.map(|p| self.block_json(p)); + let changed = match (*pos, *before) { + (Some(p), Some(b)) => self.world.block(p[0], p[1], p[2]) != b, + _ => false, + }; + let used = delta(inventory, &self.inventory_counts()); + let mut v = json!({ + "ok": !*place || changed, + "block_before": before.map(|b| self.state_string(b)), + "block": after, + "changed": changed, + "inventory_change": used, + "screen": self.screen_label(), + }); + if *place && !changed { + v["error"] = json!( + "the block did not change (blocked by an entity, or the item cannot be placed)" + ); + } + Some(v) + } + TaskKind::Attack { + id, + health, + report_tick, + } => { + if self.ticks < *report_tick && !timed_out { + return None; + } + let now = id.and_then(|id| self.mobs.iter().find(|m| m.id == id)); + Some(json!({ + "ok": true, + "target": id, + "health_before": health, + "health": now.map(|m| m.health), + "alive": now.is_some_and(|m| m.alive()), + "hit": id.is_some(), + })) + } + } + } + + fn step_goto(&mut self, g: &mut Goto, timed_out: bool) -> Option { + let p = self.position(); + let on_ground = self.player.as_ref().is_some_and(|p| p.ground.on_ground); + let horizontal = + |a: [f64; 3], b: [f64; 3]| ((a[0] - b[0]).powi(2) + (a[2] - b[2]).powi(2)).sqrt(); + let arrived = horizontal(p, g.target) <= g.near + && (p[1] - g.target[1]).abs() <= g.near.max(1.0) + 1.0; + if arrived { + return Some( + json!({ "ok": true, "arrived": true, "position": p, "target": g.target, + "distance": dist(p, g.target), "warning": g.warning }), + ); + } + if timed_out { + return Some( + json!({ "error": "timed out before arriving", "arrived": false, "position": p, + "target": g.target, "distance": dist(p, g.target), "warning": g.warning }), + ); + } + // The next waypoint: path nodes, then the target itself. + let mut aim = g.target; + while g.next < g.path.len() { + let n = g.path[g.next]; + let c = [ + f64::from(n[0]) + 0.5, + f64::from(n[1]), + f64::from(n[2]) + 0.5, + ]; + let last = g.next + 1 == g.path.len(); + if horizontal(p, c) < if last { 0.3 } else { 0.45 } && (p[1] - c[1]).abs() < 1.1 { + g.next += 1; + g.progress_tick = self.ticks; + continue; + } + aim = c; + break; + } + // Stuck: jump, then replan from here. + let stalled = self.ticks.saturating_sub(g.progress_tick); + if stalled > 60 && on_ground { + g.jump_until = self.ticks + 4; + } + if stalled > 120 { + g.replans += 1; + if g.replans > 3 { + return Some( + json!({ "error": "stuck: cannot make progress", "arrived": false, "position": p, + "target": g.target, "distance": dist(p, g.target) }), + ); + } + let from = [ + p[0].floor() as i32, + p[1].round() as i32, + p[2].floor() as i32, + ]; + if let Some(path) = self.find_path(from, g.target, g.near) { + g.path = path; + g.next = 1; + } + g.progress_tick = self.ticks; + } + let d = [aim[0] - p[0], aim[2] - p[2]]; + if d[0].abs() + d[1].abs() > 1e-3 { + self.yaw = (-d[0]).atan2(d[1]).to_degrees() as f32; + } + self.keys.insert(KeyCode::KeyW); + if g.sprint { + self.keys.insert(KeyCode::ControlLeft); + } + // Step up onto the next block, or out of water. + let in_water = { + let b = p.map(|v| v.floor() as i32); + self.res.facts.get(self.world.block(b[0], b[1], b[2])).fluid + != horizon_client::blocks::Fluid::None + }; + if aim[1] > p[1] + 0.5 && horizontal(p, aim) < 1.6 && on_ground { + g.jump_until = self.ticks + 4; + } + if self.ticks < g.jump_until || in_water { + self.keys.insert(KeyCode::Space); + } else { + self.keys.remove(&KeyCode::Space); + } + None + } + + fn step_break( + &mut self, + b: &mut Break, + timed_out: bool, + interrupted: Option<&str>, + ) -> Option { + let state = self.world.block(b.pos[0], b.pos[1], b.pos[2]); + if b.collect_until.is_none() { + if let Some(why) = interrupted { + return Some(json!({ "error": why, "pos": b.pos })); + } + if state != b.before { + // Broken: collect what drops for a moment. + let _ = self.agent_mouse(MouseButton::Left, false); + b.broke_tick = self.ticks; + b.collect_until = Some(self.ticks + 20); + } else if timed_out { + let _ = self.agent_mouse(MouseButton::Left, false); + return Some( + json!({ "error": "timed out before the block broke", "pos": b.pos, + "block": self.state_string(state), "ticks": self.ticks - b.started_tick }), + ); + } else if self.screen != Screen::Playing { + return Some( + json!({ "error": format!("the {} screen opened", self.screen_label()), "pos": b.pos }), + ); + } else { + // Keep the crosshair on the block (the player may drift). + if self.pick().is_none_or(|h| h.pos != b.pos) + && let Err(e) = self.aim_block(b.pos, None) + { + let _ = self.agent_mouse(MouseButton::Left, false); + return Some(json!({ "error": e.to_string(), "pos": b.pos })); + } + if !self.left { + let _ = self.agent_mouse(MouseButton::Left, true); + } + return None; + } + } + // New item entities near the block are its drops. + let centre = b.pos.map(|v| f64::from(v) + 0.5); + for item in &self.dropped { + if !b.items_before.contains(&item.id) + && dist(centre, [item.position.x, item.position.y, item.position.z]) < 3.0 + { + b.drops.insert(item.id, item.stack.clone()); + } + } + let remaining = b + .drops + .keys() + .filter(|id| self.dropped.iter().any(|i| i.id == **id)) + .count(); + let until = b.collect_until.unwrap_or(0); + if (self.ticks < until && (remaining > 0 || self.ticks < b.broke_tick + 3)) && !timed_out { + return None; + } + Some(json!({ + "ok": true, + "pos": b.pos, + "block_before": self.state_string(b.before), + "block": self.state_string(state), + "ticks": b.broke_tick - b.started_tick, + "drops": counts(b.drops.values().cloned()), + "picked_up": delta(&b.inventory, &self.inventory_counts()), + "items_left_on_ground": remaining, + "on_ground": self.dropped.iter().filter(|i| b.drops.contains_key(&i.id)).map(|i| json!({ + "id": i.id, "item": &*i.stack.item, "count": i.stack.count, + "pos": [i.position.x, i.position.y, i.position.z], + })).collect::>(), + })) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_flags_and_values() { + let a = parse_args(&["1", "2", "--near", "3", "--sprint", "--timeout=9", "-4"]); + assert_eq!(a.pos, ["1", "2", "-4"]); + assert_eq!(a.flags["near"], Some("3")); + assert_eq!(a.flags["sprint"], None); + assert_eq!(a.flags["timeout"], Some("9")); + assert_eq!(a.num("near", 0.0).unwrap(), 3.0); + assert_eq!(a.num("missing", 7.0).unwrap(), 7.0); + assert!(a.f64(5, "X").is_err()); + assert_eq!(a.block_pos(0).ok(), Some([1, 2, -4])); + assert!(a.block_pos(1).is_err()); + assert_eq!( + parse_args(&["-1", "64", "2"]).block_pos(0).unwrap(), + [-1, 64, 2] + ); + } + + #[test] + fn yaw_and_pitch_follow_minecraft() { + let (yaw, pitch) = yaw_pitch([0.0; 3], [0.0, 0.0, 1.0]); + assert!(yaw.abs() < 1e-4 && pitch.abs() < 1e-4); + let (yaw, _) = yaw_pitch([0.0; 3], [-1.0, 0.0, 0.0]); + assert!((yaw - 90.0).abs() < 1e-4); + let (_, pitch) = yaw_pitch([0.0; 3], [0.0, -1.0, 0.0]); + assert!((pitch - 90.0).abs() < 1e-4); + } + + #[test] + fn faces_round_trip() { + for (name, dir) in FACES { + assert_eq!(face_dir(name).unwrap(), dir); + assert_eq!(face_name(dir), name); + } + assert!(face_dir("sideways").is_err()); + } + + #[test] + fn inventory_delta() { + let before = BTreeMap::from([("a".to_owned(), 2), ("b".to_owned(), 1)]); + let after = BTreeMap::from([("a".to_owned(), 5), ("c".to_owned(), 1)]); + let d = delta(&before, &after); + assert_eq!( + d, + BTreeMap::from([ + ("a".to_owned(), 3), + ("b".to_owned(), -1), + ("c".to_owned(), 1) + ]) + ); + } +} diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index e64942da7..01ac9da9d 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -87,6 +87,8 @@ impl Game<'_> { self.pending_bench = Some((deadline, reply)); } } + horizon_client::widgets::end_frame(self.frames); + self.advance_agent(); while let Some(request) = self.control.as_ref().and_then(|c| c.try_recv()) { let reply = match self.control_command(&request.line, &request.reply, event_loop) { Ok(Some(value)) => value, @@ -118,6 +120,11 @@ impl Game<'_> { if let Some(value) = self.lan_control(&words)? { return Ok(Some(value)); } + match self.agent_command(&words, line, reply, event_loop)? { + super::agent::Handled::Reply(value) => return Ok(Some(value)), + super::agent::Handled::Deferred => return Ok(None), + super::agent::Handled::No => {} + } match words[0] { "help" => Ok(Some(json!({ "commands": HELP .iter() @@ -126,6 +133,7 @@ impl Game<'_> { .chain(super::lan::HELP) .chain(super::render_control::HELP) .chain(super::sculk::HELP) + .chain(super::agent::HELP) .collect::>() }))), "setblock" | "fill" | "particle" | "signedit" => self.render_command(&words), "sculk" => Ok(Some(self.sculk_command(&words)?)), diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index f7900e743..0bb7e0dd9 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -128,6 +128,7 @@ pub mod title; pub mod ui; pub mod ui_theme; pub mod vanillagen; +pub mod widgets; pub mod window; pub mod world; pub mod worldborder; diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index c5c467616..bd783bfd2 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -408,6 +408,7 @@ impl Title { ), } for b in self.buttons(w, h) { + crate::widgets::record(&b.label, [b.x, b.y, b.w, 20.0], b.enabled); let hover = b.enabled && cursor.0 >= b.x && cursor.0 < b.x + b.w diff --git a/crates/horizon-client/src/ui.rs b/crates/horizon-client/src/ui.rs index b1340eb8a..407504cbd 100644 --- a/crates/horizon-client/src/ui.rs +++ b/crates/horizon-client/src/ui.rs @@ -247,6 +247,7 @@ pub fn button( active: bool, hover: bool, ) { + crate::widgets::record(&label.plain(), [x, y, w, h], active); let sprite = if !active { "gui/sprites/widget/button_disabled" } else if hover { diff --git a/crates/horizon-client/src/ui_theme.rs b/crates/horizon-client/src/ui_theme.rs index 9077ab613..bcbc31a69 100644 --- a/crates/horizon-client/src/ui_theme.rs +++ b/crates/horizon-client/src/ui_theme.rs @@ -845,6 +845,12 @@ impl<'a> Ui<'a> { kind: Kind, enabled: bool, ) -> f32 { + if self.real { + // The control socket's button list, in GUI pixels. + let k = self.density / self.scale; + let (ox, oy) = self.offset; + crate::widgets::record(label, [(x + ox) * k, (y + oy) * k, w * k, h * k], enabled); + } let hover = self.interact(id, x, y, w, h, enabled); let saved = self.opacity; if !enabled { diff --git a/crates/horizon-client/src/widgets.rs b/crates/horizon-client/src/widgets.rs new file mode 100644 index 000000000..75366dcba --- /dev/null +++ b/crates/horizon-client/src/widgets.rs @@ -0,0 +1,120 @@ +//! The labelled buttons drawn in the last frame, for the control socket: a +//! script clicks a button by its label (`horizon-ctl click-button Respawn`) +//! whatever screen or menu style drew it. +use std::cell::RefCell; + +/// A button in GUI pixels (the coordinates screens take input in). +#[derive(Clone, Debug)] +pub struct Widget { + pub label: String, + pub x: f32, + pub y: f32, + pub w: f32, + pub h: f32, + pub enabled: bool, +} + +thread_local! { + /// Buttons drawn since the last `end_frame`, and the last frame's. + static WIDGETS: RefCell<(Vec, Vec, u64)> = const { RefCell::new((Vec::new(), Vec::new(), 0)) }; +} + +/// Called by the button drawers. +pub fn record(label: &str, [x, y, w, h]: [f32; 4], enabled: bool) { + let label = label.trim(); + if label.is_empty() { + return; + } + WIDGETS.with_borrow_mut(|(current, _, _)| { + if current.len() < 512 { + current.push(Widget { + label: label.to_owned(), + x, + y, + w, + h, + enabled, + }); + } + }); +} + +/// Once per event loop turn with the count of rendered frames: when a new +/// frame was drawn since the last call, its buttons become the last frame's. +pub fn end_frame(frames: u64) { + WIDGETS.with_borrow_mut(|(current, last, seen)| { + if *seen != frames { + *seen = frames; + *last = std::mem::take(current); + } + }); +} + +/// The buttons of the last drawn frame, top-most last. +pub fn last() -> Vec { + WIDGETS.with_borrow(|(_, last, _)| last.clone()) +} + +/// The button `label` names: an exact match (case-insensitive), else the only +/// button whose label contains it. The top-most wins among equals. +pub fn find(widgets: &[Widget], label: &str) -> Result { + let want = label.trim().to_lowercase(); + let exact: Vec<&Widget> = widgets + .iter() + .filter(|w| w.label.to_lowercase() == want) + .collect(); + if let Some(w) = exact.last() { + return Ok((*w).clone()); + } + let partial: Vec<&Widget> = widgets + .iter() + .filter(|w| w.label.to_lowercase().contains(&want)) + .collect(); + match partial.as_slice() { + [w] => Ok((*w).clone()), + [] => Err(format!( + "no button labelled {label:?}; buttons: {:?}", + widgets.iter().map(|w| w.label.as_str()).collect::>() + )), + many => Err(format!( + "{label:?} matches several buttons: {:?}", + many.iter().map(|w| w.label.as_str()).collect::>() + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn w(label: &str) -> Widget { + Widget { + label: label.into(), + x: 0.0, + y: 0.0, + w: 10.0, + h: 10.0, + enabled: true, + } + } + + #[test] + fn finds_exact_then_unique_partial() { + let list = [w("Play Selected World"), w("Create New World"), w("Back")]; + assert_eq!(find(&list, "back").unwrap().label, "Back"); + assert_eq!(find(&list, "create").unwrap().label, "Create New World"); + assert!(find(&list, "world").is_err()); + assert!(find(&list, "options").is_err()); + } + + #[test] + fn frames_rotate_only_when_drawn() { + record("Respawn", [1.0, 2.0, 3.0, 4.0], true); + end_frame(1); + assert_eq!(last().len(), 1); + end_frame(1); + assert_eq!(last().len(), 1); + end_frame(2); + assert!(last().is_empty()); + } +} From 24a70e84a86f5ad315610e7bb023ffc45ea7a907 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 21:57:09 +0200 Subject: [PATCH 3/8] horizon-ctl: help for every command, launch from the launcher, MCP server One command table drives horizon-ctl help, COMMAND --help (with examples) and the MCP tools. Replies stay one JSON line; errors are error objects with exit status 1 (game), 2 (usage) or 3 (unreachable). script runs a file or stdin with shell-like quoting. launch finds the game beside horizon-ctl or the newest launcher install (--version, --game), with its prepared resources and the game home, and --wait waits for the world. horizon-ctl mcp serves MCP over stdio in the launcher's style, one tool per command, with the screenshot returned as an image. Existing commands and replies are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/bin/horizon-ctl/commands.rs | 578 +++++++++++++++++ .../src/bin/horizon-ctl/launch.rs | 386 ++++++++++++ .../src/bin/horizon-ctl/main.rs | 582 +++++++++++++----- .../horizon-client/src/bin/horizon-ctl/mcp.rs | 238 +++++++ 4 files changed, 1635 insertions(+), 149 deletions(-) create mode 100644 crates/horizon-client/src/bin/horizon-ctl/commands.rs create mode 100644 crates/horizon-client/src/bin/horizon-ctl/launch.rs create mode 100644 crates/horizon-client/src/bin/horizon-ctl/mcp.rs diff --git a/crates/horizon-client/src/bin/horizon-ctl/commands.rs b/crates/horizon-client/src/bin/horizon-ctl/commands.rs new file mode 100644 index 000000000..91969d0c9 --- /dev/null +++ b/crates/horizon-client/src/bin/horizon-ctl/commands.rs @@ -0,0 +1,578 @@ +//! Every command horizon-ctl knows: its usage, help, examples and arguments. +//! The same table prints `help`, checks `COMMAND --help` and describes the +//! MCP tools, so the CLI and the MCP server always offer the same commands. +use serde_json::{Map, Value, json}; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Ty { + Int, + Num, + Str, + Bool, + /// One of these words. + Enum(&'static [&'static str]), + /// The rest of the line, spaces included. + Rest, +} + +#[derive(Clone, Copy)] +pub struct Param { + pub name: &'static str, + pub ty: Ty, + pub required: bool, + /// Sent as `--name value` (`--name` alone for booleans), not by position. + pub flag: bool, + pub help: &'static str, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Group { + Session, + Observe, + Move, + Act, + Screens, + World, + Scripting, +} +impl Group { + pub const ALL: [Group; 7] = [ + Group::Session, + Group::Observe, + Group::Move, + Group::Act, + Group::Screens, + Group::World, + Group::Scripting, + ]; + pub fn title(self) -> &'static str { + match self { + Group::Session => "Session", + Group::Observe => "Observe (JSON state)", + Group::Move => "Move and look", + Group::Act => "Act on the world", + Group::Screens => "Screens, menus and chat", + Group::World => "World and cheats", + Group::Scripting => "Scripting and benchmarks", + } + } +} + +pub struct Cmd { + pub name: &'static str, + /// What the game receives instead of `name` (aliases such as look-at-block). + pub wire: Option<&'static str>, + pub group: Group, + pub usage: &'static str, + pub summary: &'static str, + pub details: &'static str, + pub examples: &'static [&'static str], + pub params: &'static [Param], + /// Offered as an MCP tool. + pub mcp: bool, + /// Runs in horizon-ctl itself, not in the game. + pub local: bool, +} + +const fn p(name: &'static str, ty: Ty, help: &'static str) -> Param { + Param { + name, + ty, + required: true, + flag: false, + help, + } +} +const fn opt(name: &'static str, ty: Ty, help: &'static str) -> Param { + Param { + name, + ty, + required: false, + flag: false, + help, + } +} +const fn flag(name: &'static str, ty: Ty, help: &'static str) -> Param { + Param { + name, + ty, + required: false, + flag: true, + help, + } +} +const XYZ: [Param; 3] = [ + p("x", Ty::Num, "X coordinate"), + p("y", Ty::Num, "Y coordinate"), + p("z", Ty::Num, "Z coordinate"), +]; +const BLOCK_XYZ: [Param; 3] = [ + p("x", Ty::Int, "block X"), + p("y", Ty::Int, "block Y"), + p("z", Ty::Int, "block Z"), +]; +const FACE: Ty = Ty::Enum(&["down", "up", "north", "south", "west", "east"]); + +macro_rules! cmd { + ($name:expr, $group:ident, $usage:expr, $summary:expr, $details:expr, [$($ex:expr),* $(,)?], $params:expr, mcp: $mcp:expr, local: $local:expr $(, wire: $wire:expr)?) => { + Cmd { + name: $name, + wire: cmd!(@wire $($wire)?), + group: Group::$group, + usage: $usage, + summary: $summary, + details: $details, + examples: &[$($ex),*], + params: $params, + mcp: $mcp, + local: $local, + } + }; + (@wire) => { None }; + (@wire $w:expr) => { Some($w) }; +} + +pub const COMMANDS: &[Cmd] = &[ + // Session + cmd!("launch", Session, "launch [--world NAME] [--seed N] [--creative] [--version TAG] [--game PATH] [--wait] [GAME ARGS...]", + "start Horizon with the control socket and wait until it answers", + "Finds the game in this order: --game PATH; a horizon-client next to horizon-ctl (a build folder, a release folder or a launcher install); the newest version installed by the Horizon launcher (--version TAG picks one). Launcher installs run with their prepared resources and keep saves in the game home ($HORIZON_HOME, else ~/.local/share/horizon). --wait also waits until the player has spawned and chunks are loaded. Other arguments go to the game (horizon-client --help lists them). The game's output goes to a .log file beside the socket.", + ["horizon-ctl launch --world Survival --seed 42 --wait", "horizon-ctl launch --world Flat --creative --render-distance 8"], + &[flag("world", Ty::Str, "world folder to open or create"), flag("seed", Ty::Str, "seed for a new world"), flag("creative", Ty::Bool, "creative mode for a new world"), + flag("version", Ty::Str, "an installed launcher version tag such as v2026.10.13"), flag("game", Ty::Str, "path to a horizon-client binary"), + flag("wait", Ty::Bool, "also wait until the world is ready (default in MCP)")], + mcp: true, local: true), + cmd!("wait-ready", Session, "wait-ready [SECONDS]", "wait until the player has spawned and no chunks are pending", + "Polls status every 250 ms; replies with the status, or an error after SECONDS (default 120).", + ["horizon-ctl wait-ready 300"], &[opt("seconds", Ty::Num, "how long to wait (default 120)")], mcp: true, local: true), + cmd!("status", Session, "status", "game, renderer and streaming state (the scripting socket's original summary)", + "", ["horizon-ctl status"], &[], mcp: false, local: false), + cmd!("open", Session, "open WORLD [SEED] [creative]", "open or create a world from the title screen", + "Opens saves/WORLD, creating it with SEED (and creative mode) when it doesn't exist.", + ["horizon-ctl open Test 12345", "horizon-ctl open Build 0 creative"], + &[p("world", Ty::Str, "world folder"), opt("seed", Ty::Int, "seed for a new world"), opt("mode", Ty::Enum(&["creative"]), "creative for a creative world")], mcp: true, local: false), + cmd!("save", Session, "save", "save the world", "", ["horizon-ctl save"], &[], mcp: true, local: false), + cmd!("quit", Session, "quit", "save and exit the game", "", ["horizon-ctl quit"], &[], mcp: true, local: false), + cmd!("screenshot", Session, "screenshot PATH", "write the next rendered frame as a PNG", + "Relative paths are taken from horizon-ctl's directory. Over MCP the image is returned directly.", + ["horizon-ctl screenshot view.png"], &[], mcp: true, local: false), + // Observe + cmd!("state", Observe, "state", "player, world, screen and crosshair target in one reply", + "position, block_pos, eye, yaw, pitch, velocity, on_ground, health, food, saturation, xp, effects, gamemode, dimension, time, weather, the screen or title menu, the held item, what the crosshair points at and whether an action is running.", + ["horizon-ctl state"], &[], mcp: true, local: false), + cmd!("looking-at", Observe, "looking-at", "the block or entity under the crosshair", + "kind is block, entity or none; a block has pos, state, face, point and distance; an entity has id, type, health and distance.", + ["horizon-ctl looking-at"], &[], mcp: true, local: false), + cmd!("entities", Observe, "entities [RADIUS] [TYPE]", "mobs, dropped items and experience orbs near the player, nearest first", + "RADIUS defaults to 32. TYPE filters by entity type (pig, minecraft:item, ...). Mobs have an id for look-at entity and attack.", + ["horizon-ctl entities", "horizon-ctl entities 16 cow", "horizon-ctl entities 8 item"], + &[opt("radius", Ty::Num, "search radius in blocks (default 32)"), opt("type", Ty::Str, "entity type filter")], mcp: true, local: false), + cmd!("block", Observe, "block X Y Z", "the block state at a position", "", + ["horizon-ctl block 10 64 -3"], &BLOCK_XYZ, mcp: true, local: false), + cmd!("blocks", Observe, "blocks X1 Y1 Z1 X2 Y2 Z2", "the non-air blocks of a box, with counts per block", + "At most 32768 blocks per request.", ["horizon-ctl blocks 0 60 0 15 70 15"], + &[p("x1", Ty::Int, "corner X"), p("y1", Ty::Int, "corner Y"), p("z1", Ty::Int, "corner Z"), p("x2", Ty::Int, "opposite X"), p("y2", Ty::Int, "opposite Y"), p("z2", Ty::Int, "opposite Z")], mcp: true, local: false), + cmd!("find-block", Observe, "find-block BLOCK [RADIUS]", "the nearest loaded blocks of a kind", + "Searches a cube of RADIUS (default 32, at most 64) around the player; returns the count and the 16 nearest.", + ["horizon-ctl find-block oak_log", "horizon-ctl find-block diamond_ore 48"], + &[p("block", Ty::Str, "block id such as oak_log"), opt("radius", Ty::Int, "search radius (default 32)")], mcp: true, local: false), + cmd!("inventory", Observe, "inventory", "hotbar, main inventory, armor, offhand, carried stack and item counts", + "Slots carry the ids click-slot takes: 0-8 hotbar, 9-35 inventory, 500-503 armor (head to feet), 504 offhand. Stacks with components list them as SNBT.", + ["horizon-ctl inventory"], &[], mcp: true, local: false), + cmd!("screen", Observe, "screen", "the open screen or title menu, its buttons and its slots", + "buttons are what click-button takes; slots are what click-slot takes (crafting grid 100-103 in the inventory, 100-108 at a crafting table, result 200, containers from 300, stations from 600). On the title screen, menu has the mode, worlds and the create-world fields.", + ["horizon-ctl screen"], &[], mcp: true, local: false), + cmd!("messages", Observe, "messages [N]", "recent chat and system messages, the title and the action bar", + "N defaults to 20; chat is newest first.", ["horizon-ctl messages 5"], &[opt("n", Ty::Int, "how many chat lines (default 20)")], mcp: true, local: false), + cmd!("menu", Observe, "menu", "the open menu's slots and carried stack, with station details", "", + ["horizon-ctl menu"], &[], mcp: false, local: false), + // Move + cmd!("move", Move, "move forward|back|left|right SECONDS [--sprint] [--sneak] [--jump]", "walk in a direction relative to the view for a time", + "Replies when done with the start and end positions.", + ["horizon-ctl move forward 2", "horizon-ctl move forward 1.5 --sprint --jump"], + &[p("direction", Ty::Enum(&["forward", "back", "left", "right"]), "direction relative to the view"), p("seconds", Ty::Num, "how long to walk"), + flag("sprint", Ty::Bool, "sprint"), flag("sneak", Ty::Bool, "sneak"), flag("jump", Ty::Bool, "keep jumping")], mcp: true, local: false), + cmd!("goto", Move, "goto X Y Z [--near R] [--sprint] [--direct] [--timeout S]", "walk to a position, finding a path through loaded terrain", + "A* over standable blocks (steps up one block, drops up to three, avoids lava, swims when it must), then steering with jumps when stuck. Without a path it fails at once (--direct walks straight at the target anyway, falls included). --near R stops within R blocks (use 1.5-3 to reach a block you then break). Replies with arrived, position and distance, or an error when stuck or out of time (default 60 s).", + ["horizon-ctl goto 120 70 -40", "horizon-ctl goto 8 64 3 --near 2 --sprint"], + &[XYZ[0], XYZ[1], XYZ[2], flag("near", Ty::Num, "arrive within this many blocks (default 0.6)"), flag("sprint", Ty::Bool, "sprint"), flag("direct", Ty::Bool, "walk straight when no path is found"), flag("timeout", Ty::Num, "give up after this many seconds (default 60)")], mcp: true, local: false), + cmd!("jump", Move, "jump", "jump once and reply when landed", "", ["horizon-ctl jump"], &[], mcp: true, local: false), + cmd!("look", Move, "look YAW PITCH", "set the view direction in degrees", + "Yaw 0 faces south (+Z), 90 west (-X), 180 north, -90 east; pitch 90 looks straight down.", + ["horizon-ctl look 90 10"], &[p("yaw", Ty::Num, "yaw in degrees"), p("pitch", Ty::Num, "pitch in degrees (-90 up .. 90 down)")], mcp: true, local: false), + cmd!("turn", Move, "turn DYAW DPITCH", "rotate the view by an amount", "", ["horizon-ctl turn 45 0"], + &[p("dyaw", Ty::Num, "yaw change"), p("dpitch", Ty::Num, "pitch change")], mcp: false, local: false), + cmd!("look-at", Move, "look-at X Y Z | look-at block X Y Z [FACE] | look-at entity ID", "turn to face a point, a block (a visible face of it) or an entity", + "look-at block aims at a face the crosshair can reach and fails when none is visible.", + ["horizon-ctl look-at 10.5 65 3.5", "horizon-ctl look-at block 10 64 3 up", "horizon-ctl look-at entity 42"], + &XYZ, mcp: true, local: false), + cmd!("look-at-block", Move, "look-at-block X Y Z [FACE]", "aim the crosshair at a block (same as look-at block)", "", + ["horizon-ctl look-at-block 10 64 3"], &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], opt("face", FACE, "which face to aim at")], mcp: true, local: false, wire: "look-at block"), + cmd!("look-at-entity", Move, "look-at-entity ID", "face an entity (same as look-at entity)", "", + ["horizon-ctl look-at-entity 42"], &[p("id", Ty::Int, "entity id from entities")], mcp: true, local: false, wire: "look-at entity"), + cmd!("tp", Move, "tp X Y Z", "teleport the player", "", ["horizon-ctl tp 0 80 0"], &XYZ, mcp: true, local: false), + // Act + cmd!("break", Act, "break X Y Z [--timeout S]", "mine a block, holding the attack button until it breaks", + "Aims at a visible face (the block must be within reach: use goto --near 2 first), mines with the held item, then waits up to a second for the drops. Replies with block_before, block, ticks, drops and picked_up (inventory change).", + ["horizon-ctl break 10 64 3"], &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], flag("timeout", Ty::Num, "give up after this many seconds (default 30)")], mcp: true, local: false), + cmd!("place", Act, "place X Y Z [--item ITEM]", "place the held item (or ITEM from the hotbar) at an empty position", + "Clicks the face of a solid neighbour touching X Y Z. Replies with the block placed and the inventory change.", + ["horizon-ctl place 10 64 4 --item oak_planks"], &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], flag("item", Ty::Str, "hotbar item to select first")], mcp: true, local: false), + cmd!("interact", Act, "interact X Y Z [FACE]", "right-click a block: open a chest or crafting table, press a button, open a door", + "Replies with the screen afterwards and whether the block changed.", ["horizon-ctl interact 5 64 2"], + &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], opt("face", FACE, "which face to click")], mcp: true, local: false), + cmd!("use-item", Act, "use-item [--hold SECONDS]", "right-click with the held item: eat, drink, throw, draw a bow", + "Hold for 1.7 s to eat.", ["horizon-ctl use-item --hold 1.7"], &[flag("hold", Ty::Num, "hold the button this long")], mcp: true, local: false), + cmd!("attack", Act, "attack [ID]", "swing at what the crosshair targets (after facing entity ID)", + "Replies with the target's health before and after.", ["horizon-ctl attack", "horizon-ctl attack 42"], + &[opt("id", Ty::Int, "entity id to face first")], mcp: true, local: false), + cmd!("select", Act, "select SLOT|ITEM", "select a hotbar slot 1-9, or the hotbar slot holding ITEM", "", + ["horizon-ctl select 3", "horizon-ctl select oak_planks"], &[p("slot", Ty::Str, "1-9 or an item id")], mcp: true, local: false), + cmd!("drop", Act, "drop [all]", "drop one of the held item, or the whole stack", "", ["horizon-ctl drop", "horizon-ctl drop all"], + &[opt("all", Ty::Bool, "drop the whole stack")], mcp: true, local: false), + cmd!("hold", Act, "hold KEY SECONDS", "press a key, wait, release it", "Keys as for key.", ["horizon-ctl hold w 2"], + &[p("key", Ty::Str, "key name"), p("seconds", Ty::Num, "how long")], mcp: false, local: true), + cmd!("key", Act, "key KEY down|up|tap", "press or release a key (w a s d space shift ctrl e q esc f3 1-9 arrows ...)", "", + ["horizon-ctl key space tap"], &[p("key", Ty::Str, "key name"), p("action", Ty::Enum(&["down", "up", "tap"]), "what to do")], mcp: true, local: false), + cmd!("mouse", Act, "mouse left|right|middle down|up|click", "press or release a mouse button in the world", "", + ["horizon-ctl mouse right click"], &[p("button", Ty::Enum(&["left", "right", "middle"]), "button"), p("action", Ty::Enum(&["down", "up", "click"]), "what to do")], mcp: false, local: false), + cmd!("release", Act, "release", "release every key and mouse button", "", ["horizon-ctl release"], &[], mcp: false, local: false), + cmd!("stop", Act, "stop", "cancel the running action (goto, break...) and release every key", "", ["horizon-ctl stop"], &[], mcp: true, local: false), + // Screens + cmd!("open-inventory", Screens, "open-inventory", "open the inventory screen (crafting grid 100-103, result 200)", "", + ["horizon-ctl open-inventory"], &[], mcp: true, local: false), + cmd!("click-slot", Screens, "click-slot SLOT [right] [shift]", "click a slot of the open inventory or menu", + "SLOT ids as listed by screen: 0-8 hotbar, 9-35 inventory, 100+ crafting grid, 200 result, 300+ container, 500-503 armor, 504 offhand, 600+ station. A left click picks up or puts down the carried stack; right puts down one item; shift moves the stack across.", + ["horizon-ctl click-slot 36", "horizon-ctl click-slot 100 right", "horizon-ctl click-slot 200 shift"], + &[p("slot", Ty::Int, "slot id"), opt("right", Ty::Bool, "right-click"), opt("shift", Ty::Bool, "shift-click")], mcp: true, local: false), + cmd!("close", Screens, "close", "close the open menu and return to the game", "", ["horizon-ctl close"], &[], mcp: true, local: false), + cmd!("click-button", Screens, "click-button LABEL", "click a button of the open screen or title menu by its label", + "Case-insensitive; a unique part of the label is enough. screen lists the buttons.", + ["horizon-ctl click-button Singleplayer", "horizon-ctl click-button \"Create New World\"", "horizon-ctl click-button respawn"], + &[p("label", Ty::Rest, "button label")], mcp: true, local: false), + cmd!("click-at", Screens, "click-at X Y [right]", "click at GUI pixel X Y of the window (screen gives button rectangles)", "", + ["horizon-ctl click-at 200 120"], &[p("x", Ty::Num, "GUI x"), p("y", Ty::Num, "GUI y"), opt("right", Ty::Bool, "right-click")], mcp: true, local: false), + cmd!("type", Screens, "type [--field name|seed] [--replace] TEXT", "type into the focused text field (chat box, world name, anvil, sign...)", + "On the title's create-world screen, --field name|seed picks the field and --replace clears it first; type \\b deletes one character.", + ["horizon-ctl type hello everyone", "horizon-ctl type --field name --replace Agent World", "horizon-ctl type --field seed 12345"], &[flag("field", Ty::Enum(&["name", "seed"]), "create-world field to type into"), flag("replace", Ty::Bool, "clear the field first"), p("text", Ty::Rest, "text to type")], mcp: true, local: false), + cmd!("chat", Screens, "chat TEXT", "send a chat line (or a /command) as if typed", "", ["horizon-ctl chat hello"], + &[p("text", Ty::Rest, "message")], mcp: true, local: false), + cmd!("command", Screens, "command TEXT", "run a command (the leading / is optional)", "", + ["horizon-ctl command time set day", "horizon-ctl command /give @s oak_log 4"], &[p("command", Ty::Rest, "command line")], mcp: true, local: false), + cmd!("respawn", Screens, "respawn", "respawn from the death screen", "", ["horizon-ctl respawn"], &[], mcp: true, local: false), + cmd!("pause", Screens, "pause", "open the pause menu", "", ["horizon-ctl pause"], &[], mcp: true, local: false), + cmd!("resume", Screens, "resume", "leave the pause menu", "", ["horizon-ctl resume"], &[], mcp: true, local: false), + cmd!("chat-log", Screens, "chat-log [N]", "the newest N chat messages", "", ["horizon-ctl chat-log 5"], &[], mcp: false, local: false), + // World + cmd!("give", World, "give ITEM [COUNT]", "add items to the inventory", "", ["horizon-ctl give oak_log 16"], + &[p("item", Ty::Str, "item id"), opt("count", Ty::Int, "how many (default 1)")], mcp: true, local: false), + cmd!("time", World, "time TICKS", "set the time of day (0 sunrise, 6000 noon, 13000 night)", "", ["horizon-ctl time 6000"], + &[p("ticks", Ty::Int, "day time")], mcp: true, local: false), + cmd!("setblock", World, "setblock X Y Z BLOCK[props]", "set a block (with neighbour updates)", "", ["horizon-ctl setblock 0 64 0 stone"], + &[BLOCK_XYZ[0], BLOCK_XYZ[1], BLOCK_XYZ[2], p("block", Ty::Str, "block state such as oak_stairs[facing=east]")], mcp: true, local: false), + cmd!("summon", World, "summon KIND [X Y Z] [baby]", "spawn a mob", "", ["horizon-ctl summon cow"], &[p("kind", Ty::Str, "mob type")], mcp: true, local: false), + cmd!("effect", World, "effect ID SECONDS [AMPLIFIER] | effect clear", "give a status effect", "", ["horizon-ctl effect speed 30 1"], &[], mcp: false, local: false), + cmd!("render-distance", World, "render-distance N", "chunks, 2..64", "", ["horizon-ctl render-distance 8"], &[p("chunks", Ty::Int, "render distance")], mcp: false, local: false), + cmd!("wait", World, "wait TICKS", "wait until TICKS game ticks have passed (20 per second)", "", ["horizon-ctl wait 40"], + &[p("ticks", Ty::Int, "game ticks")], mcp: true, local: false), + // Scripting + cmd!("script", Scripting, "script [FILE] [--keep-going]", "run commands from FILE (or stdin), one per line", + "Lines are split like a shell (quotes keep spaces); # starts a comment; sleep SECONDS waits. Stops at the first error unless --keep-going. horizon-ctl - is the older form: read stdin and keep going.", + ["horizon-ctl script play.txt", "printf 'state\\ngoto 0 64 0\\n' | horizon-ctl script"], &[], mcp: false, local: true), + cmd!("sleep", Scripting, "sleep SECONDS", "wait (in scripts)", "", ["sleep 0.5"], &[], mcp: false, local: true), + cmd!("mcp", Scripting, "mcp", "serve the Model Context Protocol on stdin/stdout, one tool per command", + "Add it to an MCP client as a stdio server: command horizon-ctl, args [\"mcp\"] (with --socket PATH first if needed). The screenshot tool returns the image.", + ["horizon-ctl mcp"], &[], mcp: false, local: true), + cmd!("bench", Scripting, "bench SECONDS", "reset frame stats, wait, reply with the summary", "", ["horizon-ctl bench 10"], &[], mcp: false, local: false), + cmd!("stats", Scripting, "stats [reset]", "frame-time summary since the last reset", "", ["horizon-ctl stats"], &[], mcp: false, local: false), + cmd!("fly", Scripting, "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH]", "fly the camera along a line, then reply with the frame summary", "", + ["horizon-ctl fly 0 100 0 500 100 0 20"], &[], mcp: false, local: false), +]; + +pub fn find(name: &str) -> Option<&'static Cmd> { + COMMANDS.iter().find(|c| c.name == name) +} + +/// `horizon-ctl help`. +pub fn overview() -> String { + let mut out = String::from( + "horizon-ctl: play and script a running Horizon from the command line.\n\n\ + usage: horizon-ctl [--socket PATH] [--timeout SECONDS] [--pretty] COMMAND [ARGS...]\n\ + \x20 horizon-ctl COMMAND --help (or: horizon-ctl help COMMAND)\n", + ); + for group in Group::ALL { + out.push_str(&format!("\n{}:\n", group.title())); + for c in COMMANDS.iter().filter(|c| c.group == group) { + out.push_str(&format!(" {:<16} {}\n", c.name, c.summary)); + } + } + out.push_str( + "\nEvery reply is one JSON line. Errors are {\"error\": \"...\"}; the exit status is 0 on\n\ + success, 1 when the game replied with an error, 2 for a usage error and 3 when the\n\ + game cannot be reached or started. Actions (goto, break, place...) block until done.\n\ + horizon-ctl help --game lists the running game's own commands, test hooks included.\n\ + The socket is $HORIZON_CONTROL, else $XDG_RUNTIME_DIR/horizon-control.sock (on Windows\n\ + %TEMP%\\horizon-control.json, a localhost TCP port with a token; any path ending in .json\n\ + uses that transport).\n\n\ + First steps:\n\ + \x20 horizon-ctl launch --world Test --seed 1 --wait\n\ + \x20 horizon-ctl state\n\ + \x20 horizon-ctl find-block oak_log\n\ + \x20 horizon-ctl goto X Y Z --near 2 && horizon-ctl break X Y Z\n\ + \x20 horizon-ctl inventory\n", + ); + out +} + +/// `horizon-ctl COMMAND --help`. +pub fn detail(c: &Cmd) -> String { + let mut out = format!( + "usage: horizon-ctl {}\n\n{}.\n", + c.usage, + capitalize(c.summary) + ); + if !c.details.is_empty() { + out.push('\n'); + out.push_str(&wrap(c.details, 78)); + } + if !c.examples.is_empty() { + out.push_str("\nExamples:\n"); + for e in c.examples { + out.push_str(&format!(" {e}\n")); + } + } + out +} + +fn capitalize(s: &str) -> String { + let mut chars = s.chars(); + chars + .next() + .map(|c| c.to_uppercase().chain(chars).collect()) + .unwrap_or_default() +} + +fn wrap(text: &str, width: usize) -> String { + let mut out = String::new(); + let mut line = String::new(); + for word in text.split_whitespace() { + if !line.is_empty() && line.len() + 1 + word.len() > width { + out.push_str(&line); + out.push('\n'); + line.clear(); + } + if !line.is_empty() { + line.push(' '); + } + line.push_str(word); + } + if !line.is_empty() { + out.push_str(&line); + out.push('\n'); + } + out +} + +/// The MCP tool name of a command (`look-at-block` gives `look_at_block`). +pub fn tool_name(c: &Cmd) -> String { + c.name.replace('-', "_") +} + +/// The JSON schema of a command's arguments. +pub fn schema(c: &Cmd) -> Value { + let mut props = Map::new(); + let mut required = Vec::new(); + for p in c.params { + let mut s = match p.ty { + Ty::Int => json!({ "type": "integer" }), + Ty::Num => json!({ "type": "number" }), + Ty::Str | Ty::Rest => json!({ "type": "string" }), + Ty::Bool => json!({ "type": "boolean" }), + Ty::Enum(values) => json!({ "type": "string", "enum": values }), + }; + s["description"] = json!(p.help); + props.insert(p.name.to_owned(), s); + if p.required { + required.push(p.name); + } + } + json!({ "type": "object", "properties": props, "required": required }) +} + +/// The command line for an MCP call's arguments: positional values in order, +/// then `--flag value` options. +pub fn line_for(c: &Cmd, args: &Value) -> Result, String> { + let mut words: Vec = c + .wire + .unwrap_or(c.name) + .split(' ') + .map(str::to_owned) + .collect(); + let mut flags = Vec::new(); + let mut gap: Option<&str> = None; + let mut rest: Option = None; + for p in c.params { + let value = args.get(p.name).filter(|v| !v.is_null()); + let text = match value { + None => { + if p.required { + return Err(format!("{} is required", p.name)); + } + if !p.flag { + gap.get_or_insert(p.name); + } + continue; + } + Some(Value::Bool(b)) => { + if p.ty != Ty::Bool { + return Err(format!("{} must be a {}", p.name, ty_name(p.ty))); + } + if *b { + if p.flag { + flags.push(format!("--{}", p.name)); + } else { + words.push(p.name.to_owned()); + } + } + continue; + } + Some(Value::String(s)) => s.clone(), + Some(Value::Number(n)) => n.to_string(), + Some(other) => { + return Err(format!( + "{} must be a {}, not {other}", + p.name, + ty_name(p.ty) + )); + } + }; + match p.ty { + Ty::Int if text.parse::().is_err() => { + return Err(format!("{} must be an integer, not {text}", p.name)); + } + Ty::Num if text.parse::().is_err() => { + return Err(format!("{} must be a number, not {text}", p.name)); + } + Ty::Enum(values) if !values.contains(&text.as_str()) => { + return Err(format!("{} must be one of {values:?}, not {text}", p.name)); + } + _ => {} + } + if p.flag { + flags.push(format!("--{}", p.name)); + flags.push(text); + } else { + if let Some(missing) = gap { + return Err(format!("{} needs {missing} to be given too", p.name)); + } + if p.ty == Ty::Rest { + rest = Some(text); + } else if text.contains(char::is_whitespace) || text.is_empty() { + return Err(format!("{} must be a single word", p.name)); + } else { + words.push(text); + } + } + } + // Options go before free text, which runs to the end of the line. + words.extend(flags); + words.extend(rest); + Ok(words) +} + +fn ty_name(ty: Ty) -> &'static str { + match ty { + Ty::Int => "integer", + Ty::Num => "number", + Ty::Bool => "boolean", + _ => "string", + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_are_unique_and_documented() { + let mut seen = std::collections::HashSet::new(); + for c in COMMANDS { + assert!(seen.insert(c.name), "duplicate command {}", c.name); + assert!( + c.usage.starts_with(c.name.split('-').next().unwrap()), + "{}", + c.name + ); + assert!( + !c.summary.is_empty() && !c.examples.is_empty(), + "{}", + c.name + ); + } + } + + #[test] + fn mcp_arguments_become_command_lines() { + let goto = find("goto").unwrap(); + let words = line_for( + goto, + &json!({ "x": 1.5, "y": 64, "z": -3, "near": 2, "sprint": true }), + ) + .unwrap(); + assert_eq!( + words, + ["goto", "1.5", "64", "-3", "--near", "2", "--sprint"] + ); + assert!( + line_for(goto, &json!({ "x": 1, "y": 2 })) + .unwrap_err() + .contains("z is required") + ); + assert!(line_for(goto, &json!({ "x": "a", "y": 2, "z": 3 })).is_err()); + let block = find("look-at-block").unwrap(); + assert_eq!( + line_for(block, &json!({ "x": 1, "y": 2, "z": 3, "face": "up" })).unwrap(), + ["look-at", "block", "1", "2", "3", "up"] + ); + assert!( + line_for( + block, + &json!({ "x": 1, "y": 2, "z": 3, "face": "sideways" }) + ) + .is_err() + ); + let button = find("click-button").unwrap(); + assert_eq!( + line_for(button, &json!({ "label": "Create New World" })).unwrap(), + ["click-button", "Create New World"] + ); + let slot = find("click-slot").unwrap(); + assert_eq!( + line_for(slot, &json!({ "slot": 200, "shift": true })).unwrap(), + ["click-slot", "200", "shift"] + ); + let open = find("open").unwrap(); + assert!( + line_for(open, &json!({ "world": "A", "mode": "creative" })) + .unwrap_err() + .contains("seed") + ); + } + + #[test] + fn schemas_list_required_parameters() { + let s = schema(find("break").unwrap()); + assert_eq!(s["required"], json!(["x", "y", "z"])); + assert_eq!(s["properties"]["timeout"]["type"], "number"); + assert_eq!(tool_name(find("look-at-entity").unwrap()), "look_at_entity"); + } + + #[test] + fn help_mentions_every_command() { + let text = overview(); + for c in COMMANDS { + assert!(text.contains(c.name)); + assert!(detail(c).contains("usage: horizon-ctl")); + } + } +} diff --git a/crates/horizon-client/src/bin/horizon-ctl/launch.rs b/crates/horizon-client/src/bin/horizon-ctl/launch.rs new file mode 100644 index 000000000..984b634af --- /dev/null +++ b/crates/horizon-client/src/bin/horizon-ctl/launch.rs @@ -0,0 +1,386 @@ +//! `horizon-ctl launch`: find a Horizon to start and start it with a control +//! socket. Mirrors where the launcher puts things (launcher/src/backend.rs): +//! versions under `/versions/`, each with its prepared +//! resources in `.local/horizon-client/` and run from the +//! game home, where saves and options.txt live. +use std::{ + path::{Path, PathBuf}, + process::{Command, Stdio}, + thread, + time::{Duration, Instant}, +}; + +use serde_json::{Value, json}; + +#[cfg(windows)] +const CLIENT: &str = "horizon-client.exe"; +#[cfg(not(windows))] +const CLIENT: &str = "horizon-client"; + +/// The platform data folder (what the `dirs` crate's data_dir gives). +fn data_dir() -> PathBuf { + let env = |k: &str| { + std::env::var_os(k) + .filter(|v| !v.is_empty()) + .map(PathBuf::from) + }; + let home = env("HOME").or_else(|| env("USERPROFILE")); + if cfg!(windows) { + if let Some(d) = env("APPDATA") { + return d; + } + } else if cfg!(target_os = "macos") { + if let Some(h) = &home { + return h.join("Library/Application Support"); + } + } else if let Some(d) = env("XDG_DATA_HOME") { + return d; + } else if let Some(h) = &home { + return h.join(".local/share"); + } + std::env::temp_dir() +} +pub fn launcher_home() -> PathBuf { + match std::env::var_os("HORIZON_LAUNCHER_HOME").filter(|h| !h.is_empty()) { + Some(h) => PathBuf::from(h), + None => data_dir().join("horizon-launcher"), + } +} +pub fn game_home() -> PathBuf { + match std::env::var_os("HORIZON_HOME").filter(|h| !h.is_empty()) { + Some(h) => PathBuf::from(h), + None => data_dir().join("horizon"), + } +} + +/// `v2026.10.13.1` gives [2026, 10, 13, 1]; a pre-release suffix is ignored. +pub fn version_parts(tag: &str) -> Vec { + tag.trim_start_matches('v') + .split('-') + .next() + .unwrap_or("") + .split('.') + .map(|p| p.parse().unwrap_or(0)) + .collect() +} + +/// Installed launcher versions, newest first. +pub fn installed(versions: &Path) -> Vec { + let mut tags: Vec = std::fs::read_dir(versions) + .into_iter() + .flatten() + .flatten() + .filter(|e| e.path().join(".installed").exists() && e.path().join(CLIENT).exists()) + .filter_map(|e| e.file_name().into_string().ok()) + .collect(); + tags.sort_by_key(|t| std::cmp::Reverse(version_parts(t))); + tags +} + +/// A folder's prepared resources, as the launcher prepares them. +pub fn prepared_resources(dir: &Path) -> Option { + let version = std::fs::read_to_string(dir.join("research-lock.json")) + .ok() + .and_then(|t| serde_json::from_str::(&t).ok()) + .and_then(|v| v["minecraft"]["version"].as_str().map(str::to_owned)) + .unwrap_or_else(|| "26.3".into()); + let resources = dir.join(".local/horizon-client").join(version); + resources + .join("horizon-resources.json") + .exists() + .then_some(resources) +} + +#[derive(Debug, PartialEq)] +pub struct Install { + pub game: PathBuf, + /// Passed as --resources unless the caller gave their own. + pub resources: Option, + /// The working directory (the game home for prepared installs). + pub cwd: Option, + pub source: &'static str, + pub version: Option, +} + +/// Which game to start: an explicit binary, the one beside horizon-ctl, or a +/// launcher install. +pub fn find( + game: Option<&Path>, + version: Option<&str>, + beside: Option<&Path>, + launcher: &Path, +) -> Result { + let prepared = |dir: &Path, source, version| { + let resources = prepared_resources(dir); + Install { + game: dir.join(CLIENT), + cwd: resources.as_ref().map(|_| game_home()), + resources, + source, + version, + } + }; + if let Some(game) = game { + if !game.is_file() { + return Err(format!("{} is not a file", game.display())); + } + let dir = game.parent().unwrap_or(Path::new(".")); + let mut install = prepared(dir, "--game", None); + install.game = game.to_owned(); + return Ok(install); + } + let versions = launcher.join("versions"); + if version.is_none() + && let Some(dir) = beside + && dir.join(CLIENT).is_file() + { + return Ok(prepared(dir, "beside horizon-ctl", None)); + } + let tags = installed(&versions); + let tag = match version { + Some(v) => { + let want = if v.starts_with('v') { v.to_owned() } else { format!("v{v}") }; + tags.iter() + .find(|t| **t == want || **t == v) + .cloned() + .ok_or_else(|| format!("version {v} is not installed in {} (installed: {tags:?})", versions.display()))? + } + None => tags.first().cloned().ok_or_else(|| { + format!( + "no Horizon found: no horizon-client beside horizon-ctl and no version installed by the launcher in {}. Install one with the launcher (horizon-launcher install latest) or pass --game PATH.", + versions.display() + ) + })?, + }; + let dir = versions.join(&tag); + let install = prepared(&dir, "launcher", Some(tag.clone())); + if install.resources.is_none() { + return Err(format!( + "{tag} is installed but not prepared; prepare it in the launcher first (horizon-launcher prepare {tag})" + )); + } + Ok(install) +} + +pub struct Options { + pub game: Option, + pub version: Option, + pub wait: bool, + pub game_args: Vec, +} + +pub fn parse(args: &[String]) -> Result { + let mut o = Options { + game: None, + version: None, + wait: false, + game_args: Vec::new(), + }; + let mut i = 0; + while i < args.len() { + let value = |i: usize| { + args.get(i + 1) + .cloned() + .ok_or_else(|| format!("{} needs a value", args[i])) + }; + match args[i].as_str() { + "--game" => { + o.game = Some(value(i)?.into()); + i += 1; + } + "--version" => { + o.version = Some(value(i)?); + i += 1; + } + "--wait" | "--wait-ready" => o.wait = true, + other => o.game_args.push(other.to_owned()), + } + i += 1; + } + Ok(o) +} + +/// Start the game and wait for its control endpoint; Ok(reply) or Err(reply). +pub fn launch(socket: &Path, args: &[String]) -> Result { + let o = parse(args).map_err(|e| json!({ "error": e, "kind": "usage" }))?; + if horizon_client::control::connect(socket).is_ok() { + return Err(json!({ + "error": format!("a game is already listening on {}; quit it first or pass another --socket", socket.display()), + "kind": "connection", + })); + } + let exe = std::env::current_exe().ok(); + let beside = exe.as_deref().and_then(Path::parent); + let install = find( + o.game.as_deref(), + o.version.as_deref(), + beside, + &launcher_home(), + ) + .map_err(|e| json!({ "error": e, "kind": "launch" }))?; + let log = socket.with_extension("log"); + let file = std::fs::File::create(&log) + .map_err(|e| json!({ "error": format!("{}: {e}", log.display()), "kind": "launch" }))?; + let mut cmd = Command::new(&install.game); + let gave_resources = o.game_args.iter().any(|a| a == "--resources"); + if let Some(resources) = install.resources.as_ref().filter(|_| !gave_resources) { + cmd.arg("--resources").arg(resources); + } + if let Some(cwd) = &install.cwd { + let _ = std::fs::create_dir_all(cwd); + cmd.current_dir(cwd); + } + let stderr = file + .try_clone() + .map_err(|e| json!({ "error": e.to_string(), "kind": "launch" }))?; + let mut child = cmd + .args(&o.game_args) + .arg("--control-socket") + .arg(socket) + .stdin(Stdio::null()) + .stdout(file) + .stderr(stderr) + .spawn() + .map_err( + |e| json!({ "error": format!("{}: {e}", install.game.display()), "kind": "launch" }), + )?; + let deadline = Instant::now() + Duration::from_secs(300); + let info = json!({ + "pid": child.id(), + "socket": socket, + "log": log, + "game": install.game, + "source": install.source, + "version": install.version, + "resources": install.resources, + "home": install.cwd, + }); + while Instant::now() < deadline { + if horizon_client::control::connect(socket).is_ok() { + let mut reply = json!({ "ok": true }); + reply + .as_object_mut() + .unwrap() + .extend(info.as_object().unwrap().clone()); + return Ok(reply); + } + if let Ok(Some(status)) = child.try_wait() { + let tail = std::fs::read_to_string(&log).unwrap_or_default(); + let tail: Vec<&str> = tail.lines().rev().take(15).collect(); + return Err(json!({ + "error": format!("the game exited ({status}) before opening the control socket"), + "kind": "launch", + "log_tail": tail.into_iter().rev().collect::>(), + "log": log, + })); + } + thread::sleep(Duration::from_millis(100)); + } + Err( + json!({ "error": "control socket did not open within 300 seconds", "kind": "launch", "log": log }), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("horizon-ctl-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + fn fake_version(versions: &Path, tag: &str, prepared: bool) -> PathBuf { + let dir = versions.join(tag); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join(CLIENT), "").unwrap(); + std::fs::write(dir.join(".installed"), "").unwrap(); + std::fs::write( + dir.join("research-lock.json"), + r#"{"minecraft":{"version":"26.3"}}"#, + ) + .unwrap(); + if prepared { + let res = dir.join(".local/horizon-client/26.3"); + std::fs::create_dir_all(&res).unwrap(); + std::fs::write(res.join("horizon-resources.json"), "{}").unwrap(); + } + dir + } + + #[test] + fn versions_sort_newest_first() { + let home = temp("sort"); + let versions = home.join("versions"); + for tag in ["v2026.9.30", "v2026.10.13", "v2026.10.13.1", "v2026.10.2"] { + fake_version(&versions, tag, true); + } + assert_eq!( + installed(&versions), + ["v2026.10.13.1", "v2026.10.13", "v2026.10.2", "v2026.9.30"] + ); + let install = find(None, None, None, &home).unwrap(); + assert_eq!(install.version.as_deref(), Some("v2026.10.13.1")); + assert!( + install + .resources + .unwrap() + .ends_with(".local/horizon-client/26.3") + ); + assert_eq!(install.cwd, Some(game_home())); + let picked = find(None, Some("2026.10.2"), None, &home).unwrap(); + assert_eq!(picked.version.as_deref(), Some("v2026.10.2")); + assert!(find(None, Some("v1.0"), None, &home).is_err()); + let _ = std::fs::remove_dir_all(home); + } + + #[test] + fn a_game_beside_ctl_wins_and_dev_builds_keep_the_directory() { + let home = temp("beside"); + fake_version(&home.join("versions"), "v2026.10.13", true); + let build = temp("build"); + std::fs::write(build.join(CLIENT), "").unwrap(); + let install = find(None, None, Some(&build), &home).unwrap(); + assert_eq!(install.source, "beside horizon-ctl"); + assert_eq!((install.resources, install.cwd), (None, None)); + // --version always means a launcher install. + assert_eq!( + find(None, Some("v2026.10.13"), Some(&build), &home) + .unwrap() + .source, + "launcher" + ); + let _ = std::fs::remove_dir_all(home); + let _ = std::fs::remove_dir_all(build); + } + + #[test] + fn unprepared_or_missing_installs_explain_themselves() { + let home = temp("unprepared"); + assert!( + find(None, None, None, &home) + .unwrap_err() + .contains("no Horizon found") + ); + fake_version(&home.join("versions"), "v2026.10.13", false); + assert!( + find(None, None, None, &home) + .unwrap_err() + .contains("not prepared") + ); + let _ = std::fs::remove_dir_all(home); + } + + #[test] + fn launch_options_pass_the_rest_to_the_game() { + let args: Vec = ["--world", "A", "--version", "v1", "--wait", "--seed", "3"] + .map(String::from) + .to_vec(); + let o = parse(&args).unwrap(); + assert_eq!(o.version.as_deref(), Some("v1")); + assert!(o.wait); + assert_eq!(o.game_args, ["--world", "A", "--seed", "3"]); + assert!(parse(&["--game".to_owned()]).is_err()); + } +} diff --git a/crates/horizon-client/src/bin/horizon-ctl/main.rs b/crates/horizon-client/src/bin/horizon-ctl/main.rs index 962a4885d..193f84410 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/main.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/main.rs @@ -1,66 +1,235 @@ -//! horizon-ctl: drive a running Horizon client through its control socket. +//! horizon-ctl: play and script a running Horizon client through its control +//! socket, from a shell, a script or an AI agent (`horizon-ctl mcp`). #![forbid(unsafe_code)] +mod commands; +mod launch; +mod mcp; + use std::{ io::{BufRead, BufReader, Write}, path::{Path, PathBuf}, - process::{Command, ExitCode, Stdio}, + process::ExitCode, thread, time::{Duration, Instant}, }; -use horizon_client::control::UnixStream; +use horizon_client::control::Stream; +use serde_json::{Value, json}; -const USAGE: &str = "usage: horizon-ctl [--socket PATH] COMMAND [ARGS...] +/// Exit statuses. +const GAME_ERROR: u8 = 1; +const USAGE: u8 = 2; +const UNREACHABLE: u8 = 3; -Local commands: - launch [GAME ARGS...] start horizon-client with a control socket and wait for it - hold KEY SECONDS press KEY, wait, release it - wait-ready [SECONDS] wait until the player has spawned and no chunks are pending - - run commands from stdin, one per line (\"sleep S\" waits locally) +/// A failure, with the exit status it maps to. +#[derive(Debug)] +pub struct Failure { + pub reply: Value, + pub status: u8, +} +impl Failure { + fn usage(message: impl Into) -> Self { + Self { + reply: json!({ "error": message.into(), "kind": "usage" }), + status: USAGE, + } + } + fn unreachable(message: impl Into) -> Self { + Self { + reply: json!({ "error": message.into(), "kind": "connection" }), + status: UNREACHABLE, + } + } +} -Game commands (run \"horizon-ctl help\" against a running game for the full list): - status, key, mouse, look, turn, tp, hotbar, give, render-distance, time, - screenshot PATH, stats, bench SECONDS, open, save, quit - -Replies are JSON lines; the exit status is 1 when the reply has an \"error\". -The socket defaults to $HORIZON_CONTROL or $XDG_RUNTIME_DIR/horizon-control.sock."; - -struct Client { - writer: UnixStream, - reader: BufReader, +pub struct Client { + writer: Stream, + reader: BufReader, } impl Client { - fn connect(path: &Path) -> Result { - let stream = UnixStream::connect(path).map_err(|e| { - format!( - "cannot connect to {} ({e}); is the game running with --control?", + fn connect(path: &Path, timeout: Option) -> Result { + let stream = horizon_client::control::connect(path).map_err(|e| { + Failure::unreachable(format!( + "cannot connect to {} ({e}); is the game running with --control? Start one with: horizon-ctl launch --world NAME", path.display() - ) + )) })?; - let reader = BufReader::new(stream.try_clone().map_err(|e| e.to_string())?); + stream + .set_read_timeout(timeout) + .map_err(|e| Failure::unreachable(e.to_string()))?; + let reader = BufReader::new( + stream + .try_clone() + .map_err(|e| Failure::unreachable(e.to_string()))?, + ); Ok(Self { writer: stream, reader, }) } - fn send(&mut self, line: &str) -> Result { - writeln!(self.writer, "{line}").map_err(|e| e.to_string())?; + /// Send one line and read its JSON reply. + fn send(&mut self, line: &str) -> Result { + writeln!(self.writer, "{line}").map_err(|e| Failure::unreachable(e.to_string()))?; let mut reply = String::new(); - if self - .reader - .read_line(&mut reply) - .map_err(|e| e.to_string())? - == 0 - { - return Err("the game closed the connection".into()); + let n = self.reader.read_line(&mut reply).map_err(|e| { + Failure::unreachable( + if matches!( + e.kind(), + std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut + ) { + "timed out waiting for the game's reply (--timeout)".to_owned() + } else { + e.to_string() + }, + ) + })?; + if n == 0 { + return Err(Failure::unreachable("the game closed the connection")); } - Ok(reply.trim_end().to_owned()) + serde_json::from_str(reply.trim_end()).map_err(|_| Failure { + reply: json!({ "error": "the game sent a reply that is not JSON", "reply": reply.trim_end() }), + status: GAME_ERROR, + }) } } -fn is_error(reply: &str) -> bool { - serde_json::from_str::(reply).map_or(true, |v| v.get("error").is_some()) +/// Global options and the connection, opened on first use. +pub struct Session { + pub socket: PathBuf, + pub timeout: Option, + client: Option, +} + +impl Session { + pub fn new(socket: PathBuf, timeout: Option) -> Self { + Self { + socket, + timeout, + client: None, + } + } + fn client(&mut self) -> Result<&mut Client, Failure> { + if self.client.is_none() { + self.client = Some(Client::connect(&self.socket, self.timeout)?); + } + Ok(self.client.as_mut().unwrap()) + } + /// Send a line to the game; a reply with "error" is a failure. + pub fn game(&mut self, line: &str) -> Result { + let result = self.client()?.send(line); + if result.as_ref().is_err_and(|f| f.status == UNREACHABLE) { + // Reconnect next time (the game may have restarted). + self.client = None; + } + let reply = result?; + if reply.get("error").is_some() { + return Err(Failure { + reply, + status: GAME_ERROR, + }); + } + Ok(reply) + } + + /// Run one command (CLI words); Ok(reply) or a failure. + pub fn run(&mut self, words: &[String]) -> Result { + let Some(name) = words.first().map(String::as_str) else { + return Err(Failure::usage("no command; try horizon-ctl help")); + }; + if words.iter().skip(1).any(|w| w == "--help" || w == "-h") { + return Err(Failure::usage( + "use horizon-ctl COMMAND --help outside scripts", + )); + } + let number = |i: usize, what: &str| -> Result { + words + .get(i) + .ok_or_else(|| Failure::usage(format!("missing {what}; usage: {}", usage(name))))? + .parse::() + .map_err(|_| { + Failure::usage(format!("{what} must be a number; usage: {}", usage(name))) + }) + }; + match name { + "sleep" => { + thread::sleep(Duration::from_secs_f64(number(1, "SECONDS")?.max(0.0))); + Ok(json!({ "ok": true })) + } + "launch" => { + let socket = self.socket.clone(); + let wait = words.iter().any(|w| w == "--wait" || w == "--wait-ready"); + let reply = launch::launch(&socket, &words[1..]).map_err(|reply| Failure { + status: if reply["kind"] == "usage" { + USAGE + } else { + UNREACHABLE + }, + reply, + })?; + if !wait { + return Ok(reply); + } + let mut ready = self.wait_ready(300.0)?; + ready["launch"] = reply; + Ok(ready) + } + "hold" => { + let (key, seconds) = match words { + [_, key, _] => (key.clone(), number(2, "SECONDS")?), + _ => return Err(Failure::usage(format!("usage: {}", usage(name)))), + }; + self.game(&format!("key {key} down"))?; + thread::sleep(Duration::from_secs_f64(seconds.max(0.0))); + self.game(&format!("key {key} up")) + } + "wait-ready" => { + let limit = if words.len() > 1 { + number(1, "SECONDS")? + } else { + 120.0 + }; + self.wait_ready(limit) + } + "help" if words.get(1).is_some_and(|w| w == "--game") => self.game("help"), + _ => { + let mut words = words.to_vec(); + if let Some(cmd) = commands::find(name) { + if cmd.local { + return Err(Failure::usage(format!( + "{name} runs only as horizon-ctl {name}, not inside a script" + ))); + } + if let Some(wire) = cmd.wire { + words.splice(0..1, wire.split(' ').map(str::to_owned)); + } + } + absolute_paths(&mut words); + self.game(&words.join(" ")) + } + } + } + + fn wait_ready(&mut self, limit: f64) -> Result { + let deadline = Instant::now() + Duration::from_secs_f64(limit.max(0.0)); + loop { + let status = self.game("status")?; + if !status["player"].is_null() && status["pending_chunks"] == 0 { + return Ok(status); + } + if Instant::now() > deadline { + return Err(Failure { + reply: json!({ "error": format!("not ready after {limit} seconds"), "status": status }), + status: GAME_ERROR, + }); + } + thread::sleep(Duration::from_millis(250)); + } + } +} + +fn usage(name: &str) -> String { + commands::find(name).map_or_else(|| name.to_owned(), |c| format!("horizon-ctl {}", c.usage)) } /// Screenshot paths are written by the game process: make them absolute here. @@ -73,132 +242,247 @@ fn absolute_paths(words: &mut [String]) { } } -fn run_line(client: &mut Client, words: &mut [String]) -> Result { - match words.first().map(String::as_str) { - Some("sleep") => { - let seconds: f64 = words - .get(1) - .ok_or("sleep SECONDS")? - .parse() - .map_err(|_| "sleep SECONDS")?; - thread::sleep(Duration::from_secs_f64(seconds)); - Ok(true) - } - Some("hold") => { - let (key, seconds) = match words { - [_, key, seconds] => ( - key.clone(), - seconds.parse::().map_err(|_| "hold KEY SECONDS")?, - ), - _ => return Err("hold KEY SECONDS".into()), - }; - let down = client.send(&format!("key {key} down"))?; - if is_error(&down) { - println!("{down}"); - return Ok(false); +/// Split a script line like a shell: quotes keep spaces, backslash escapes. +pub fn split_line(line: &str) -> Result, String> { + let mut words = Vec::new(); + let mut word = String::new(); + let mut in_word = false; + let mut quote: Option = None; + let mut chars = line.chars(); + while let Some(c) = chars.next() { + match (quote, c) { + (Some(q), c) if c == q => quote = None, + (Some('"'), '\\') => word.push(chars.next().unwrap_or('\\')), + (Some(_), c) => word.push(c), + (None, '"' | '\'') => { + quote = Some(c); + in_word = true; } - thread::sleep(Duration::from_secs_f64(seconds)); - let up = client.send(&format!("key {key} up"))?; - println!("{up}"); - Ok(!is_error(&up)) - } - Some("wait-ready") => { - let limit = words - .get(1) - .map_or(Ok(120.0), |s| s.parse::()) - .map_err(|_| "wait-ready [SECONDS]")?; - let deadline = Instant::now() + Duration::from_secs_f64(limit); - loop { - let reply = client.send("status")?; - let status: serde_json::Value = - serde_json::from_str(&reply).map_err(|e| e.to_string())?; - if !status["player"].is_null() && status["pending_chunks"] == 0 { - println!("{reply}"); - return Ok(true); - } - if Instant::now() > deadline { - println!( - "{{\"error\":\"not ready after {limit} seconds\",\"status\":{reply}}}" - ); - return Ok(false); - } - thread::sleep(Duration::from_millis(250)); + (None, '\\') => { + word.push(chars.next().unwrap_or('\\')); + in_word = true; + } + (None, '#') if !in_word => break, + (None, c) if c.is_whitespace() => { + if in_word { + words.push(std::mem::take(&mut word)); + in_word = false; + } + } + (None, c) => { + word.push(c); + in_word = true; } - } - _ => { - absolute_paths(words); - let reply = client.send(&words.join(" "))?; - println!("{reply}"); - Ok(!is_error(&reply)) } } + if quote.is_some() { + return Err("unterminated quote".into()); + } + if in_word { + words.push(word); + } + Ok(words) } -fn launch(socket: &Path, args: &[String]) -> Result { - let exe = std::env::current_exe().map_err(|e| e.to_string())?; - let game = exe.with_file_name("horizon-client"); - let log = socket.with_extension("log"); - let file = std::fs::File::create(&log).map_err(|e| format!("{}: {e}", log.display()))?; - let child = Command::new(&game) - .args(args) - .arg("--control-socket") - .arg(socket) - .stdin(Stdio::null()) - .stdout(file.try_clone().map_err(|e| e.to_string())?) - .stderr(file) - .spawn() - .map_err(|e| format!("{}: {e}", game.display()))?; - let deadline = Instant::now() + Duration::from_secs(300); - while Instant::now() < deadline { - if UnixStream::connect(socket).is_ok() { - println!( - "{}", - serde_json::json!({ "ok": true, "pid": child.id(), "socket": socket, "log": log }) - ); - return Ok(true); +fn print(value: &Value, pretty: bool) { + let text = if pretty { + serde_json::to_string_pretty(value).unwrap_or_default() + } else { + value.to_string() + }; + println!("{text}"); +} + +/// Run a script; the exit status of the first failure (or the last one with --keep-going). +fn script(session: &mut Session, reader: impl BufRead, keep_going: bool, pretty: bool) -> u8 { + let mut status = 0; + for (n, line) in reader.lines().enumerate() { + let Ok(line) = line else { break }; + let words = match split_line(&line) { + Ok(w) if w.is_empty() => continue, + Ok(w) => w, + Err(e) => { + print( + &json!({ "error": e, "kind": "usage", "line": n + 1 }), + pretty, + ); + status = USAGE; + if keep_going { + continue; + } + break; + } + }; + match session.run(&words) { + Ok(reply) => print(&reply, pretty), + Err(mut f) => { + f.reply["line"] = json!(n + 1); + print(&f.reply, pretty); + status = f.status; + if !keep_going || f.status == UNREACHABLE { + break; + } + } } - thread::sleep(Duration::from_millis(100)); } - println!( - "{}", - serde_json::json!({ "error": "control socket did not open within 300 seconds", "log": log }) - ); - Ok(false) + status } fn main() -> ExitCode { let mut args: Vec = std::env::args().skip(1).collect(); let mut socket = horizon_client::control::default_path(); - if args.first().map(String::as_str) == Some("--socket") && args.len() >= 2 { - socket = PathBuf::from(args.remove(1)); - args.remove(0); - } - let result = match args.first().map(String::as_str) { - None | Some("-h" | "--help") => { - println!("{USAGE}"); - return ExitCode::SUCCESS; - } - Some("launch") => launch(&socket, &args[1..]), - Some("-") => Client::connect(&socket).and_then(|mut client| { - let mut all_ok = true; - for line in std::io::stdin().lock().lines() { - let line = line.map_err(|e| e.to_string())?; - let mut words: Vec = line.split_whitespace().map(str::to_owned).collect(); - if words.is_empty() || words[0].starts_with('#') { - continue; - } - all_ok &= run_line(&mut client, &mut words)?; + let mut timeout = None; + let mut pretty = false; + // Global options before the command. + loop { + match args.first().map(String::as_str) { + Some("--socket") if args.len() >= 2 => { + socket = PathBuf::from(args.remove(1)); + args.remove(0); } - Ok(all_ok) - }), - Some(_) => Client::connect(&socket).and_then(|mut client| run_line(&mut client, &mut args)), - }; - match result { - Ok(true) => ExitCode::SUCCESS, - Ok(false) => ExitCode::from(1), - Err(e) => { - eprintln!("horizon-ctl: {e}"); - ExitCode::from(2) + Some("--timeout") if args.len() >= 2 => { + let Ok(s) = args[1].parse::() else { + print( + &json!({ "error": "--timeout takes seconds", "kind": "usage" }), + false, + ); + return ExitCode::from(USAGE); + }; + timeout = Some(Duration::from_secs_f64(s.max(0.001))); + args.drain(0..2); + } + Some("--pretty") => { + pretty = true; + args.remove(0); + } + _ => break, } } + let mut session = Session::new(socket, timeout); + let name = args.first().cloned(); + let status = match name.as_deref() { + None | Some("-h" | "--help") => { + print!("{}", commands::overview()); + 0 + } + Some("help") if args.get(1).is_none_or(|a| a != "--game") => match args.get(1) { + None => { + print!("{}", commands::overview()); + 0 + } + Some(c) => match commands::find(c) { + Some(cmd) => { + print!("{}", commands::detail(cmd)); + 0 + } + None => { + print( + &json!({ "error": format!("unknown command {c}; horizon-ctl help lists them, horizon-ctl help --game lists the game's own"), "kind": "usage" }), + pretty, + ); + USAGE + } + }, + }, + Some(c) if args.len() == 2 && matches!(args[1].as_str(), "--help" | "-h") => { + match commands::find(c) { + Some(cmd) => { + print!("{}", commands::detail(cmd)); + 0 + } + None => { + print( + &json!({ "error": format!("no help for {c}; horizon-ctl help --game lists the game's own commands"), "kind": "usage" }), + pretty, + ); + USAGE + } + } + } + Some("mcp") => match mcp::serve(&mut session) { + Ok(()) => 0, + Err(e) => { + eprintln!("horizon-ctl mcp: {e}"); + UNREACHABLE + } + }, + Some("-") => { + // The original form: stdin, keep going, status 1 if anything failed. + let status = script(&mut session, std::io::stdin().lock(), true, pretty); + if status == 0 { + 0 + } else { + status.min(GAME_ERROR).max(1) + } + } + Some("script") => { + let keep_going = args.iter().any(|a| a == "--keep-going"); + match args.iter().skip(1).find(|a| !a.starts_with("--")) { + Some(file) if file != "-" => match std::fs::File::open(file) { + Ok(f) => script(&mut session, BufReader::new(f), keep_going, pretty), + Err(e) => { + print( + &json!({ "error": format!("{file}: {e}"), "kind": "usage" }), + pretty, + ); + USAGE + } + }, + _ => script(&mut session, std::io::stdin().lock(), keep_going, pretty), + } + } + Some(_) => match session.run(&args) { + Ok(reply) => { + print(&reply, pretty); + 0 + } + Err(f) => { + print(&f.reply, pretty); + f.status + } + }, + }; + ExitCode::from(status) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn script_lines_split_like_a_shell() { + assert_eq!( + split_line("goto 1 2 3 --near 2").unwrap(), + ["goto", "1", "2", "3", "--near", "2"] + ); + assert_eq!( + split_line("click-button \"Create New World\"").unwrap(), + ["click-button", "Create New World"] + ); + assert_eq!( + split_line("type 'it''s' # comment").unwrap(), + ["type", "its"] + ); + assert_eq!(split_line("chat a\\ b").unwrap(), ["chat", "a b"]); + assert_eq!(split_line("chat issue#4").unwrap(), ["chat", "issue#4"]); + assert!(split_line(" # only a comment").unwrap().is_empty()); + assert!(split_line("type \"open").is_err()); + } + + #[test] + fn unreachable_games_fail_with_status_3() { + let mut s = Session::new(std::env::temp_dir().join("horizon-ctl-nobody.sock"), None); + let f = s.run(&["state".to_owned()]).unwrap_err(); + assert_eq!(f.status, UNREACHABLE); + assert_eq!(f.reply["kind"], "connection"); + let f = s.run(&["sleep".to_owned(), "x".to_owned()]).unwrap_err(); + assert_eq!(f.status, USAGE); + } + + #[test] + fn screenshot_paths_become_absolute() { + let mut words = vec!["screenshot".to_owned(), "a.png".to_owned()]; + absolute_paths(&mut words); + assert!(Path::new(&words[1]).is_absolute()); + } } diff --git a/crates/horizon-client/src/bin/horizon-ctl/mcp.rs b/crates/horizon-client/src/bin/horizon-ctl/mcp.rs new file mode 100644 index 000000000..492377fe7 --- /dev/null +++ b/crates/horizon-client/src/bin/horizon-ctl/mcp.rs @@ -0,0 +1,238 @@ +//! `horizon-ctl mcp`: the Model Context Protocol over stdin and stdout +//! (JSON-RPC 2.0, one message per line, like the launcher's `mcp`), so AI +//! agents can play Horizon. Each tool is a horizon-ctl command from the +//! shared table, run through the same `Session` as the CLI. +use crate::{Session, commands}; +use serde_json::{Value, json}; +use std::io::{BufRead, Write}; + +const PROTOCOL: &str = "2025-06-18"; + +fn tools() -> Vec { + commands::COMMANDS + .iter() + .filter(|c| c.mcp) + .map(|c| { + let mut description = format!("{}. Usage: horizon-ctl {}", capital(c.summary), c.usage); + if !c.details.is_empty() { + description.push_str(". "); + description.push_str(c.details); + } + let mut schema = commands::schema(c); + if c.name == "screenshot" { + schema = json!({ "type": "object", "properties": {} }); + description = "Capture the game window and return it as a PNG image.".into(); + } + json!({ "name": commands::tool_name(c), "description": description, "inputSchema": schema }) + }) + .collect() +} + +fn capital(s: &str) -> String { + let mut c = s.chars(); + c.next() + .map(|f| f.to_uppercase().chain(c).collect()) + .unwrap_or_default() +} + +/// Standard base64 (RFC 4648) for image content. +pub fn base64(bytes: &[u8]) -> String { + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let n = (u32::from(chunk[0]) << 16) + | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8) + | u32::from(*chunk.get(2).unwrap_or(&0)); + for i in 0..4 { + if i <= chunk.len() { + out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char); + } else { + out.push('='); + } + } + } + out +} + +impl Session { + /// One tool call: (content blocks, is_error). + fn call(&mut self, name: &str, args: &Value) -> (Vec, bool) { + let text = |v: &Value| json!({ "type": "text", "text": serde_json::to_string_pretty(v).unwrap_or_default() }); + let Some(cmd) = commands::COMMANDS + .iter() + .find(|c| c.mcp && commands::tool_name(c) == name) + else { + return ( + vec![text(&json!({ "error": format!("unknown tool {name}") }))], + true, + ); + }; + if cmd.name == "screenshot" { + let path = std::env::temp_dir().join(format!("horizon-ctl-{}.png", std::process::id())); + let result = self + .run(&["screenshot".to_owned(), path.display().to_string()]) + .and_then(|reply| { + std::fs::read(&path) + .map(|png| (reply, png)) + .map_err(|e| crate::Failure { + reply: json!({ "error": format!("{}: {e}", path.display()) }), + status: 1, + }) + }); + let _ = std::fs::remove_file(&path); + return match result { + Ok((reply, png)) => ( + vec![ + json!({ "type": "image", "data": base64(&png), "mimeType": "image/png" }), + text(&reply), + ], + false, + ), + Err(f) => (vec![text(&f.reply)], true), + }; + } + let mut words = match commands::line_for(cmd, args) { + Ok(w) => w, + Err(e) => return (vec![text(&json!({ "error": e, "kind": "usage" }))], true), + }; + if cmd.name == "launch" { + // An agent wants a world it can play once the call returns. + if args.get("wait").and_then(Value::as_bool) != Some(false) + && !words.contains(&"--wait".to_owned()) + { + words.push("--wait".into()); + } + words.push("--no-pause".into()); + } + match self.run(&words) { + Ok(reply) => (vec![text(&reply)], false), + Err(f) => (vec![text(&f.reply)], true), + } + } + + fn handle(&mut self, method: &str, params: &Value) -> Result { + match method { + "initialize" => Ok(json!({ + "protocolVersion": params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL), + "capabilities": { "tools": {} }, + "serverInfo": { "name": "horizon-ctl", "version": env!("CARGO_PKG_VERSION") }, + "instructions": "Play Horizon, a Rust reimplementation of Minecraft Java Edition. Start with launch (it finds the game installed by the Horizon launcher and opens or creates a world), then read the world with state, inventory, screen, entities and find_block, and act with goto, look_at_block, break, place, interact, click_slot and click_button. Actions block until they finish and report what happened. Coordinates are block coordinates; yaw 0 faces south (+Z).", + })), + "ping" => Ok(json!({})), + "tools/list" => Ok(json!({ "tools": tools() })), + "tools/call" => { + let name = params + .get("name") + .and_then(Value::as_str) + .ok_or((-32602, "name is required".to_string()))?; + if !tools().iter().any(|t| t["name"] == name) { + return Err((-32602, format!("Unknown tool {name}"))); + } + let args = params.get("arguments").cloned().unwrap_or(json!({})); + let (content, error) = self.call(name, &args); + Ok(json!({ "content": content, "isError": error })) + } + _ => Err((-32601, format!("Method not found: {method}"))), + } + } +} + +pub fn serve(session: &mut Session) -> Result<(), String> { + let stdin = std::io::stdin(); + let mut stdout = std::io::stdout(); + for line in stdin.lock().lines() { + let Ok(line) = line else { break }; + if line.trim().is_empty() { + continue; + } + let reply = match serde_json::from_str::(&line) { + Err(e) => Some( + json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32700, "message": e.to_string() } }), + ), + Ok(msg) => { + let method = msg + .get("method") + .and_then(Value::as_str) + .unwrap_or_default(); + let params = msg.get("params").cloned().unwrap_or(json!({})); + // Notifications (no id) get no reply. + msg.get("id").cloned().map(|id| match session.handle(method, ¶ms) { + Ok(result) => json!({ "jsonrpc": "2.0", "id": id, "result": result }), + Err((code, message)) => json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } }), + }) + } + }; + if let Some(reply) = reply { + writeln!(stdout, "{reply}") + .and_then(|_| stdout.flush()) + .map_err(|e| e.to_string())?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn base64_matches_rfc_4648() { + assert_eq!(base64(b""), ""); + assert_eq!(base64(b"f"), "Zg=="); + assert_eq!(base64(b"fo"), "Zm8="); + assert_eq!(base64(b"foo"), "Zm9v"); + assert_eq!(base64(b"foobar"), "Zm9vYmFy"); + } + + #[test] + fn tools_have_schemas_and_unique_names() { + let list = tools(); + let mut names = std::collections::HashSet::new(); + for t in &list { + assert!(names.insert(t["name"].as_str().unwrap().to_owned())); + assert_eq!(t["inputSchema"]["type"], "object"); + } + for want in [ + "launch", + "state", + "goto", + "break_block", + "place", + "click_slot", + "click_button", + "screenshot", + "inventory", + ] { + let want = if want == "break_block" { "break" } else { want }; + assert!(names.contains(want), "{want}"); + } + } + + #[test] + fn protocol_basics() { + let mut s = Session::new(std::env::temp_dir().join("horizon-ctl-mcp-test.sock"), None); + let init = s + .handle("initialize", &json!({ "protocolVersion": "2025-03-26" })) + .unwrap(); + assert_eq!(init["protocolVersion"], "2025-03-26"); + assert!(s.handle("nope", &json!({})).is_err()); + let r = s + .handle( + "tools/call", + &json!({ "name": "goto", "arguments": { "x": 1 } }), + ) + .unwrap(); + assert_eq!(r["isError"], true); + assert!( + r["content"][0]["text"] + .as_str() + .unwrap() + .contains("y is required") + ); + // No game: a connection error, reported as a tool error. + let r = s + .handle("tools/call", &json!({ "name": "state", "arguments": {} })) + .unwrap(); + assert_eq!(r["isError"], true); + } +} From 772e0a7070957d5d22934d904ba1e6fb5abacbe2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 21:57:09 +0200 Subject: [PATCH 4/8] tools/agent_control_e2e.py: play a survival start through the CLI and MCP On a virtual screen: create a world through the title menus, walk to a tree, break a log, craft planks in the inventory screen, place one and read it back, once with horizon-ctl commands and once over horizon-ctl mcp. Co-Authored-By: Claude Opus 5.5 --- tools/agent_control_e2e.py | 302 +++++++++++++++++++++++++++++++++++++ 1 file changed, 302 insertions(+) create mode 100644 tools/agent_control_e2e.py diff --git a/tools/agent_control_e2e.py b/tools/agent_control_e2e.py new file mode 100644 index 000000000..781b59edb --- /dev/null +++ b/tools/agent_control_e2e.py @@ -0,0 +1,302 @@ +#!/usr/bin/env python3 +"""End-to-end check of agent control: play Horizon on a virtual screen with horizon-ctl. + +A script creates a world through the title menus, finds a tree it can walk to, breaks a log, +checks the inventory, crafts planks in the inventory screen, places one and reads it back. It +runs through the CLI (one horizon-ctl process per command) and through `horizon-ctl mcp` with a +small JSON-RPC client, and saves a screenshot of each run. + + python3 tools/agent_control_e2e.py # both modes + python3 tools/agent_control_e2e.py --mode mcp # one of them + python3 tools/agent_control_e2e.py --bin-dir target/fast --out /tmp/agent-e2e + +Needs vscreen (Linux desktop), the prepared resources in .local/horizon-client and a build of +horizon-client and horizon-ctl (built with the fast profile unless --bin-dir is given). Games +started here have no audio (HORIZON_NO_AUDIO=1). +""" +import argparse +import base64 +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +LAVAPIPE = Path('/run/opengl-driver/share/vulkan/icd.d/lvp_icd.x86_64.json') +LOG_KINDS = ['oak_log', 'birch_log', 'spruce_log', 'jungle_log', 'acacia_log', 'dark_oak_log', + 'mangrove_log', 'cherry_log'] +# Positional arguments of the commands the scenario uses, for the CLI. +POSITIONAL = { + 'goto': ['x', 'y', 'z'], 'break': ['x', 'y', 'z'], 'place': ['x', 'y', 'z'], 'block': ['x', 'y', 'z'], + 'find_block': ['block', 'radius'], 'entities': ['radius', 'type'], 'click_slot': ['slot'], + 'click_button': ['label'], 'type': ['text'], 'wait': ['ticks'], 'wait_ready': ['seconds'], + 'command': ['command'], 'look_at_block': ['x', 'y', 'z'], +} +# Booleans the game takes as bare words. +BARE = {'click_slot': ['right', 'shift']} + + +class Failed(Exception): + pass + + +def vscreen_env(screen): + env = dict(os.environ, VSCREEN=screen) + subprocess.run(['vscreen', 'up'], env=env, check=False, capture_output=True) + text = subprocess.run(['vscreen', 'env'], env=env, capture_output=True, text=True, check=True).stdout + env.pop('DISPLAY', None) + for match in re.finditer(r'(\w+)=(\S+)', text.split('unset')[0]): + env[match.group(1)] = match.group(2) + env['HORIZON_NO_AUDIO'] = '1' + if LAVAPIPE.exists(): + env['VK_ICD_FILENAMES'] = str(LAVAPIPE) + return env + + +class Cli: + """One horizon-ctl process per command, as a shell script would.""" + name = 'cli' + + def __init__(self, ctl, socket, cwd, env): + self.base = [str(ctl), '--socket', str(socket)] + self.cwd, self.env = cwd, env + + def __call__(self, tool, **args): + cmd = tool.replace('_', '-') + positional = [str(args.pop(k)) for k in POSITIONAL.get(tool, []) if k in args] + options = [] + for k, v in args.items(): + if v is True: + options.append(k if k in BARE.get(tool, []) else '--' + k) + elif v is not False and v is not None: + options += ['--' + k, str(v)] + # Options first: free text (type, command) runs to the end of the line. + words = [cmd] + (options + positional if tool in ('type', 'command') else positional + options) + if tool == 'screenshot': + words = ['screenshot', str(args.get('path', self.cwd / 'shot.png'))] + result = subprocess.run(self.base + words, cwd=self.cwd, env=self.env, capture_output=True, text=True, + timeout=600) + out = result.stdout.strip().splitlines() + reply = json.loads(out[-1]) if out else {'error': result.stderr.strip()} + log(self.name, words, reply) + if result.returncode or 'error' in reply: + raise Failed(f'{" ".join(words)}: exit {result.returncode}: {reply}') + return reply + + def close(self): + pass + + +class Mcp: + """`horizon-ctl mcp` driven over JSON-RPC, as an AI agent's client would.""" + name = 'mcp' + + def __init__(self, ctl, socket, cwd, env): + self.proc = subprocess.Popen([str(ctl), '--socket', str(socket), 'mcp'], cwd=cwd, env=env, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) + self.next_id = 0 + self.cwd = cwd + init = self.rpc('initialize', {'protocolVersion': '2025-06-18', 'capabilities': {}, + 'clientInfo': {'name': 'agent_control_e2e', 'version': '1'}}) + assert init['serverInfo']['name'] == 'horizon-ctl', init + self.notify('notifications/initialized') + self.tools = {t['name']: t for t in self.rpc('tools/list', {})['tools']} + print(f'[mcp] {len(self.tools)} tools: {", ".join(sorted(self.tools))}') + + def notify(self, method): + self.proc.stdin.write(json.dumps({'jsonrpc': '2.0', 'method': method}) + '\n') + self.proc.stdin.flush() + + def rpc(self, method, params): + self.next_id += 1 + self.proc.stdin.write(json.dumps({'jsonrpc': '2.0', 'id': self.next_id, 'method': method, + 'params': params}) + '\n') + self.proc.stdin.flush() + reply = json.loads(self.proc.stdout.readline()) + assert reply['id'] == self.next_id, reply + if 'error' in reply: + raise Failed(f'{method}: {reply["error"]}') + return reply['result'] + + def __call__(self, tool, **args): + if tool not in self.tools: + raise Failed(f'no MCP tool {tool}') + result = self.rpc('tools/call', {'name': tool, 'arguments': args}) + texts = [c for c in result['content'] if c['type'] == 'text'] + reply = json.loads(texts[-1]['text']) if texts else {} + images = [c for c in result['content'] if c['type'] == 'image'] + if images: + reply['_image'] = base64.b64decode(images[0]['data']) + log(self.name, [tool, args], {k: v for k, v in reply.items() if k != '_image'}) + if result['isError']: + raise Failed(f'{tool} {args}: {reply}') + return reply + + def close(self): + self.proc.stdin.close() + self.proc.wait(timeout=30) + + +def log(mode, words, reply): + text = json.dumps(reply) + print(f'[{mode}] {words if isinstance(words, list) else words} -> {text[:400]}{"..." if len(text) > 400 else ""}') + + +def trunk_bases(d): + """Logs with no log under them, nearest first: (distance, pos, log id).""" + bases = [] + for kind in LOG_KINDS: + found = d('find_block', block=kind, radius=40) + for n in found['nearest']: + x, y, z = n['pos'] + below = d('block', x=x, y=y - 1, z=z)['block'] + if not below.endswith('_log') and not below.endswith('_wood'): + bases.append((n['distance'], (x, y, z), found['block'])) + return sorted(bases) + + +def scenario(d, out): + # 1. A world, made through the title screen's menus. + screen = d('screen') + assert screen['screen'] == 'title', screen + assert any(b['label'] == 'Singleplayer' for b in screen['buttons']), screen + d('click_button', label='Singleplayer') + d('click_button', label='Create New World') + d('type', field='name', replace=True, text='Agent World') + d('type', field='seed', text='5') # spawn near a walkable oak + created = d('click_button', label='Create New World') + assert created['screen'] == 'playing', created + d('wait_ready', seconds=400) + state = d('state') + assert state['gamemode'] == 'survival' and state['player']['health'] > 0, state + d('command', command='time set day') + + # 2. Walk to a tree: the nearest trunk the path finder can reach. + for _, base, log_id in trunk_bases(d)[:8]: + x, y, z = base + try: + d('goto', x=x + 0.5, y=y, z=z + 0.5, near=2.5, timeout=60) + break + except Failed as e: + print(f' cannot reach {log_id} at {base}: {e}') + else: + raise Failed('no reachable tree near spawn') + + # 3. Break the log at the bottom of the trunk; it must end up in the inventory. + broke = d('break', x=x, y=y, z=z) + assert broke['block_before'].startswith(log_id), broke + assert broke['drops'].get(log_id, 0) >= 1, broke + if broke['picked_up'].get(log_id, 0) < 1: + items = d('entities', radius=8, type='item')['entities'] + drop = next(e for e in items if e['item']['item'] == log_id) + d('goto', x=drop['pos'][0], y=drop['pos'][1], z=drop['pos'][2], near=0.4, timeout=20) + d('wait', ticks=10) + inventory = d('inventory') + assert inventory['counts'].get(log_id, 0) >= 1, inventory + + # 4. Craft planks in the inventory screen's 2x2 grid. + planks_id = log_id.replace('_log', '_planks') + d('open_inventory') + screen = d('screen') + assert screen['screen'] == 'inventory' and screen['craft_size'] == 2, screen + log_slot = next(s['slot'] for s in screen['slots'] if s.get('item') == log_id and s['slot'] < 36) + d('click_slot', slot=log_slot) # pick up the logs + d('click_slot', slot=100, right=True) # put one in the crafting grid + d('click_slot', slot=log_slot) # put the rest back + result = next(s for s in d('screen')['slots'] if s['slot'] == 200) + assert result.get('item') == planks_id and result['count'] == 4, result + d('click_slot', slot=200, shift=True) # craft into the inventory + d('close') + inventory = d('inventory') + assert inventory['counts'].get(planks_id, 0) >= 4, inventory + + # 5. Place a plank beside the player and read it back. + p = d('state')['player']['block_pos'] + target = None + for dx, dz in [(2, 0), (-2, 0), (0, 2), (0, -2), (2, 1), (1, 2), (-2, -1), (-1, -2)]: + at = (p[0] + dx, p[1], p[2] + dz) + here = d('block', x=at[0], y=at[1], z=at[2])['block'] + below = d('block', x=at[0], y=at[1] - 1, z=at[2])['block'] + if here in ('minecraft:air', 'minecraft:short_grass') and below not in ('minecraft:air', 'minecraft:water'): + target = at + break + if target is None: + raise Failed(f'no free spot beside {p} to place a block') + hotbar = d('inventory')['hotbar'] + if not any(s.get('item') == planks_id for s in hotbar): + raise Failed(f'{planks_id} did not land in the hotbar: {hotbar}') + placed = d('place', x=target[0], y=target[1], z=target[2], item=planks_id) + assert placed['changed'], placed + back = d('block', x=target[0], y=target[1], z=target[2]) + assert back['block'] == planks_id, back + d('look_at_block', x=target[0], y=target[1], z=target[2]) + shot = d('screenshot', path=str(out / f'{d.name}.png')) + if '_image' in shot: + (out / f'{d.name}.png').write_bytes(shot['_image']) + seen = d('looking_at') + assert seen['kind'] == 'block' and seen['block']['pos'] == list(target), seen + return {'tree': base, 'log': log_id, 'placed': target} + + +def run(mode, ctl, out, resources): + work = Path(tempfile.mkdtemp(prefix=f'hzac-{mode}-')) + (work / '.local').mkdir() + (work / '.local/horizon-client').mkdir() + os.symlink(resources, work / '.local/horizon-client/26.3') + socket = work / 'c.sock' + env = vscreen_env(os.environ.get('VSCREEN', 'agent-control')) + driver = (Cli if mode == 'cli' else Mcp)(ctl, socket, work, env) + started = time.time() + try: + driver('launch', wait=False) + summary = scenario(driver, out) + print(f'[{mode}] PASS in {time.time() - started:.0f} s: {summary}') + return True + except (Failed, AssertionError, StopIteration) as e: + print(f'[{mode}] FAIL: {e!r}') + log_file = socket.with_suffix('.log') + if log_file.exists(): + print('game log tail:\n' + '\n'.join(log_file.read_text(errors='replace').splitlines()[-15:])) + return False + finally: + try: + driver('quit') + except Exception: + pass + driver.close() + time.sleep(2) + shutil.rmtree(work, ignore_errors=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--mode', choices=['cli', 'mcp', 'both'], default='both') + parser.add_argument('--bin-dir', help='prebuilt horizon-client and horizon-ctl (default: build with the fast profile)') + parser.add_argument('--out', default=str(ROOT / '.local/agent-control-e2e'), help='screenshots go here') + args = parser.parse_args() + if args.bin_dir: + bins = Path(args.bin_dir).resolve() + else: + subprocess.run(['cargo', 'build', '--locked', '--profile', 'fast', '-p', 'horizon-client', '--bins'], + cwd=ROOT, check=True) + meta = json.loads(subprocess.run(['cargo', 'metadata', '--format-version', '1', '--no-deps'], cwd=ROOT, + capture_output=True, text=True, check=True).stdout) + bins = Path(meta['target_directory']) / 'fast' + resources = (ROOT / '.local/horizon-client/26.3').resolve() + if not (resources / 'horizon-resources.json').exists(): + sys.exit(f'no prepared resources in {resources}') + out = Path(args.out) + out.mkdir(parents=True, exist_ok=True) + modes = ['cli', 'mcp'] if args.mode == 'both' else [args.mode] + results = {m: run(m, bins / 'horizon-ctl', out, resources) for m in modes} + print(json.dumps(results)) + sys.exit(0 if all(results.values()) else 1) + + +if __name__ == '__main__': + main() From 601fbb533a051e92f0ad3df327f686948c602d79 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 21:59:34 +0200 Subject: [PATCH 5/8] Ship horizon-ctl in the release folders release.yml builds horizon-ctl beside the client (checked for system-only imports like it), packaging/package.sh copies it from beside the client binary and refuses to package without it (the macOS folders made by hand go through the same script), and package_native_client.py adds it to private archives. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 15 ++++++++++----- packaging/PLAY.txt | 9 +++++++++ packaging/package.sh | 11 ++++++++++- tools/package_native_client.py | 5 ++++- 4 files changed, 33 insertions(+), 7 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b6e36a6e3..e36ce3685 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,7 @@ name: release builds # Started by hand: gh workflow run release.yml --ref -# Builds the Windows x64 and Linux x86_64 clients and uploads the playable folders as artifacts. +# Builds the Windows x64 and Linux x86_64 clients (with horizon-ctl) and uploads the playable folders +# as artifacts. # macOS builds are made on the development machines. Linux is built here, on an older Ubuntu, # so the binary uses the standard loader and runs on any recent distribution (and on NixOS # through nix-ld): a build made on NixOS asks for a /nix/store loader no other system has. @@ -19,11 +20,13 @@ jobs: # The C runtime linked in, so the game runs without the Visual C++ redistributable. env: RUSTFLAGS: -C target-feature=+crt-static - run: cargo +stable build --release --locked -p horizon-client --bin horizon-client + run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl - name: Only system DLLs # Vulkan and the rest are loaded at run time; a linked non-system DLL is a # "DLL not found" dialog on some players' machines. - run: python tools/check_imports.py target/release/horizon-client.exe + run: | + python tools/check_imports.py target/release/horizon-client.exe + python tools/check_imports.py target/release/horizon-ctl.exe - name: Package shell: bash run: packaging/package.sh target/release/horizon-client.exe dist/horizon-windows-x64 @@ -40,9 +43,11 @@ jobs: - name: ALSA headers run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev - name: Build the client - run: cargo +stable build --release --locked -p horizon-client --bin horizon-client + run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl - name: Standard loader and libraries only - run: python3 tools/check_imports.py target/release/horizon-client + run: | + python3 tools/check_imports.py target/release/horizon-client + python3 tools/check_imports.py target/release/horizon-ctl - name: Package run: packaging/package.sh target/release/horizon-client dist/horizon-linux-x86_64 - uses: actions/upload-artifact@v4 diff --git a/packaging/PLAY.txt b/packaging/PLAY.txt index 292656c55..e932c0db3 100644 --- a/packaging/PLAY.txt +++ b/packaging/PLAY.txt @@ -30,3 +30,12 @@ Downloaded this archive directly? Controls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint, left click break, right click place/use, 1-9 or scroll for the hotbar, E inventory, Q drop, F1 hide the HUD, F3 debug, Esc pause. + +Scripts and AI agents + horizon-ctl, in this folder, plays the game from a terminal or a script: + ./horizon-ctl launch --world Test --wait (horizon-ctl.exe on Windows) + ./horizon-ctl state + ./horizon-ctl help lists every command + horizon-ctl mcp is an MCP server for AI agents (stdio; add it to your MCP + client as the command horizon-ctl with the argument mcp). It finds the game + beside it or the version the launcher installed. diff --git a/packaging/package.sh b/packaging/package.sh index 0cab07331..a289116a0 100755 --- a/packaging/package.sh +++ b/packaging/package.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash # packaging/package.sh BINARY OUTDIR: a playable Horizon folder with the game -# binary, the resource preparation tool and what it compiles, and PLAY.txt. +# binary, horizon-ctl (built beside it: cargo build --release -p horizon-client --bins), +# the resource preparation tool and what it compiles, and PLAY.txt. # It holds none of Minecraft's files: players prepare those from their own copy. set -euo pipefail bin=$1 @@ -10,4 +11,12 @@ rm -rf "$out" mkdir -p "$out" git -C "$repo" archive HEAD tools mods/horizon/src/test/java research-lock.json LICENSE | tar -x -C "$out" cp "$bin" "$out/" +# horizon-ctl, the command line and MCP server that play the game, sits beside the client. +ctl="$(dirname "$bin")/horizon-ctl" +case "$bin" in *.exe) ctl="$ctl.exe" ;; esac +if [ ! -f "$ctl" ]; then + echo "package.sh: $ctl is missing; build it too: cargo build --release -p horizon-client --bins" >&2 + exit 1 +fi +cp "$ctl" "$out/" cp "$repo/packaging/PLAY.txt" "$out/PLAY.txt" diff --git a/tools/package_native_client.py b/tools/package_native_client.py index 82847ee4b..abda2210f 100644 --- a/tools/package_native_client.py +++ b/tools/package_native_client.py @@ -3,7 +3,7 @@ tarball for one of your own Linux or macOS machines. The resources are Mojang assets: keep the archive in ignored .local/ and never publish or commit it. - cargo build --release -p horizon-client + cargo build --release -p horizon-client --bins python3 tools/package_native_client.py """ import argparse @@ -102,6 +102,9 @@ def main(): archive = args.out / f'{name}.tar.gz' with tarfile.open(archive, 'w:gz', compresslevel=1) as tar: tar.add(args.binary, 'horizon/horizon-client') + ctl = args.binary.with_name('horizon-ctl') # built with --bins: scripts and agents play through it + if ctl.is_file(): + tar.add(ctl, 'horizon/horizon-ctl') add_bytes(tar, 'horizon/horizon.sh', LAUNCHER.encode(), 0o755) tar.add(ROOT / 'docs/media/icon-256.png', 'horizon/horizon.png') add_bytes(tar, 'horizon/README.txt', README.format(version=version, commit=commit, platform=plat).encode()) From 6716b0d9531fdfcf072b8ddc4bdae990b245019d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 21:59:35 +0200 Subject: [PATCH 6/8] Docs: agent control with horizon-ctl and its MCP server README gets an Agent control section (out of the roadmap: it's done), the native client guide describes every command group, the blocking semantics, exit codes, launch discovery, MCP and the two transports, and PLAY.txt tells release players about horizon-ctl. Co-Authored-By: Claude Opus 5.5 --- README.md | 18 +++++++- docs/native-client.md | 104 +++++++++++++++++++++++++++++++++--------- 2 files changed, 99 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index f790d29bd..f1d723aae 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,21 @@ The [native client](docs/native-client.md) opens on a vanilla-style title screen - shields, maps, books, fireworks, beacons, advancements and statistics; - Anvil saves, joining vanilla servers, and opening a world to LAN. +## Agent control + +AI agents and scripts can play Horizon. `horizon-ctl`, shipped beside the game in every release folder, is a command line that reads the game as JSON and acts like a player; `horizon-ctl mcp` serves the same commands as an MCP server (one tool per command, screenshots returned as images). + +```sh +horizon-ctl launch --world Survival --seed 5 --wait # finds the version the launcher installed +horizon-ctl state # position, health, food, target, screen... +horizon-ctl find-block birch_log # the nearest logs +horizon-ctl goto -0.5 65 -2.5 --near 2.5 # walks there along a path +horizon-ctl break -1 65 -3 # mines it; replies with the drops +horizon-ctl open-inventory && horizon-ctl click-slot 0 # menus: slots, buttons by label, text fields +``` + +Commands block until the action is done and reply with what happened; errors are JSON with distinct exit codes, `horizon-ctl help` lists every command and `horizon-ctl COMMAND --help` explains one with examples. It talks to the game over a Unix socket on Linux and macOS and over a token-protected localhost port on Windows. See [Agent control in the native client guide](docs/native-client.md#agent-control-horizon-ctl-and-mcp). + ## Build from source For developers. Requirements: Rust 1.90 or newer, Python 3.10 or newer, JDK 25, and on Linux the ALSA development headers (`libasound2-dev` on Debian and Ubuntu). Development and the vanilla harnesses run on Linux. @@ -132,7 +147,7 @@ cargo run --release -p horizon-client Everything prepared lands in the gitignored `.local/`. It is derived from the game: never commit it or share it. -The client starts on the title screen. Command-line options (`--world`, `--seed`, `--creative`, `--render-distance`, `--dedicated`), controls, scripting through `horizon-ctl`, and the architecture are described in [the native client guide](docs/native-client.md). The rest of the documentation is indexed in [docs/README.md](docs/README.md), including [the parity workflow](docs/parity-workflow.md). +The client starts on the title screen. Command-line options (`--world`, `--seed`, `--creative`, `--render-distance`, `--dedicated`), controls, playing and scripting through `horizon-ctl` and its MCP server, and the architecture are described in [the native client guide](docs/native-client.md). The rest of the documentation is indexed in [docs/README.md](docs/README.md), including [the parity workflow](docs/parity-workflow.md). ## Project status @@ -175,7 +190,6 @@ them too (Rust uses Java's own float maths on each platform). - **Performance optimisation:** take the client and the server as far as they can go (rendering, chunk generation and meshing, memory, multithreaded ticking), building on v2026.10.13.1's faster renderer, while the differential harnesses keep gameplay identical to vanilla. - **Mod support:** a stable API for writing and loading mods against Horizon. -- **Agent control:** an MCP server and a CLI so AI agents and scripts can play and drive the game, growing out of today's `horizon-ctl` scripting socket (the launcher already works as a CLI and an MCP server for installing and starting Horizon). - **Built-in recording:** capture gameplay video in a keypress, without external tools. - **Automatic version updates:** a pipeline that ports each new Minecraft release on its own: compare the new version with the pinned one, regenerate the data, rewrite the changed parts and prove them with the same differential harnesses. diff --git a/docs/native-client.md b/docs/native-client.md index 209026f0c..b6f2e0db5 100644 --- a/docs/native-client.md +++ b/docs/native-client.md @@ -64,35 +64,97 @@ mute a test run's stream in the mixer: PipeWire remembers the mute for every later `horizon-client`. The launcher starts the game as "Horizon" for that reason. -### Drive the game from scripts (`horizon-ctl`) +### Agent control (`horizon-ctl` and MCP) -`--control` opens a local Unix socket (`$XDG_RUNTIME_DIR/horizon-control.sock`, -or `--control-socket PATH`). `horizon-ctl` sends it one command per line and -prints one JSON reply per command; the exit status is 1 when the reply holds an -`error`. Under control, losing window focus does not pause the game or release -held keys, so a script can play while you use other windows. +AI agents and scripts play Horizon through `horizon-ctl`, a command line that +reads the game as JSON and acts like a player, and `horizon-ctl mcp`, an MCP +server with the same commands. `--control` makes the game accept them on a +local socket; under control, losing window focus does not pause the game or +release held keys, so a script can play while you use other windows. ```sh cargo build --release -p horizon-client --bins C=target/release/horizon-ctl -$C launch --world Bench --seed 12345 --render-distance 32 # starts the game, waits for the socket -$C wait-ready # player spawned, no chunks pending -$C look 90 10; $C hold w 2 # face west, walk for two seconds -$C screenshot /tmp/view.png # PNG of the next presented frame -$C bench 10 # avg/1%-low FPS and p50/p95/p99/max frame times -$C quit # save and exit +$C launch --world Survival --seed 5 --wait # start the game, open or create the world, wait for it +$C state # player, world, screen, crosshair target +$C find-block birch_log # the 16 nearest loaded logs +$C goto -0.5 65 -2.5 --near 2.5 # walk there along a path +$C break -1 65 -3 # mine it: {"drops": {"minecraft:birch_log": 1}, ...} +$C inventory # hotbar, inventory, armor, offhand, counts +$C open-inventory # craft planks in the 2x2 grid: +$C click-slot 0; $C click-slot 100 right; $C click-slot 0; $C click-slot 200 shift; $C close +$C place 2 65 -2 --item birch_planks # {"changed": true, "block": {...}} +$C screenshot /tmp/view.png # PNG of the next presented frame +$C quit # save and exit ``` -`fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH]` moves the camera along a line at -constant speed and replies with the same summary as `bench`, plus CPU and GPU -time per frame; [the graphics benchmark](graphics.md#benchmark) is built on it. +`horizon-ctl help` lists the commands by group and `horizon-ctl COMMAND --help` +explains one with examples; `horizon-ctl help --game` lists what the running +game accepts, test hooks included. -Other commands: `status`, `key KEY down|up|tap`, `mouse left|right|middle -down|up|click`, `turn`, `tp X Y Z`, `hotbar N`, `give ITEM [COUNT]`, -`render-distance N`, `time TICKS`, `resume`, `stats [reset]`, `open WORLD [SEED] -[creative]` and `save`; `horizon-ctl help` lists them from the running game. -`horizon-ctl -` reads a script from standard input, where `sleep S` waits locally. -Frame times include waits for presentation, so `bench` reports what is on screen. +- **Observe:** `state` (position, rotation, velocity, health, food, saturation, + XP, effects, game mode, dimension, time, weather, the screen and what the + crosshair points at), `looking-at`, `entities [RADIUS] [TYPE]` (mobs with + ids and health, dropped items, orbs), `block X Y Z`, `blocks X1 Y1 Z1 X2 Y2 Z2`, + `find-block BLOCK [RADIUS]`, `inventory` (stacks with their components as + SNBT), `screen` (the open screen or title menu, its buttons and slots) and + `messages` (chat, title, subtitle and action bar). +- **Move and act:** `move DIR SECONDS`, `jump`, `goto X Y Z` (A* over standable + blocks: steps up one block, drops up to three, avoids lava), `look`, + `look-at` a point, block face or entity, `attack [ID]`, `break X Y Z`, + `place X Y Z [--item ITEM]`, `interact X Y Z` (doors, chests, crafting + tables), `use-item [--hold S]` (eat, drink, throw), `select SLOT|ITEM`, `drop`. +- **Screens:** `open-inventory`, `click-slot SLOT [right] [shift]` (0-8 hotbar, + 9-35 inventory, 100+ crafting grid, 200 result, 300+ containers, 500-503 + armor, 504 offhand, 600+ stations), `close`, `click-button LABEL` (any + button of any screen or title menu, classic or Horizon style, by its label), + `click-at X Y`, `type TEXT` (on the create-world screen `--field name|seed + --replace`), `chat`, `command`, `respawn`, `pause`, `resume`. +- **World:** `tp`, `give`, `time`, `setblock`, `summon`, `wait TICKS`, and the + benchmarking commands `bench`, `stats` and `fly` (below). + +Actions block until they finish or time out and reply with the outcome: `goto` +says whether it arrived, `break` what dropped and what was picked up, `place` +the block placed. `stop` cancels the running action. Every reply is one JSON +line; errors are `{"error": "..."}` objects, and the exit status is 0 on +success, 1 when the game replied with an error, 2 for a usage error and 3 when +the game cannot be reached or started. `horizon-ctl script FILE` (or stdin) +runs one command per line with shell-like quoting and stops at the first error +(`--keep-going` doesn't); `sleep S` waits. `horizon-ctl -` is the older form +that reads stdin and keeps going. + +`launch` finds the game to start: `--game PATH`, else a `horizon-client` next +to `horizon-ctl` (a build folder or a release folder), else the newest version +the launcher installed (`--version TAG` picks another), run with its prepared +resources from the game home, where the saves are. So after installing with +the launcher, `horizon-ctl launch --world X --wait` is all an agent needs. +Other arguments go to the game; its output goes to a `.log` file beside the +socket. + +**MCP.** `horizon-ctl mcp` serves the Model Context Protocol over stdin and +stdout (JSON-RPC 2.0, one message per line), with one tool per command and a +JSON schema for each; `screenshot` returns the frame as an image. Register it +in an MCP client as a stdio server with the command `horizon-ctl` and the +argument `mcp` (`--socket PATH` before `mcp` to pick a socket). + +**Transport.** On Linux and macOS the endpoint is a Unix socket: +`$HORIZON_CONTROL`, else `$XDG_RUNTIME_DIR/horizon-control.sock`, or +`--control-socket PATH` (`horizon-ctl --socket PATH`). Windows has no Unix +sockets: there the game listens on a random `127.0.0.1` port and writes +`{"transport":"tcp","port":N,"token":"..."}` to the endpoint path +(`%TEMP%\horizon-control.json` by default), readable only by its user; the +client's first line must be `auth TOKEN`. Any endpoint path ending in `.json` +selects that transport on Linux and macOS too. + +`tools/agent_control_e2e.py` checks it all on a virtual screen: it creates a +world through the title menus, walks to a tree, breaks a log, crafts planks in +the inventory screen and places one, through the CLI and through MCP. + +`fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH]` moves the camera along a line at +constant speed and replies with the same summary as `bench` (avg/1%-low FPS and +p50/p95/p99/max frame times), plus CPU and GPU time per frame; [the graphics +benchmark](graphics.md#benchmark) is built on it. Frame times include waits for +presentation, so `bench` reports what is on screen. ### Play on another of your machines From c0f468a8718887f081f55696db4b253e246a7b27 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:00:44 +0200 Subject: [PATCH 7/8] horizon-ctl: horizon-ctl - returns the last failure's status Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/bin/horizon-ctl/main.rs | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/bin/horizon-ctl/main.rs b/crates/horizon-client/src/bin/horizon-ctl/main.rs index 193f84410..39bcc1d8e 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/main.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/main.rs @@ -406,15 +406,8 @@ fn main() -> ExitCode { UNREACHABLE } }, - Some("-") => { - // The original form: stdin, keep going, status 1 if anything failed. - let status = script(&mut session, std::io::stdin().lock(), true, pretty); - if status == 0 { - 0 - } else { - status.min(GAME_ERROR).max(1) - } - } + // The original form: stdin, keep going after errors. + Some("-") => script(&mut session, std::io::stdin().lock(), true, pretty), Some("script") => { let keep_going = args.iter().any(|a| a == "--keep-going"); match args.iter().skip(1).find(|a| !a.starts_with("--")) { From 502c8b9311f6c2ac17ee64a830c4d211cfcc0579 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:28:14 +0200 Subject: [PATCH 8/8] agent_control_e2e: pick up a drop from within a block (it can land under the trunk) Co-Authored-By: Claude Opus 5.5 --- tools/agent_control_e2e.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/agent_control_e2e.py b/tools/agent_control_e2e.py index 781b59edb..5d56398bc 100644 --- a/tools/agent_control_e2e.py +++ b/tools/agent_control_e2e.py @@ -194,7 +194,7 @@ def scenario(d, out): if broke['picked_up'].get(log_id, 0) < 1: items = d('entities', radius=8, type='item')['entities'] drop = next(e for e in items if e['item']['item'] == log_id) - d('goto', x=drop['pos'][0], y=drop['pos'][1], z=drop['pos'][2], near=0.4, timeout=20) + d('goto', x=drop['pos'][0], y=drop['pos'][1], z=drop['pos'][2], near=1.0, timeout=20) # pickup reaches a block; the drop may lie under the trunk d('wait', ticks=10) inventory = d('inventory') assert inventory['counts'].get(log_id, 0) >= 1, inventory