Merge remote-tracking branch 'origin/agent-control' into merge-50-53
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
name: release builds
|
||||
# Started by hand: gh workflow run release.yml --ref <branch>
|
||||
# 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
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -1,204 +0,0 @@
|
||||
//! horizon-ctl: drive a running Horizon client through its control socket.
|
||||
#![forbid(unsafe_code)]
|
||||
use std::{
|
||||
io::{BufRead, BufReader, Write},
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, ExitCode, Stdio},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use horizon_client::control::UnixStream;
|
||||
|
||||
const USAGE: &str = "usage: horizon-ctl [--socket PATH] COMMAND [ARGS...]
|
||||
|
||||
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)
|
||||
|
||||
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<UnixStream>,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
fn connect(path: &Path) -> Result<Self, String> {
|
||||
let stream = UnixStream::connect(path).map_err(|e| {
|
||||
format!(
|
||||
"cannot connect to {} ({e}); is the game running with --control?",
|
||||
path.display()
|
||||
)
|
||||
})?;
|
||||
let reader = BufReader::new(stream.try_clone().map_err(|e| e.to_string())?);
|
||||
Ok(Self {
|
||||
writer: stream,
|
||||
reader,
|
||||
})
|
||||
}
|
||||
fn send(&mut self, line: &str) -> Result<String, String> {
|
||||
writeln!(self.writer, "{line}").map_err(|e| 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());
|
||||
}
|
||||
Ok(reply.trim_end().to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
fn is_error(reply: &str) -> bool {
|
||||
serde_json::from_str::<serde_json::Value>(reply).map_or(true, |v| v.get("error").is_some())
|
||||
}
|
||||
|
||||
/// Screenshot paths are written by the game process: make them absolute here.
|
||||
fn absolute_paths(words: &mut [String]) {
|
||||
if words.first().map(String::as_str) == Some("screenshot")
|
||||
&& let Some(path) = words.get_mut(1)
|
||||
&& let Ok(cwd) = std::env::current_dir()
|
||||
{
|
||||
*path = cwd.join(&*path).display().to_string();
|
||||
}
|
||||
}
|
||||
|
||||
fn run_line(client: &mut Client, words: &mut [String]) -> Result<bool, String> {
|
||||
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::<f64>().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);
|
||||
}
|
||||
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::<f64>())
|
||||
.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));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
absolute_paths(words);
|
||||
let reply = client.send(&words.join(" "))?;
|
||||
println!("{reply}");
|
||||
Ok(!is_error(&reply))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn launch(socket: &Path, args: &[String]) -> Result<bool, String> {
|
||||
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);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({ "error": "control socket did not open within 300 seconds", "log": log })
|
||||
);
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let mut args: Vec<String> = 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<String> = 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)?;
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Vec<String>, String> {
|
||||
let mut words: Vec<String> = 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<String> = 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::<i64>().is_err() => {
|
||||
return Err(format!("{} must be an integer, not {text}", p.name));
|
||||
}
|
||||
Ty::Num if text.parse::<f64>().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"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 `<launcher home>/versions/<tag>`, each with its prepared
|
||||
//! resources in `.local/horizon-client/<minecraft version>` 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<u64> {
|
||||
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<String> {
|
||||
let mut tags: Vec<String> = 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<PathBuf> {
|
||||
let version = std::fs::read_to_string(dir.join("research-lock.json"))
|
||||
.ok()
|
||||
.and_then(|t| serde_json::from_str::<Value>(&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<PathBuf>,
|
||||
/// The working directory (the game home for prepared installs).
|
||||
pub cwd: Option<PathBuf>,
|
||||
pub source: &'static str,
|
||||
pub version: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<Install, String> {
|
||||
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<PathBuf>,
|
||||
pub version: Option<String>,
|
||||
pub wait: bool,
|
||||
pub game_args: Vec<String>,
|
||||
}
|
||||
|
||||
pub fn parse(args: &[String]) -> Result<Options, String> {
|
||||
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<Value, Value> {
|
||||
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::<Vec<_>>(),
|
||||
"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<String> = ["--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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,481 @@
|
||||
//! 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::ExitCode,
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use horizon_client::control::Stream;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Exit statuses.
|
||||
const GAME_ERROR: u8 = 1;
|
||||
const USAGE: u8 = 2;
|
||||
const UNREACHABLE: u8 = 3;
|
||||
|
||||
/// 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<String>) -> Self {
|
||||
Self {
|
||||
reply: json!({ "error": message.into(), "kind": "usage" }),
|
||||
status: USAGE,
|
||||
}
|
||||
}
|
||||
fn unreachable(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
reply: json!({ "error": message.into(), "kind": "connection" }),
|
||||
status: UNREACHABLE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Client {
|
||||
writer: Stream,
|
||||
reader: BufReader<Stream>,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
fn connect(path: &Path, timeout: Option<Duration>) -> Result<Self, Failure> {
|
||||
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()
|
||||
))
|
||||
})?;
|
||||
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,
|
||||
})
|
||||
}
|
||||
/// Send one line and read its JSON reply.
|
||||
fn send(&mut self, line: &str) -> Result<Value, Failure> {
|
||||
writeln!(self.writer, "{line}").map_err(|e| Failure::unreachable(e.to_string()))?;
|
||||
let mut reply = String::new();
|
||||
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"));
|
||||
}
|
||||
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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Global options and the connection, opened on first use.
|
||||
pub struct Session {
|
||||
pub socket: PathBuf,
|
||||
pub timeout: Option<Duration>,
|
||||
client: Option<Client>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn new(socket: PathBuf, timeout: Option<Duration>) -> 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<Value, Failure> {
|
||||
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<Value, Failure> {
|
||||
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<f64, Failure> {
|
||||
words
|
||||
.get(i)
|
||||
.ok_or_else(|| Failure::usage(format!("missing {what}; usage: {}", usage(name))))?
|
||||
.parse::<f64>()
|
||||
.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<Value, Failure> {
|
||||
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.
|
||||
fn absolute_paths(words: &mut [String]) {
|
||||
if words.first().map(String::as_str) == Some("screenshot")
|
||||
&& let Some(path) = words.get_mut(1)
|
||||
&& let Ok(cwd) = std::env::current_dir()
|
||||
{
|
||||
*path = cwd.join(&*path).display().to_string();
|
||||
}
|
||||
}
|
||||
|
||||
/// Split a script line like a shell: quotes keep spaces, backslash escapes.
|
||||
pub fn split_line(line: &str) -> Result<Vec<String>, String> {
|
||||
let mut words = Vec::new();
|
||||
let mut word = String::new();
|
||||
let mut in_word = false;
|
||||
let mut quote: Option<char> = 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;
|
||||
}
|
||||
(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
if quote.is_some() {
|
||||
return Err("unterminated quote".into());
|
||||
}
|
||||
if in_word {
|
||||
words.push(word);
|
||||
}
|
||||
Ok(words)
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let mut args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let mut socket = horizon_client::control::default_path();
|
||||
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);
|
||||
}
|
||||
Some("--timeout") if args.len() >= 2 => {
|
||||
let Ok(s) = args[1].parse::<f64>() 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
|
||||
}
|
||||
},
|
||||
// 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("--")) {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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<Value> {
|
||||
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<Value>, 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<Value, (i64, String)> {
|
||||
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::<Value>(&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);
|
||||
}
|
||||
}
|
||||
@@ -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<Self> {
|
||||
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: AsRef<Path>>(_: P) -> io::Result<Self> {
|
||||
Err(unavailable())
|
||||
}
|
||||
pub fn try_clone(&self) -> io::Result<Self> {
|
||||
Err(unavailable())
|
||||
/// A read timeout (None waits forever).
|
||||
pub fn set_read_timeout(&self, timeout: Option<std::time::Duration>) -> 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<usize> {
|
||||
Err(unavailable())
|
||||
}
|
||||
impl Read for Stream {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
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<usize> {
|
||||
Err(unavailable())
|
||||
}
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
impl Write for Stream {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
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: AsRef<Path>>(_: P) -> io::Result<Self> {
|
||||
Err(unavailable())
|
||||
}
|
||||
pub fn incoming(&self) -> std::iter::Empty<io::Result<UnixStream>> {
|
||||
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<Stream> {
|
||||
#[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<Request>,
|
||||
}
|
||||
|
||||
/// `$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<Self> {
|
||||
// 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<Self> {
|
||||
// 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<S: Send + 'static>(
|
||||
mut accept_next: impl FnMut() -> io::Result<S> + Send + 'static,
|
||||
sender: mpsc::Sender<Request>,
|
||||
accept: impl Fn(S) -> Option<Stream> + 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<Request>) {
|
||||
fn serve(stream: Stream, sender: &mpsc::Sender<Request>) {
|
||||
let Ok(mut writer) = stream.try_clone() else {
|
||||
return;
|
||||
};
|
||||
@@ -140,6 +298,55 @@ fn serve(stream: UnixStream, sender: &mpsc::Sender<Request>) {
|
||||
}
|
||||
}
|
||||
|
||||
#[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)]
|
||||
|
||||
@@ -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<horizon_client::gfx::Frustum>,
|
||||
/// A scripted flight from the control socket (`fly`).
|
||||
flight: Option<control::Flight>,
|
||||
/// 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<Option<((i64, u32, u32), i32)>>,
|
||||
persist: persist::EntityMemory,
|
||||
@@ -8618,6 +8621,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(),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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::<Vec<_>>() }))),
|
||||
"setblock" | "fill" | "particle" | "signedit" => self.render_command(&words),
|
||||
"sculk" => Ok(Some(self.sculk_command(&words)?)),
|
||||
|
||||
@@ -130,6 +130,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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<Widget>, Vec<Widget>, 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<Widget> {
|
||||
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<Widget, String> {
|
||||
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::<Vec<_>>()
|
||||
)),
|
||||
many => Err(format!(
|
||||
"{label:?} matches several buttons: {:?}",
|
||||
many.iter().map(|w| w.label.as_str()).collect::<Vec<_>>()
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[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());
|
||||
}
|
||||
}
|
||||
+83
-21
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
+10
-1
@@ -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"
|
||||
|
||||
@@ -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=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
|
||||
|
||||
# 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()
|
||||
@@ -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())
|
||||
|
||||
Reference in New Issue
Block a user