Merge pull request #1342 from ludovic111/feat/no-ai-switch

🤖 Agent: merged after verify passed and the agent-control-2 integration of all six PRs on the Mac mini. agent_control_e2e passes in CLI and MCP (one known survival flake), launcher_mcp_e2e passes, No AI is refused, and the options, screen_layout, menu_click and world_options parity harnesses pass. Ludovic asked for this on 2026-10-23.
This commit is contained in:
Ludovic Marie
2026-10-23 03:37:59 +02:00
committed by GitHub
11 changed files with 296 additions and 12 deletions
@@ -366,8 +366,9 @@ pub fn overview() -> String {
}
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\
success, 1 when the game replied with an error, 2 for a usage error, 3 when the\n\
game cannot be reached or started and 4 while No AI is on (the launcher's settings).\n\
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\
@@ -20,6 +20,8 @@ use serde_json::{Value, json};
const GAME_ERROR: u8 = 1;
const USAGE: u8 = 2;
const UNREACHABLE: u8 = 3;
/// No AI is on (`horizon_core::no_ai`): agent control is off.
const DENIED: u8 = 4;
/// A failure, with the exit status it maps to.
#[derive(Debug)]
@@ -34,6 +36,13 @@ impl Failure {
status: USAGE,
}
}
/// No AI is on in the game's home.
fn denied() -> Self {
Self {
reply: json!({ "error": horizon_core::no_ai::REFUSAL, "kind": "denied" }),
status: DENIED,
}
}
fn unreachable(message: impl Into<String>) -> Self {
Self {
reply: json!({ "error": message.into(), "kind": "connection" }),
@@ -98,6 +107,8 @@ impl Client {
pub struct Session {
pub socket: PathBuf,
pub timeout: Option<Duration>,
/// The game's home, where No AI is read (`horizon_core::no_ai`).
pub home: PathBuf,
client: Option<Client>,
}
@@ -106,9 +117,14 @@ impl Session {
Self {
socket,
timeout,
home: horizon_client::logging::game_home(),
client: None,
}
}
/// A failure while No AI is on: every command refuses (help aside).
pub fn allowed(&self) -> Result<(), Failure> {
horizon_core::no_ai::check(&self.home).map_err(|_| Failure::denied())
}
fn client(&mut self) -> Result<&mut Client, Failure> {
if self.client.is_none() {
self.client = Some(Client::connect(&self.socket, self.timeout)?);
@@ -137,6 +153,7 @@ impl Session {
let Some(name) = words.first().map(String::as_str) else {
return Err(Failure::usage("no command; try horizon-ctl help"));
};
self.allowed()?;
if words.iter().skip(1).any(|w| w == "--help" || w == "-h") {
return Err(Failure::usage(
"use horizon-ctl COMMAND --help outside scripts",
@@ -183,7 +200,7 @@ impl Session {
thread::sleep(Duration::from_secs_f64(seconds.max(0.0)));
self.game(&format!("key {key} up"))
}
"logs" => logs(&horizon_client::logging::game_home(), &words[1..]),
"logs" => logs(&self.home, &words[1..]),
"wait-ready" => {
let limit = if words.len() > 1 {
number(1, "SECONDS")?
@@ -451,6 +468,10 @@ fn main() -> ExitCode {
}
}
}
Some("mcp") if session.allowed().is_err() => {
eprintln!("horizon-ctl mcp: {}", horizon_core::no_ai::REFUSAL);
DENIED
}
Some("mcp") => match mcp::serve(&mut session) {
Ok(()) => 0,
Err(e) => {
@@ -581,6 +602,27 @@ mod tests {
assert_eq!(f.status, USAGE);
}
#[test]
fn no_ai_refuses_every_command() {
let home = std::env::temp_dir().join(format!("horizon-ctl-no-ai-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&home);
let mut s = Session::new(std::env::temp_dir().join("horizon-ctl-nobody.sock"), None);
s.home = home.clone();
assert_eq!(
s.run(&["state".to_owned()]).unwrap_err().status,
UNREACHABLE
);
horizon_core::no_ai::set(&home, true).unwrap();
for words in [vec!["state"], vec!["logs"], vec!["launch", "--world", "A"]] {
let words: Vec<String> = words.into_iter().map(str::to_owned).collect();
let f = s.run(&words).unwrap_err();
assert_eq!(f.status, DENIED, "{words:?}");
assert_eq!(f.reply["kind"], "denied");
assert_eq!(f.reply["error"], horizon_core::no_ai::REFUSAL);
}
let _ = std::fs::remove_dir_all(&home);
}
#[test]
fn screenshot_paths_become_absolute() {
let mut words = vec!["screenshot".to_owned(), "a.png".to_owned()];
+7 -1
View File
@@ -107,6 +107,8 @@ pub struct Extras {
pub sort: bool,
/// A vanilla key name: sorts the part under the cursor.
pub sort_key: String,
/// No AI: every AI feature hidden and off (`horizon_core::no_ai`; the launcher writes it too).
pub no_ai: bool,
}
impl Default for Extras {
fn default() -> Self {
@@ -135,6 +137,7 @@ impl Default for Extras {
mouse_tweaks_wheel: true,
sort: false,
sort_key: "key.keyboard.unknown".into(),
no_ai: false,
}
}
}
@@ -198,6 +201,7 @@ impl Extras {
"mouseTweaksWheel" => e.mouse_tweaks_wheel = flag(e.mouse_tweaks_wheel),
"sort" => e.sort = flag(e.sort),
"sortKey" if value.starts_with("key.") => e.sort_key = value.to_owned(),
horizon_core::no_ai::KEY => e.no_ai = flag(e.no_ai),
_ => {}
}
}
@@ -205,7 +209,7 @@ impl Extras {
}
pub fn serialize(&self) -> String {
format!(
"fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n",
"fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n{}:{}\n",
bool_text(self.fullbright),
bool_text(self.dynamic_lights),
bool_text(self.zoom),
@@ -234,6 +238,8 @@ impl Extras {
bool_text(self.mouse_tweaks_wheel),
bool_text(self.sort),
self.sort_key,
horizon_core::no_ai::KEY,
bool_text(self.no_ai),
)
}
/// Binds the extra key `name` (`ZOOM_KEY`, `SORT_KEY`); false for
+7 -1
View File
@@ -12443,7 +12443,13 @@ fn start_game<'a>(
game.mods.dev = game.options.dev_mods.clone();
game.start_mods();
}
if let Some(path) = &game.options.control {
if game.options.control.is_some() && game.settings.extras.no_ai {
// No AI turns agent control off: the socket is never opened.
log::warn!(
"Horizon: control socket not opened: {}",
horizon_core::no_ai::REFUSAL
);
} else if let Some(path) = &game.options.control {
let server = horizon_client::control::Server::start(path)
.map_err(|e| format!("control socket {}: {e}", path.display()))?;
log::info!("Horizon: control socket {}", server.path().display());
+1
View File
@@ -9,6 +9,7 @@ pub mod carving;
pub mod density;
pub mod geometry;
pub mod jmath;
pub mod no_ai;
pub mod noise;
pub mod paletted;
pub mod position;
+97
View File
@@ -0,0 +1,97 @@
//! The "No AI" switch: one setting that hides and turns off every AI feature of Horizon (the
//! companion, agent control through the control socket, `horizon-ctl`, its MCP server and the
//! launcher's). The launcher and the game both read and write it here, so they always agree.
//!
//! It is the `noAi` line of the game's `horizon-extras.txt`, in the game's home (the folder
//! with `options.txt`). Missing means off: AI features are available. See docs/agent-control.md.
use std::{fs, io, path::Path};
/// The game's extras file, beside `options.txt`.
pub const FILE: &str = "horizon-extras.txt";
/// The key No AI is kept under there.
pub const KEY: &str = "noAi";
/// The one line every AI surface answers with while No AI is on.
pub const REFUSAL: &str = "AI features are off: turn off No AI in the launcher's settings";
/// Whether `text` (an extras file) says No AI.
pub fn parse(text: &str) -> bool {
text.lines().any(|line| {
line.split_once(':')
.is_some_and(|(k, v)| k.trim() == KEY && v.trim() == "true")
})
}
/// Whether No AI is on for the game whose home is `home`.
pub fn is_on(home: &Path) -> bool {
fs::read_to_string(home.join(FILE)).is_ok_and(|text| parse(&text))
}
/// `text` with its `noAi` line set to `on`, every other line kept as it was.
pub fn with(text: &str, on: bool) -> String {
let mut out: String = text
.lines()
.filter(|line| line.split_once(':').is_none_or(|(k, _)| k.trim() != KEY))
.flat_map(|line| [line, "\n"])
.collect();
out.push_str(&format!("{KEY}:{on}\n"));
out
}
/// Turns No AI on or off for the game in `home`, keeping the file's other settings. Turning it
/// off where there is no file writes nothing (off is the default).
pub fn set(home: &Path, on: bool) -> io::Result<()> {
let path = home.join(FILE);
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
if !on {
return Ok(());
}
String::new()
}
Err(e) => return Err(e),
};
fs::create_dir_all(home)?;
fs::write(path, with(&text, on))
}
/// `Err(REFUSAL)` while No AI is on in `home`.
pub fn check(home: &Path) -> Result<(), &'static str> {
if is_on(home) { Err(REFUSAL) } else { Ok(()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_and_writes_the_extras_line_keeping_the_others() {
assert!(!parse(""));
assert!(!parse("noAi:false\nzoom:true\n"));
assert!(parse("zoom:true\nnoAi: true\n"));
assert_eq!(
with("zoom:true\nnoAi:false\nfps:true", true),
"zoom:true\nfps:true\nnoAi:true\n"
);
assert_eq!(with("", false), "noAi:false\n");
}
#[test]
fn set_writes_only_when_needed() {
let home = std::env::temp_dir().join(format!("horizon-no-ai-{}", std::process::id()));
let _ = fs::remove_dir_all(&home);
set(&home, false).unwrap();
assert!(!home.join(FILE).exists(), "off needs no file");
assert!(check(&home).is_ok());
set(&home, true).unwrap();
assert!(is_on(&home));
assert_eq!(check(&home), Err(REFUSAL));
fs::write(home.join(FILE), "fps:true\nnoAi:true\n").unwrap();
set(&home, false).unwrap();
assert_eq!(
fs::read_to_string(home.join(FILE)).unwrap(),
"fps:true\nnoAi:false\n"
);
let _ = fs::remove_dir_all(&home);
}
}
+11
View File
@@ -1269,6 +1269,17 @@ pub fn game_home() -> PathBuf {
.join("horizon")
}
/// Whether No AI is on: every AI feature hidden and off (`horizon_core::no_ai`, kept in the
/// game's `horizon-extras.txt` so the game reads the same switch).
pub fn no_ai() -> bool {
horizon_core::no_ai::is_on(&game_home())
}
/// Turns No AI on or off for the launcher and the game.
pub fn set_no_ai(on: bool) -> Result<(), String> {
horizon_core::no_ai::set(&game_home(), on).map_err(|e| format!("Could not save No AI: {e}"))
}
// ----- Logs and crash reports ---------------------------------------------------------------------
/// The game's logs (`latest.log` and the day archives), as it writes them in its home.
+23 -1
View File
@@ -343,8 +343,16 @@ enum Cmd {
#[command(subcommand)]
action: Option<ServersCmd>,
},
/// Serve the Model Context Protocol on stdin and stdout, for AI agents
/// Serve the Model Context Protocol on stdin and stdout, for AI agents (refused while No AI
/// is on)
Mcp,
/// Show or set No AI: on hides and turns off every AI feature (the companion, agent control,
/// horizon-ctl and both MCP servers); off, the default, makes them available
NoAi {
/// Omit to show the current state
#[arg(value_parser = ["on", "off"])]
state: Option<String>,
},
/// Measure the launcher: starts (the first is the cold one), page switching, idle CPU and
/// memory, the release list fetch; writes a benchmark report to benchmarks/ in its data folder
Benchmark {
@@ -359,6 +367,7 @@ pub fn run() -> Option<i32> {
let cli = Cli::parse();
let command = cli.command?;
let result = match command {
Cmd::Mcp if backend::no_ai() => Err(horizon_core::no_ai::REFUSAL.into()),
Cmd::Mcp => crate::mcp::serve(),
command => execute(command, cli.json),
};
@@ -553,6 +562,19 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> {
}
}
}
Cmd::NoAi { state } => {
if let Some(state) = state {
backend::set_no_ai(state == "on")?;
}
let on = backend::no_ai();
if as_json {
json(serde_json::json!({ "no_ai": on }));
} else if on {
println!("No AI is on: every AI feature is hidden and off.");
} else {
println!("No AI is off: AI features are available.");
}
}
Cmd::UpdateChannel { channel } => {
let mut settings = backend::Settings::load();
if let Some(channel) = channel.as_deref().and_then(backend::UpdateChannel::parse) {
+4
View File
@@ -439,6 +439,10 @@ impl Session {
}
Ok(json!({ "tools": list }))
}
// No AI turned on during the session: nothing more runs.
"tools/call" if backend::no_ai() => {
Err((-32000, horizon_core::no_ai::REFUSAL.to_string()))
}
"tools/call" => {
let name = params
.get("name")
+67 -5
View File
@@ -11,7 +11,9 @@ states (wait-for) and reads the event log; the consume scenario eats and drinks
golden apple, milk, honey, chorus fruit) and checks their effects, remainders and teleport; the
pick scenario middle-clicks slots (AbstractContainerScreen's cloning): a full stack in creative, from
the hotbar and from an item tab, and nothing in survival; the suggestions scenario checks
slash-command Tab completion on single player's connected client after a fresh launch.
slash-command Tab completion on single player's connected client after a fresh launch; the no-ai
scenario turns No AI on in a scratch game home and checks that horizon-ctl, its MCP server and the
game's control socket all refuse.
python3 tools/agent_control_e2e.py # both modes
python3 tools/agent_control_e2e.py --mode mcp # one of them
@@ -571,13 +573,73 @@ SCENARIOS = {'survival': scenario, 'ui': ui_scenario, 'options': options_scenari
'consume': consume_scenario, 'pick': pick_scenario, 'suggestions': suggestions_scenario}
def run(mode, ctl, out, resources, which='survival'):
REFUSAL = "AI features are off: turn off No AI in the launcher's settings"
def scratch(mode, resources):
"""A scratch game home with the prepared resources, and the game's environment for it."""
work = Path(tempfile.mkdtemp(prefix=f'hzac-{mode}-'))
(work / '.local').mkdir()
(work / '.local/horizon-client').mkdir()
os.symlink(resources, work / '.local/horizon-client' / lab.VERSION)
# horizon-ctl reads No AI in the game home: this one, not the player's.
env = dict(game_env(os.environ.get('VSCREEN', 'agent-control')), HORIZON_HOME=str(work))
return work, env
def no_ai_check(mode, ctl, resources):
"""No AI on: horizon-ctl refuses (exit 4, kind denied), so does its MCP server, and the game
started with --control-socket never opens it."""
work, env = scratch(mode, resources)
socket = work / 'c.sock'
try:
(work / 'horizon-extras.txt').write_text('fps:true\nnoAi:true\n')
if mode == 'cli':
for words in (['state'], ['launch', '--world', 'NoAi'], ['logs']):
r = subprocess.run([str(ctl), '--socket', str(socket), *words], cwd=work, env=env,
capture_output=True, text=True, timeout=60)
reply = json.loads(r.stdout.strip().splitlines()[-1])
log(mode, words, reply)
assert r.returncode == 4 and reply == {'error': REFUSAL, 'kind': 'denied'}, (r.returncode, reply)
client = ctl.with_name('horizon-client')
args = [str(client), '--control-socket', str(socket), '--world', 'NoAi', '--world-frames', '30']
if sys.platform == 'darwin':
args.append('--offscreen')
r = subprocess.run(args, cwd=work, env=env, capture_output=True, text=True, timeout=600)
text = r.stdout + r.stderr + ''.join(
p.read_text(errors='replace') for p in (work / 'logs').glob('latest.log'))
assert r.returncode == 0, f'game exit {r.returncode}: {text[-2000:]}'
assert 'control socket not opened' in text and REFUSAL in text, text[-2000:]
assert not socket.exists(), 'the game opened its control socket under No AI'
else:
r = subprocess.run([str(ctl), '--socket', str(socket), 'mcp'], cwd=work, env=env, input='',
capture_output=True, text=True, timeout=60)
log(mode, ['mcp'], {'exit': r.returncode, 'stderr': r.stderr.strip()})
assert r.returncode == 4 and r.stderr.strip() == f'horizon-ctl mcp: {REFUSAL}', r
# Turned on during a session: the next call refuses.
(work / 'horizon-extras.txt').write_text('noAi:false\n')
m = Mcp(ctl, socket, work, env)
(work / 'horizon-extras.txt').write_text('noAi:true\n')
try:
m('state')
raise AssertionError('state ran under No AI')
except Failed as e:
assert REFUSAL in str(e) and 'denied' in str(e), e
m.close()
print(f'[{mode}] PASS: no-ai')
return True
except (Failed, AssertionError, json.JSONDecodeError, IndexError, subprocess.TimeoutExpired) as e:
print(f'[{mode}] FAIL: no-ai: {e!r}')
return False
finally:
shutil.rmtree(work, ignore_errors=True)
def run(mode, ctl, out, resources, which='survival'):
if which == 'no-ai':
return no_ai_check(mode, ctl, resources)
work, env = scratch(mode, resources)
socket = work / 'c.sock'
env = game_env(os.environ.get('VSCREEN', 'agent-control'))
driver = (Cli if mode == 'cli' else Mcp)(ctl, socket, work, env)
started = time.time()
try:
@@ -604,7 +666,7 @@ def run(mode, ctl, out, resources, which='survival'):
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--mode', choices=['cli', 'mcp', 'both'], default='both')
parser.add_argument('--scenario', choices=[*SCENARIOS, 'all'], default='all')
parser.add_argument('--scenario', choices=[*SCENARIOS, 'no-ai', 'all'], default='all')
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()
@@ -622,7 +684,7 @@ def main():
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
modes = ['cli', 'mcp'] if args.mode == 'both' else [args.mode]
scenarios = list(SCENARIOS) if args.scenario == 'all' else [args.scenario]
scenarios = [*SCENARIOS, 'no-ai'] if args.scenario == 'all' else [args.scenario]
results = {f'{m}/{s}': run(m, bins / 'horizon-ctl', out, resources, s) for m in modes for s in scenarios}
print(json.dumps(results))
sys.exit(0 if all(results.values()) else 1)
+33 -1
View File
@@ -5,7 +5,9 @@ A scratch launcher home gets one "installed" version made of this checkout's bui
(horizon-client and horizon-ctl) and the prepared resources in .local/horizon-client. An MCP
client then talks to `horizon-launcher mcp` alone: the game tools are listed, a call before the
game runs says to launch it, launch_client starts it under control, and game_wait_ready,
game_state, game_ui and game_screenshot play it until game_quit.
game_state, game_ui and game_screenshot play it until game_quit. Then No AI is turned on with
`horizon-launcher no-ai on`: `horizon-launcher mcp` refuses to start, and a session already running
refuses its next call.
python3 tools/launcher_mcp_e2e.py --bin-dir target/fast --launcher launcher/target/debug/horizon-launcher
@@ -96,6 +98,35 @@ def scenario(m, out):
return {'tools': len(tools)}
REFUSAL = "AI features are off: turn off No AI in the launcher's settings"
def no_ai_scenario(launcher, env, home):
run = lambda *a: subprocess.run([str(launcher), *a], env=env, input='', capture_output=True, text=True,
timeout=60)
assert json.loads(run('no-ai', '--json').stdout) == {'no_ai': False}
m = Mcp(launcher, env)
m.rpc('initialize', {'protocolVersion': '2025-06-18', 'capabilities': {},
'clientInfo': {'name': 'launcher_mcp_e2e', 'version': '1'}})
r = run('no-ai', 'on')
assert r.returncode == 0, r
assert 'noAi:true' in (home / 'horizon-extras.txt').read_text()
try:
m.call('links')
raise AssertionError('links ran under No AI')
except Failed as e:
assert REFUSAL in str(e), e
m.close()
r = run('mcp')
print(f'[launcher-mcp] mcp under No AI -> exit {r.returncode}: {r.stderr.strip()}')
assert r.returncode == 1 and r.stderr.strip() == f'error: {REFUSAL}', r
# What the launcher needs keeps working.
assert run('versions', '--installed', '--json').returncode == 0
assert run('no-ai', 'off').returncode == 0
assert json.loads(run('no-ai', '--json').stdout) == {'no_ai': False}
return {'no_ai': 'refused'}
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--bin-dir', required=True, help='horizon-client and horizon-ctl built from this checkout')
@@ -120,6 +151,7 @@ def main():
m = Mcp(Path(args.launcher).resolve(), env)
try:
summary = scenario(m, out)
summary.update(no_ai_scenario(Path(args.launcher).resolve(), env, work / 'home'))
print(f'[launcher-mcp] PASS: {summary}')
ok = True
except (Failed, AssertionError, KeyError, json.JSONDecodeError) as e: