Download tasks/t39-rct-onetile/environment/run-supervisor.py from refreshdotdev/Refresh-GUI-dataset: direct link, hf CLI and curl.
- Browser
- Download file 11.8 kB
-
https://huggingface.co/datasets/refreshdotdev/Refresh-GUI-dataset/resolve/main/tasks/t39-rct-onetile/environment/run-supervisor.py
- Command line
-
hf download hf://datasets/refreshdotdev/Refresh-GUI-dataset/tasks/t39-rct-onetile/environment/run-supervisor.py
-
curl -L -o run-supervisor.py https://huggingface.co/datasets/refreshdotdev/Refresh-GUI-dataset/resolve/main/tasks/t39-rct-onetile/environment/run-supervisor.py
11.8 kB
| """Own the engine for one run of the one-tile start. | |
| A run is three attempts. The score is whether the objective was settled and how | |
| much in-game time it took, and the in-game days of every attempt are added up -- | |
| so a restart is not free, it costs exactly the time it cost, and "time to | |
| completion" still means something. This process installs the trusted plugin (the | |
| scenario configuration concatenated ahead of the controller), plays the base | |
| plot, leaves a pristine read-only copy for each further attempt, and stops | |
| watching when the engine settles the objective, runs out of attempts, or stops | |
| running. The park is then left on screen for the agent and the verifier. | |
| A park that closes down does not end the run while attempts remain: the agent | |
| takes the next one by loading 2nd-try.park or 3rd-try.park from the game's own | |
| load dialog, which the controller sees as a fresh attempt and charges to the total. | |
| The agent has no shell, and the controller blocks the in-game actions that could | |
| re-date the park, re-grant land or cheat, so the only way to a new park is an | |
| attempt that has been counted. | |
| """ | |
| import json | |
| import os | |
| import shutil | |
| import signal | |
| import subprocess | |
| import sys | |
| import time | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| AUDIT = Path(os.environ["T39_AUDIT_DIR"]) | |
| STATE = Path("/logs/artifacts/run") | |
| HOME = Path(os.environ.get("HOME", "/home/rct2")) | |
| PROFILE = HOME/".config/OpenRCT2" | |
| BASE = Path("/opt/onetile/onetile-base.park") | |
| LIB = Path("/usr/local/lib/t39") | |
| # Attempts in one run. The number is the single source: it is compiled into the | |
| # plugin, it is how many pristine restart copies are laid down, and it is what | |
| # decides when a closed-down park ends the run. tests/grade.py declares the same | |
| # number and refuses a stream that disagrees. | |
| ATTEMPTS = 3 | |
| # Seconds a settled run stays untouched before the last evidence is collected, | |
| # so the outcome message and the final figures are on screen to be read. | |
| SETTLE_GRACE = 120 | |
| # How long a failed attempt is held open for the agent to take the next one. Long | |
| # enough to read the message and work the load dialog, short enough that an agent | |
| # that has given up is not paid to stare at a closed park. | |
| RESTART_GRACE = 300 | |
| # The controller reports every five seconds in real time, paused or not. A much | |
| # longer silence with a live engine means the park is no longer running (quit to | |
| # the title screen). | |
| HEARTBEAT_TIMEOUT = 180 | |
| # A run that never reports at all is a broken engine, not a park. | |
| STARTUP_TIMEOUT = 900 | |
| POLL = 2 | |
| def now(): | |
| return datetime.now(timezone.utc).isoformat() | |
| def restart_name(attempt): | |
| """The save file the agent loads to take `attempt`. | |
| Short on purpose: the game's load dialog truncates the name column at seven | |
| characters, so restart-attempt-2 and restart-attempt-3 both render as | |
| "restart-..." and the agent cannot tell which row is which. Ordinals fit, sort | |
| to the top of the list, and say what the file is for. controller.js builds the | |
| same name for the on-screen instructions. | |
| """ | |
| suffix = {2: "2nd", 3: "3rd"}.get(attempt, f"{attempt}th") | |
| return f"{suffix}-try.park" | |
| def mark(record): | |
| """Append a supervisor record to the same audit stream as the engine's.""" | |
| AUDIT.mkdir(parents=True, exist_ok=True) | |
| record["schema"] = 1 | |
| record["observed_at"] = now() | |
| with (AUDIT/"game.jsonl").open("a") as audit: | |
| audit.write(json.dumps(record)+"\n") | |
| def publish(status): | |
| """Record the run's state for collect.py and the verifier.""" | |
| STATE.mkdir(parents=True, exist_ok=True) | |
| temp = STATE/"current.tmp" | |
| temp.write_text(json.dumps({"status": status, "updated_at": now()}, indent=2)+"\n") | |
| temp.replace(STATE/"current.json") | |
| def target_guests(): | |
| """The guest target this run is scored on. | |
| Two tasks share this environment -- a calibrated target and the video's 1,000 | |
| -- and a plugin cannot read the environment, so the number is compiled into | |
| the plugin here. A missing or unreadable value is a broken task definition, | |
| not something to guess a default for. | |
| """ | |
| raw = os.environ.get("T39_TARGET_GUESTS", "") | |
| try: | |
| guests = int(raw) | |
| except ValueError: | |
| raise SystemExit(f"T39_TARGET_GUESTS must be an integer, got {raw!r}") | |
| if guests < 1: | |
| raise SystemExit(f"T39_TARGET_GUESTS must be positive, got {guests}") | |
| return guests | |
| def install_plugin(guests): | |
| """One installed plugin: the target, the allowance, the configuration, then | |
| the controller. | |
| A plugin cannot read a file, read the environment or import another, and | |
| relying on two plugins loading in a particular order would be relying on a | |
| directory listing. The controller calls applyOneTileConfig() directly instead. | |
| """ | |
| target = PROFILE/"plugin/t39-controller.js" | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| target.write_text(f"var ONETILE_TARGET_GUESTS = {guests};\n" | |
| f"var ONETILE_ATTEMPTS_ALLOWED = {ATTEMPTS};\n" | |
| + (LIB/"onetile-config.js").read_text() | |
| + "\n" + (LIB/"controller.js").read_text()) | |
| return target | |
| def reset_profile(): | |
| """Start from an empty save directory and an empty attempt ledger. | |
| The game profile is a volume that can outlive a container, and the grader | |
| falls back to the newest save when a run never settled. A previous run's | |
| autosave sitting in there would be graded as this run's park. The ledger is | |
| the same hazard for the clock: it lives in the engine's shared plugin store | |
| precisely so that it survives the park being reloaded, which means it also | |
| survives a container, and a stale one would charge this run for attempts it | |
| never took. | |
| """ | |
| for name in ("save", "screenshot"): | |
| shutil.rmtree(PROFILE/name, ignore_errors=True) | |
| (PROFILE/name).mkdir(parents=True, exist_ok=True) | |
| (PROFILE/"plugin.store.json").unlink(missing_ok=True) | |
| def playable_base(): | |
| """Put the base plot somewhere the agent's save dialog can write, and lay | |
| down one pristine copy per further attempt. | |
| The engine opens Save As in the directory the park was loaded from, and | |
| /opt/onetile is root-owned and read-only, so loading straight from there | |
| leaves the agent in a directory where saving silently fails. The immutable | |
| copy stays in /opt; the engine plays a copy in the save directory, which is | |
| writable and is the one directory the collector preserves -- so a park the | |
| agent saves by hand ends up in the evidence instead of somewhere nothing | |
| looks. Runs after reset_profile(), which would otherwise delete this. | |
| The restart copies are the agent's route to attempts 2 and 3 and are the only | |
| parks in there that a restart may be taken from, so they are read-only: Save | |
| As offers the loaded park's name first, and a restart point the agent can | |
| save over is a restart point that disappears exactly when it is needed. Their | |
| names are short because the load dialog truncates the column -- see | |
| restart_name(). | |
| """ | |
| target = PROFILE/"save/onetile-base.park" | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| target.write_bytes(BASE.read_bytes()) | |
| target.chmod(0o644) | |
| for attempt in range(2, ATTEMPTS+1): | |
| restart = PROFILE/f"save/{restart_name(attempt)}" | |
| restart.write_bytes(BASE.read_bytes()) | |
| restart.chmod(0o444) | |
| return target | |
| def collect(): | |
| subprocess.run([sys.executable, str(LIB/"collect.py"), "--screenshot"], check=False) | |
| def attempts_used(): | |
| """How many attempts the controller has started, read from its own stream. | |
| The audit is the authority on this, not a counter here: the attempt begins | |
| when the controller configures a fresh park, and only the controller knows | |
| that happened. Only this run's part of the stream is counted -- the audit is | |
| append-only and /logs is a volume that can outlive a container, so an earlier | |
| run's attempts are sitting in front of it. run_started is this run's mark. | |
| """ | |
| try: | |
| text = (AUDIT/"game.jsonl").read_text() | |
| except OSError: | |
| return 0 | |
| return text.rpartition('"kind": "run_started"')[2].count("onetile_initialized") | |
| def run(park, arguments): | |
| """Play the run; return the child and why the watch ended.""" | |
| outcome = STATE/"outcome" | |
| heartbeat = STATE/"heartbeat" | |
| for path in (outcome, heartbeat): | |
| path.unlink(missing_ok=True) | |
| child = subprocess.Popen( | |
| [sys.executable, str(LIB/"game-process.py"), str(park), *arguments, | |
| "--rct2-data-path", "/opt/rct2-assets", | |
| "--openrct2-data-path", "/opt/OpenRCT2/data"], | |
| env={**os.environ, "T39_RUN_OUTCOME": str(outcome), | |
| "T39_RUN_HEARTBEAT": str(heartbeat)}) | |
| started = time.time() | |
| # When an attempt fails with attempts left, this is the moment it failed: the | |
| # run is held open from here for the agent to take the next one. | |
| failed_at = None | |
| while True: | |
| # An outcome the engine reported stands even if the engine then died, so | |
| # a crash on the way out cannot erase a settled run. game-process clears | |
| # the file when a fresh attempt starts, so it always describes the attempt | |
| # being played. | |
| if outcome.exists(): | |
| reason = outcome.read_text().strip() or "objective_failed" | |
| if reason == "objective_complete" or attempts_used() >= ATTEMPTS: | |
| return child, reason | |
| if failed_at is None: | |
| failed_at = time.time() | |
| mark({"kind": "attempt_ended", "reason": reason, | |
| "attempts_used": attempts_used(), "attempts_allowed": ATTEMPTS}) | |
| elif time.time()-failed_at > RESTART_GRACE: | |
| return child, "attempts_unused" | |
| else: | |
| failed_at = None | |
| if child.poll() is not None: | |
| return child, "engine_exit" | |
| if heartbeat.exists(): | |
| silent = time.time()-heartbeat.stat().st_mtime | |
| # A park left on the title screen is only the end of the run once the | |
| # attempts are gone; before that the agent is given the same window to | |
| # come back with a fresh one. | |
| if silent > HEARTBEAT_TIMEOUT and (attempts_used() >= ATTEMPTS | |
| or silent > HEARTBEAT_TIMEOUT+RESTART_GRACE): | |
| return child, "park_closed" | |
| elif time.time()-started > STARTUP_TIMEOUT: | |
| return child, "engine_stalled" | |
| time.sleep(POLL) | |
| def stop(child): | |
| if child.poll() is not None: | |
| return | |
| child.terminate() | |
| try: | |
| child.wait(timeout=30) | |
| except subprocess.TimeoutExpired: | |
| child.kill() | |
| child.wait() | |
| def main(): | |
| child = None | |
| def shutdown(*_): | |
| if child is not None: | |
| stop(child) | |
| sys.exit(0) | |
| signal.signal(signal.SIGTERM, shutdown) | |
| signal.signal(signal.SIGINT, shutdown) | |
| publish("starting") | |
| guests = target_guests() | |
| reset_profile() | |
| installed = install_plugin(guests) | |
| park = playable_base() | |
| mark({"kind": "run_started", "plugin": str(installed), "base": str(BASE), | |
| "park": str(park), "target_guests": guests, "attempts_allowed": ATTEMPTS}) | |
| publish("running") | |
| child, reason = run(park, sys.argv[1:]) | |
| if reason in ("objective_complete", "objective_failed"): | |
| time.sleep(SETTLE_GRACE) | |
| collect() | |
| mark({"kind": "run_ended", "reason": reason}) | |
| publish(reason) | |
| # The park stays on screen: the agent reports on it and the verifier | |
| # screenshots it. Exiting here would stop the container. | |
| if child is not None: | |
| sys.exit(child.wait()) | |
| if __name__ == "__main__": | |
| main() | |