Launcher: CLI subcommands and an MCP server over stdio, both on the shared core
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -359,6 +359,147 @@ pub fn agree_eula(folder: &Path) -> Result<(), String> {
|
||||
fs::write(folder.join("eula.txt"), text).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// ----- Shared steps for the front ends -----------------------------------------------------------
|
||||
|
||||
/// The installed version to use: the one asked for, else the selected one, else the newest.
|
||||
pub fn resolve_version(requested: Option<&str>) -> Result<String, String> {
|
||||
let installed = installed();
|
||||
if let Some(tag) = requested {
|
||||
return installed.iter().find(|t| *t == tag).cloned().ok_or_else(|| format!("{tag} is not installed."));
|
||||
}
|
||||
let selected = Settings::load().selected.filter(|s| installed.contains(s));
|
||||
selected.or_else(|| installed.first().cloned()).ok_or_else(|| "No version is installed yet.".into())
|
||||
}
|
||||
|
||||
/// Removes an installed version and moves the selection to the newest one left if needed.
|
||||
pub fn remove_version(tag: &str) -> Result<(), String> {
|
||||
if !installed().iter().any(|t| t == tag) {
|
||||
return Err(format!("{tag} is not installed."));
|
||||
}
|
||||
remove(tag)?;
|
||||
let mut settings = Settings::load();
|
||||
if settings.selected.as_deref() == Some(tag) {
|
||||
settings.selected = installed().first().cloned();
|
||||
settings.save();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The Minecraft folder to prepare from: the one given, the one chosen in the launcher, or the
|
||||
/// official launcher's default.
|
||||
pub fn minecraft_dir(requested: Option<PathBuf>) -> Result<PathBuf, String> {
|
||||
requested
|
||||
.or(Settings::load().minecraft_dir)
|
||||
.or_else(default_minecraft_dir)
|
||||
.ok_or_else(|| "No Minecraft folder found. Pass the official launcher's game folder.".into())
|
||||
}
|
||||
|
||||
/// The server folder: the one given, the one chosen in the launcher, or `server/` in the data folder.
|
||||
pub fn server_dir(requested: Option<PathBuf>) -> PathBuf {
|
||||
requested.or(Settings::load().server_dir).unwrap_or_else(|| data_dir().join("server"))
|
||||
}
|
||||
|
||||
fn need_prepared(tag: &str) -> Result<(), String> {
|
||||
if is_prepared(tag) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("{tag} is not prepared yet. Prepare it first (it needs your own Minecraft {}).", game_version(tag)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The client's command, once its resources are prepared.
|
||||
pub fn client(tag: &str) -> Result<Command, String> {
|
||||
need_prepared(tag)?;
|
||||
Ok(client_command(tag))
|
||||
}
|
||||
|
||||
/// The dedicated server's command in `folder`, once prepared and the EULA is agreed to.
|
||||
pub fn server(tag: &str, folder: &Path, accept_eula: bool) -> Result<Command, String> {
|
||||
need_prepared(tag)?;
|
||||
if accept_eula {
|
||||
agree_eula(folder)?;
|
||||
}
|
||||
if !eula_agreed(folder) {
|
||||
return Err("Running a server needs your agreement to the Minecraft EULA (https://aka.ms/MinecraftEULA). Accept it to continue.".into());
|
||||
}
|
||||
fs::create_dir_all(folder).map_err(|e| e.to_string())?;
|
||||
Ok(server_command(tag, folder))
|
||||
}
|
||||
|
||||
/// One release's notes: the tag given, or the newest.
|
||||
pub fn release_notes(tag: Option<&str>) -> Result<Release, String> {
|
||||
let releases = releases()?;
|
||||
match tag {
|
||||
Some(tag) => releases.into_iter().find(|r| r.tag == tag).ok_or_else(|| format!("No Horizon release is tagged {tag}.")),
|
||||
None => releases.into_iter().next().ok_or_else(|| "No release is published yet.".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A process whose output is kept: the last `LOG_KEEP` lines, and its result once it ends.
|
||||
pub struct Logged {
|
||||
pub running: Running,
|
||||
pub log: Arc<Mutex<std::collections::VecDeque<String>>>,
|
||||
pub exit: Arc<Mutex<Option<Result<(), String>>>>,
|
||||
}
|
||||
|
||||
pub const LOG_KEEP: usize = 2000;
|
||||
|
||||
impl Logged {
|
||||
pub fn start(job: Job, cmd: Command) -> Result<Self, String> {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let running = spawn(job, cmd, tx)?;
|
||||
let log = Arc::new(Mutex::new(std::collections::VecDeque::new()));
|
||||
let exit = Arc::new(Mutex::new(None));
|
||||
let (l, e) = (log.clone(), exit.clone());
|
||||
std::thread::spawn(move || {
|
||||
for msg in rx {
|
||||
match msg {
|
||||
Msg::Line(_, line) => {
|
||||
let mut log = l.lock().unwrap();
|
||||
log.push_back(line);
|
||||
if log.len() > LOG_KEEP {
|
||||
log.pop_front();
|
||||
}
|
||||
}
|
||||
Msg::Exit(_, result) => *e.lock().unwrap() = Some(result),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(Self { running, log, exit })
|
||||
}
|
||||
|
||||
pub fn finished(&self) -> Option<Result<(), String>> {
|
||||
self.exit.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
pub fn tail(&self, lines: usize) -> Vec<String> {
|
||||
let log = self.log.lock().unwrap();
|
||||
log.iter().skip(log.len().saturating_sub(lines)).cloned().collect()
|
||||
}
|
||||
|
||||
pub fn wait(&self) -> Result<(), String> {
|
||||
loop {
|
||||
if let Some(result) = self.finished() {
|
||||
return result;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks a server to stop, and kills it if it has not after `grace`.
|
||||
pub fn stop(&mut self, grace: std::time::Duration) {
|
||||
self.running.send("stop");
|
||||
let start = std::time::Instant::now();
|
||||
while self.finished().is_none() && start.elapsed() < grace {
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
if self.finished().is_none() {
|
||||
self.running.kill();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ----- Updates -----------------------------------------------------------------------------------
|
||||
|
||||
/// What a check found: a Horizon build newer than every installed one, and a newer launcher.
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
//! `horizon-launcher <subcommand>`: the same steps as the window, from a terminal. Every
|
||||
//! command goes through `backend`; this file only parses arguments and prints.
|
||||
use clap::{Parser, Subcommand};
|
||||
use horizon_launcher::backend::{self, Release};
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "horizon-launcher", version, about = "Installs, prepares and starts Horizon. Without a subcommand, opens the window.")]
|
||||
struct Cli {
|
||||
/// Print JSON instead of text, where a command has something to report
|
||||
#[arg(long, global = true)]
|
||||
json: bool,
|
||||
#[command(subcommand)]
|
||||
command: Option<Cmd>,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Cmd {
|
||||
/// List Horizon releases, or the installed versions
|
||||
Versions {
|
||||
/// Only the versions installed here (no network)
|
||||
#[arg(long)]
|
||||
installed: bool,
|
||||
},
|
||||
/// Download and install a release (a tag such as v2026.10.13, or "latest")
|
||||
Install { tag: String },
|
||||
/// Remove an installed version
|
||||
Remove { tag: String },
|
||||
/// Prepare a version's resources from your own Minecraft install
|
||||
Prepare {
|
||||
/// The official launcher's game folder (default: the one the launcher uses)
|
||||
#[arg(long)]
|
||||
minecraft: Option<PathBuf>,
|
||||
/// The installed version (default: the selected one)
|
||||
#[arg(long)]
|
||||
version: Option<String>,
|
||||
},
|
||||
/// Start the client
|
||||
Play {
|
||||
#[arg(long)]
|
||||
version: Option<String>,
|
||||
},
|
||||
/// Run a dedicated server here; type commands into its console
|
||||
Server {
|
||||
/// The server's folder (default: the one the launcher uses)
|
||||
#[arg(long)]
|
||||
dir: Option<PathBuf>,
|
||||
#[arg(long)]
|
||||
version: Option<String>,
|
||||
/// Agree to the Minecraft EULA (https://aka.ms/MinecraftEULA)
|
||||
#[arg(long)]
|
||||
accept_eula: bool,
|
||||
},
|
||||
/// Show a release's patch notes (default: the newest)
|
||||
Notes { tag: Option<String> },
|
||||
/// Show the roadmap
|
||||
Next,
|
||||
/// Look for a newer Horizon release and launcher, and install them
|
||||
Update {
|
||||
/// Only report what is available
|
||||
#[arg(long)]
|
||||
check: bool,
|
||||
},
|
||||
/// Serve the Model Context Protocol on stdin and stdout, for AI agents
|
||||
Mcp,
|
||||
}
|
||||
|
||||
/// Runs a subcommand and returns the exit code, or None when the window should open.
|
||||
pub fn run() -> Option<i32> {
|
||||
let cli = Cli::parse();
|
||||
let command = cli.command?;
|
||||
let result = match command {
|
||||
Cmd::Mcp => crate::mcp::serve(),
|
||||
command => execute(command, cli.json),
|
||||
};
|
||||
Some(match result {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
1
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn progress(label: String) -> impl Fn(f32) {
|
||||
move |p| {
|
||||
eprint!("\r{label} {:>3.0}%", p * 100.);
|
||||
let _ = std::io::stderr().flush();
|
||||
if p >= 1.0 {
|
||||
eprintln!();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn json(value: serde_json::Value) {
|
||||
println!("{}", serde_json::to_string_pretty(&value).unwrap());
|
||||
}
|
||||
|
||||
/// Runs a game process in this terminal and reports how it ended.
|
||||
fn attached(mut cmd: Command) -> Result<(), String> {
|
||||
let status = cmd.status().map_err(|e| format!("Could not start {:?}: {e}", cmd.get_program()))?;
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("Exited with {status}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn release_json(r: &Release) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"tag": r.tag, "name": r.name, "date": r.date,
|
||||
"available_here": r.asset.is_some(), "installed": backend::installed().contains(&r.tag),
|
||||
})
|
||||
}
|
||||
|
||||
fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
|
||||
match command {
|
||||
Cmd::Versions { installed: true } => {
|
||||
let installed = backend::installed();
|
||||
let selected = backend::resolve_version(None).ok();
|
||||
if as_json {
|
||||
json(serde_json::json!({ "installed": installed, "selected": selected }));
|
||||
} else if installed.is_empty() {
|
||||
println!("No version is installed.");
|
||||
}
|
||||
for tag in installed.iter().filter(|_| !as_json) {
|
||||
let mark = if selected.as_ref() == Some(tag) { "*" } else { " " };
|
||||
let state = if backend::is_prepared(tag) { "prepared" } else { "not prepared" };
|
||||
println!("{mark} {tag} {state}");
|
||||
}
|
||||
}
|
||||
Cmd::Versions { installed: false } => {
|
||||
let releases = backend::releases()?;
|
||||
if as_json {
|
||||
json(releases.iter().map(release_json).collect());
|
||||
return Ok(());
|
||||
}
|
||||
let installed = backend::installed();
|
||||
for r in &releases {
|
||||
let state = match (installed.contains(&r.tag), r.asset.is_some()) {
|
||||
(true, _) => "installed",
|
||||
(false, true) => "",
|
||||
(false, false) => "no build for this platform",
|
||||
};
|
||||
println!("{:<14} {} {}", r.tag, r.date, state);
|
||||
}
|
||||
}
|
||||
Cmd::Install { tag } => {
|
||||
let label = format!("Installing {tag}");
|
||||
let tag = backend::install_tag(&tag, false, progress(label))?;
|
||||
if as_json {
|
||||
json(serde_json::json!({ "installed": tag }));
|
||||
} else {
|
||||
println!("Installed {tag}. Prepare it next: horizon-launcher prepare --version {tag}");
|
||||
}
|
||||
}
|
||||
Cmd::Remove { tag } => {
|
||||
backend::remove_version(&tag)?;
|
||||
println!("Removed {tag}.");
|
||||
}
|
||||
Cmd::Prepare { minecraft, version } => {
|
||||
let tag = backend::resolve_version(version.as_deref())?;
|
||||
let minecraft = backend::minecraft_dir(minecraft)?;
|
||||
let cmd = backend::prepare_command(&tag, &minecraft, &|line| eprintln!("{line}"))?;
|
||||
attached(cmd)?;
|
||||
println!("{tag} is prepared.");
|
||||
}
|
||||
Cmd::Play { version } => attached(backend::client(&backend::resolve_version(version.as_deref())?)?)?,
|
||||
Cmd::Server { dir, version, accept_eula } => {
|
||||
let tag = backend::resolve_version(version.as_deref())?;
|
||||
let dir = backend::server_dir(dir);
|
||||
// The server inherits this terminal, so typed lines reach its console.
|
||||
attached(backend::server(&tag, &dir, accept_eula)?)?
|
||||
}
|
||||
Cmd::Notes { tag } => {
|
||||
let r = backend::release_notes(tag.as_deref())?;
|
||||
if as_json {
|
||||
json(serde_json::json!({ "tag": r.tag, "name": r.name, "date": r.date, "notes": r.body }));
|
||||
} else {
|
||||
let title = if r.name.is_empty() { &r.tag } else { &r.name };
|
||||
println!("{title}\n{} {}\n\n{}", r.tag, r.date, backend::markdown_to_text(&r.body));
|
||||
}
|
||||
}
|
||||
Cmd::Next => {
|
||||
let roadmap = backend::roadmap()?;
|
||||
if as_json {
|
||||
json(serde_json::json!({ "roadmap": roadmap }));
|
||||
} else {
|
||||
print!("{}", backend::markdown_to_text(&roadmap));
|
||||
}
|
||||
}
|
||||
Cmd::Update { check } => update(check, as_json)?,
|
||||
Cmd::Mcp => unreachable!(),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn update(check: bool, as_json: bool) -> Result<(), String> {
|
||||
let updates = backend::check_updates()?;
|
||||
if as_json && check {
|
||||
json(serde_json::json!({
|
||||
"horizon": updates.horizon.as_ref().map(|r| &r.tag),
|
||||
"launcher": updates.launcher.as_ref().and_then(|r| backend::launcher_version(&r.tag)),
|
||||
"launcher_current": backend::VERSION,
|
||||
}));
|
||||
return Ok(());
|
||||
}
|
||||
match &updates.horizon {
|
||||
None => println!("Horizon: up to date."),
|
||||
Some(r) if check => println!("Horizon: {} is available.", r.tag),
|
||||
Some(r) => {
|
||||
let tag = backend::install_tag(&r.tag, true, progress(format!("Installing {}", r.tag)))?;
|
||||
println!("Horizon: installed {tag}.");
|
||||
}
|
||||
}
|
||||
match &updates.launcher {
|
||||
None => println!("Launcher: {} is up to date.", backend::VERSION),
|
||||
Some(r) => {
|
||||
let version = backend::launcher_version(&r.tag).unwrap_or_default();
|
||||
if check {
|
||||
println!("Launcher: {version} is available (this is {}).", backend::VERSION);
|
||||
} else if !backend::self_update_allowed() {
|
||||
println!("Launcher: {version} is available; this build does not replace itself.");
|
||||
} else {
|
||||
backend::self_update(r, progress(format!("Updating the launcher to {version}")))?;
|
||||
println!("Launcher: updated to {version}; the next start uses it.");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
//! Horizon launcher: installs Horizon builds, prepares them from the player's own Minecraft,
|
||||
//! and starts the client or a dedicated server.
|
||||
|
||||
mod cli;
|
||||
mod markdown;
|
||||
mod mcp;
|
||||
mod theme;
|
||||
|
||||
use horizon_launcher::backend::{self, Job, Msg, Release, Running, Settings, Updates};
|
||||
@@ -359,15 +361,12 @@ impl Launcher {
|
||||
}
|
||||
|
||||
fn remove(&mut self, tag: &str) {
|
||||
if let Err(e) = backend::remove(tag) {
|
||||
if let Err(e) = backend::remove_version(tag) {
|
||||
self.install_error = Some((tag.to_string(), e));
|
||||
}
|
||||
self.confirm_remove = None;
|
||||
self.installed = backend::installed();
|
||||
if self.settings.selected.as_deref() == Some(tag) {
|
||||
self.settings.selected = self.installed.first().cloned();
|
||||
}
|
||||
self.settings.save();
|
||||
self.settings.selected = Settings::load().selected.or_else(|| self.installed.first().cloned());
|
||||
}
|
||||
|
||||
fn prepare(&mut self) {
|
||||
@@ -1602,6 +1601,10 @@ impl Render for Launcher {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
backend::exe_path();
|
||||
if let Some(code) = cli::run() {
|
||||
std::process::exit(code);
|
||||
}
|
||||
Application::new().run(|cx: &mut App| {
|
||||
cx.text_system()
|
||||
.add_fonts(vec![
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
//! `horizon-launcher mcp`: the Model Context Protocol over stdin and stdout (JSON-RPC 2.0, one
|
||||
//! message per line), so AI agents can install, prepare and run Horizon. Every tool goes through
|
||||
//! `backend`. A server started here lives as long as the session.
|
||||
use horizon_launcher::backend::{self, Job, Logged};
|
||||
use serde_json::{json, Value};
|
||||
use std::io::{BufRead, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
const PROTOCOL: &str = "2025-06-18";
|
||||
|
||||
struct Session {
|
||||
server: Option<Logged>,
|
||||
client: Option<Logged>,
|
||||
}
|
||||
|
||||
fn tools() -> Value {
|
||||
let version = json!({ "type": "string", "description": "An installed version tag such as v2026.10.13. Default: the selected version." });
|
||||
let none = json!({ "type": "object", "properties": {} });
|
||||
json!([
|
||||
{ "name": "list_versions", "description": "List Horizon releases on GitHub (newest first) and the versions installed here, with which is selected and which are prepared.",
|
||||
"inputSchema": { "type": "object", "properties": { "installed_only": { "type": "boolean", "description": "Skip GitHub and list only installed versions." } } } },
|
||||
{ "name": "install_version", "description": "Download and install a Horizon release for this platform. Takes a minute or two.",
|
||||
"inputSchema": { "type": "object", "properties": { "tag": { "type": "string", "description": "A release tag such as v2026.10.13, or \"latest\"." } }, "required": ["tag"] } },
|
||||
{ "name": "remove_version", "description": "Remove an installed Horizon version and its prepared resources.",
|
||||
"inputSchema": { "type": "object", "properties": { "tag": { "type": "string" } }, "required": ["tag"] } },
|
||||
{ "name": "prepare_resources", "description": "Prepare a version's resources from the player's own Minecraft install (needs Minecraft 26.3 played once in the official launcher, Java 25 and Python 3.10+). Can take several minutes; returns the end of the log.",
|
||||
"inputSchema": { "type": "object", "properties": { "version": version, "minecraft_dir": { "type": "string", "description": "The official launcher's game folder. Default: the launcher's setting, else the platform default." } } } },
|
||||
{ "name": "launch_client", "description": "Start the Horizon client (a game window on the player's screen). Returns once it has started.",
|
||||
"inputSchema": { "type": "object", "properties": { "version": version } } },
|
||||
{ "name": "start_server", "description": "Start a Horizon dedicated server. It runs until stop_server or the end of this MCP session. Requires agreeing to the Minecraft EULA.",
|
||||
"inputSchema": { "type": "object", "properties": { "version": version, "dir": { "type": "string", "description": "The server's folder. Default: the launcher's server folder." }, "accept_eula": { "type": "boolean", "description": "Agree to the Minecraft EULA (https://aka.ms/MinecraftEULA) on the player's behalf. Only with their consent." } } } },
|
||||
{ "name": "server_command", "description": "Send a console command to the running server (for example \"list\" or \"say hello\"), and return the lines it printed in reply.",
|
||||
"inputSchema": { "type": "object", "properties": { "command": { "type": "string" } }, "required": ["command"] } },
|
||||
{ "name": "server_log", "description": "The most recent lines of the server's console.",
|
||||
"inputSchema": { "type": "object", "properties": { "lines": { "type": "integer", "minimum": 1, "maximum": 2000, "description": "How many lines (default 50)." } } } },
|
||||
{ "name": "stop_server", "description": "Stop the running server cleanly (it saves the world), killing it if it does not stop within 30 seconds.", "inputSchema": none },
|
||||
{ "name": "patch_notes", "description": "A release's patch notes as markdown.",
|
||||
"inputSchema": { "type": "object", "properties": { "tag": { "type": "string", "description": "Default: the newest release." } } } },
|
||||
{ "name": "roadmap", "description": "What's planned next for Horizon, from the README's roadmap.", "inputSchema": none },
|
||||
{ "name": "check_updates", "description": "Check GitHub for a Horizon release newer than every installed version, and for a newer launcher.", "inputSchema": none },
|
||||
])
|
||||
}
|
||||
|
||||
fn arg_str<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
|
||||
args.get(key).and_then(Value::as_str).filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
impl Session {
|
||||
fn call(&mut self, name: &str, args: &Value) -> Result<String, String> {
|
||||
match name {
|
||||
"list_versions" => {
|
||||
let installed = backend::installed();
|
||||
let mut out = json!({
|
||||
"installed": installed.iter().map(|t| json!({ "tag": t, "prepared": backend::is_prepared(t) })).collect::<Vec<_>>(),
|
||||
"selected": backend::resolve_version(None).ok(),
|
||||
});
|
||||
if !args.get("installed_only").and_then(Value::as_bool).unwrap_or(false) {
|
||||
out["releases"] = backend::releases()?
|
||||
.iter()
|
||||
.map(|r| json!({ "tag": r.tag, "name": r.name, "date": r.date, "available_here": r.asset.is_some() }))
|
||||
.collect();
|
||||
}
|
||||
Ok(serde_json::to_string_pretty(&out).unwrap())
|
||||
}
|
||||
"install_version" => {
|
||||
let tag = backend::install_tag(arg_str(args, "tag").ok_or("tag is required")?, false, |_| {})?;
|
||||
Ok(format!("Installed {tag}. It is now the selected version; prepare it before playing."))
|
||||
}
|
||||
"remove_version" => {
|
||||
let tag = arg_str(args, "tag").ok_or("tag is required")?;
|
||||
backend::remove_version(tag)?;
|
||||
Ok(format!("Removed {tag}."))
|
||||
}
|
||||
"prepare_resources" => {
|
||||
let tag = backend::resolve_version(arg_str(args, "version"))?;
|
||||
let minecraft = backend::minecraft_dir(arg_str(args, "minecraft_dir").map(PathBuf::from))?;
|
||||
let cmd = backend::prepare_command(&tag, &minecraft, &|_| {})?;
|
||||
let run = Logged::start(Job::Prepare, cmd)?;
|
||||
let result = run.wait();
|
||||
let tail = run.tail(20).join("\n");
|
||||
result.map(|_| format!("{tag} is prepared.\n{tail}")).map_err(|e| format!("{e}\n{tail}"))
|
||||
}
|
||||
"launch_client" => {
|
||||
if self.client.as_ref().is_some_and(|c| c.finished().is_none()) {
|
||||
return Err("The client is already running.".into());
|
||||
}
|
||||
let tag = backend::resolve_version(arg_str(args, "version"))?;
|
||||
let client = Logged::start(Job::Client, backend::client(&tag)?)?;
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
if let Some(Err(e)) = client.finished() {
|
||||
return Err(format!("{e}\n{}", client.tail(20).join("\n")));
|
||||
}
|
||||
self.client = Some(client);
|
||||
Ok(format!("Started the {tag} client."))
|
||||
}
|
||||
"start_server" => {
|
||||
if self.server.as_ref().is_some_and(|s| s.finished().is_none()) {
|
||||
return Err("A server is already running. Stop it first.".into());
|
||||
}
|
||||
let tag = backend::resolve_version(arg_str(args, "version"))?;
|
||||
let dir = backend::server_dir(arg_str(args, "dir").map(PathBuf::from));
|
||||
let accept = args.get("accept_eula").and_then(Value::as_bool).unwrap_or(false);
|
||||
let server = Logged::start(Job::Server, backend::server(&tag, &dir, accept)?)?;
|
||||
std::thread::sleep(Duration::from_secs(3));
|
||||
let tail = server.tail(15).join("\n");
|
||||
if let Some(result) = server.finished() {
|
||||
return Err(format!("The server stopped: {}\n{tail}", result.err().unwrap_or_default()));
|
||||
}
|
||||
self.server = Some(server);
|
||||
Ok(format!("Started the {tag} server in {}.\n{tail}", dir.display()))
|
||||
}
|
||||
"server_command" => {
|
||||
let server = self.running_server()?;
|
||||
let before = server.log.lock().unwrap().len();
|
||||
let command = arg_str(args, "command").ok_or("command is required")?;
|
||||
server.running.send(command.trim_start_matches('/'));
|
||||
std::thread::sleep(Duration::from_millis(700));
|
||||
let log = server.log.lock().unwrap();
|
||||
let reply: Vec<_> = log.iter().skip(before.min(log.len())).cloned().collect();
|
||||
Ok(if reply.is_empty() { "(no output yet)".into() } else { reply.join("\n") })
|
||||
}
|
||||
"server_log" => {
|
||||
let server = self.server.as_ref().ok_or("No server was started in this session.")?;
|
||||
let lines = args.get("lines").and_then(Value::as_u64).unwrap_or(50) as usize;
|
||||
let state = if server.finished().is_some() { "stopped" } else { "running" };
|
||||
Ok(format!("[server {state}]\n{}", server.tail(lines).join("\n")))
|
||||
}
|
||||
"stop_server" => {
|
||||
let mut server = self.server.take().ok_or("No server was started in this session.")?;
|
||||
server.stop(Duration::from_secs(30));
|
||||
Ok(format!("The server stopped.\n{}", server.tail(5).join("\n")))
|
||||
}
|
||||
"patch_notes" => {
|
||||
let r = backend::release_notes(arg_str(args, "tag"))?;
|
||||
Ok(format!("# {} ({}, {})\n\n{}", if r.name.is_empty() { &r.tag } else { &r.name }, r.tag, r.date, r.body))
|
||||
}
|
||||
"roadmap" => backend::roadmap(),
|
||||
"check_updates" => {
|
||||
let u = backend::check_updates()?;
|
||||
Ok(serde_json::to_string_pretty(&json!({
|
||||
"horizon_update": u.horizon.as_ref().map(|r| &r.tag),
|
||||
"installed": backend::installed(),
|
||||
"launcher_update": u.launcher.as_ref().and_then(|r| backend::launcher_version(&r.tag)),
|
||||
"launcher_version": backend::VERSION,
|
||||
}))
|
||||
.unwrap())
|
||||
}
|
||||
_ => Err(format!("Unknown tool {name}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn running_server(&mut self) -> Result<&mut Logged, String> {
|
||||
match &mut self.server {
|
||||
Some(s) if s.finished().is_none() => Ok(s),
|
||||
_ => Err("No server is running. Start one with start_server.".into()),
|
||||
}
|
||||
}
|
||||
|
||||
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-launcher", "version": backend::VERSION },
|
||||
"instructions": "Manage Horizon, a Rust reimplementation of Minecraft Java Edition: install versions, prepare them from the player's own Minecraft, start the client or a dedicated server.",
|
||||
})),
|
||||
"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().as_array().unwrap().iter().any(|t| t["name"] == name) {
|
||||
return Err((-32602, format!("Unknown tool {name}")));
|
||||
}
|
||||
let args = params.get("arguments").cloned().unwrap_or(json!({}));
|
||||
let (text, error) = match self.call(name, &args) {
|
||||
Ok(text) => (text, false),
|
||||
Err(e) => (e, true),
|
||||
};
|
||||
Ok(json!({ "content": [{ "type": "text", "text": text }], "isError": error }))
|
||||
}
|
||||
_ => Err((-32601, format!("Method not found: {method}"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn serve() -> Result<(), String> {
|
||||
let mut session = Session { server: None, client: None };
|
||||
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())?;
|
||||
}
|
||||
}
|
||||
// The session is over: the server it started goes with it.
|
||||
if let Some(mut server) = session.server.take() {
|
||||
server.stop(Duration::from_secs(30));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user