// XLeRobot Sim: MuJoCo-GS-Web's XLeRobot (and any uploaded robot) in its scenes or the kitchen, with
// keyboard teleop, skills, a learned policy and an LLM agent; and a Unitree G1 that walks with a learned
// policy. window.xlerobotSim exposes it all.
import "./style.css";
import { SceneView } from "./render/view.js";
import { fetchRobot, json, mujocoModule, onnxRuntime, progress, readRobotFolder, download, text } from "./core/assets.js";
import { writeScene } from "./core/compose.js";
import { Sim } from "./core/sim.js";
import { TELEOP_KEYS, XLeRobot, XLeRobotTeleop } from "./robots/xlerobot.js";
import { G1_KEYS, G1Robot, G1Teleop } from "./robots/g1.js";
import { GenericRobot } from "./robots/generic.js";
import { SkillRunner, comfortable, homeArm, objectInfo, holding } from "./robots/skills.js";
import { PolicyRunner } from "./policy/runner.js";
import { Episode, Household } from "./tasks/household.js";
import { solve } from "./tasks/solver.js";
import { createTools } from "./agent/tools.js";
import { BRIDGE_SPECS, TOOL_GUIDE, TOOL_SPECS } from "./agent/specs.js";
import { Agent, CLAUDE_DEFAULT, CLAUDE_MODELS } from "./agent/agent.js";
import { Bridge, bridgeRequested } from "./agent/bridge.js";
import { DEFAULT_MODEL, HF_ROUTER, routerModels } from "./agent/llm.js";
import { GEMINI_AGENT_DEFAULT } from "./agent/gemini.js";
import { GEMINI_MODEL } from "./agent/perception.js";
import { currentLogin, signIn, signInRequested, signOut } from "./agent/oauth.js";
const BASE = import.meta.env.BASE_URL;
// What the page opens on, unless its URL says otherwise: the kitchen, in Lit (its photographic room).
const DEFAULT_ENV = "kitchen";
const $ = (id) => document.getElementById(id);
const store = {
get: (k, d = null) => {
try {
return localStorage.getItem(`xlerobot-sim.${k}`) ?? d;
} catch {
return d;
}
},
set: (k, v) => {
try {
localStorage.setItem(`xlerobot-sim.${k}`, v);
} catch {
// storage blocked: settings last for this visit
}
},
};
const app = {
mujoco: null,
envs: [],
robots: [],
robotData: {}, // id -> fetched robot (xml, meshes, meta)
envId: null,
robotId: null,
sim: null,
robot: null,
teleop: null,
skills: new SkillRunner(),
settled: null,
view: null,
policy: null,
policyLoading: null,
walking: {}, // robot id -> promise of its locomotion policy session (ONNX Runtime)
pictures: {}, // camera -> the last picture it took for a tool, with the camera's pose then (locate)
activity: null, // what is loading, shown on the view when no skill runs
household: null, // the scene's household tasks, if it has them (src/tasks/)
episode: null, // the task instance being done
};
function setLoading(message, fraction) {
$("loading").hidden = false;
$("loading").classList.remove("failed");
if (message) $("loading-text").textContent = message;
if (fraction !== undefined) $("loading-bar").style.width = `${Math.round(fraction * 100)}%`;
}
function showError(error) {
console.error(error);
$("loading").hidden = false;
$("loading-text").textContent = `Could not load: ${error.message}`;
$("loading").classList.add("failed");
}
// ---------------------------------------------------------------------------------------------
// Scenes
/**
* The environment's XML, and the files next to it to include: its decor (a modelled stand-in for its
* splat) and its objects ("objects" naming a file), if it has them.
*/
async function envSource(env) {
const dir = env.xml.slice(0, env.xml.lastIndexOf("/") + 1);
const extra = [env.decor, env.objects?.endsWith(".xml") ? env.objects : null].filter(Boolean);
const [xml, ...files] = await Promise.all([text(`${BASE}environments/${env.xml}`), ...extra.map((f) => download(`${BASE}environments/${dir}${f}`))]);
return { xml, files: extra.map((f, k) => [f, files[k]]), includes: extra };
}
/** Compose `envId` with the robot `robotId`, compile, settle and show it. */
async function loadScene(envId, robotId) {
const env = app.envs.find((e) => e.id === envId) ?? app.envs[0];
const robotData = app.robotData[robotId];
app.skills.cancel("scene changed");
app.pictures = {};
setLoading(`Building ${env.name} with ${robotData.meta.name}…`);
await new Promise((r) => requestAnimationFrame(r));
const withObjects = env.objects === "robot" && robotData.objectsXml;
const path = writeScene(app.mujoco, "/scene", await envSource(env), { ...robotData, objectsXml: withObjects ? robotData.objectsXml : null }, { modelName: `${env.id}_${robotId}` });
let model;
try {
model = app.mujoco.MjModel.from_xml_path(path);
} catch (error) {
throw new Error(`MuJoCo could not compile the scene: ${error.message ?? error}`);
}
// A walking robot's policy loads with the scene (once): it has to run from the first step.
const walking = robotData.meta.controller === "g1" ? await walkingPolicy(robotData) : null;
app.sim?.dispose();
const sim = new Sim(app.mujoco, model, { controlHz: 50 });
const { controller } = robotData.meta;
const robot = controller === "xlerobot" ? new XLeRobot(sim, robotData.meta) : controller === "g1" ? new G1Robot(sim, robotData.meta, robotData.policyConfig) : new GenericRobot(sim, robotData.meta);
app.sim = sim;
app.robot = robot;
app.envId = env.id;
app.robotId = robotId;
app.teleop = robot instanceof XLeRobot ? new XLeRobotTeleop(robot) : robot instanceof G1Robot ? new G1Teleop(robot) : null;
// XLeRobot's arms start in their resting pose: rising to it from the model's zero pose, they would
// sweep objects off a counter beside the robot.
sim.reset(() => {
robot.home();
if (robot instanceof XLeRobot) robot.snapJoints();
});
// Objects settle where the scene drops them; a walking robot stands on its joint servos meanwhile.
sim.run(robot instanceof G1Robot ? 0.3 : 1.0, () => robot.update());
if (walking) robot.setPolicy(walking.ort, walking.session);
sim.steps = 0;
app.settled = sim.snapshot();
// Household tasks (the kitchen's): BDDL problems over the scene's objects and fixtures.
app.household = null;
app.episode = null;
if (env.tasks && robot instanceof XLeRobot) {
try {
app.household = await loadHousehold(env, sim, robot);
} catch (error) {
console.warn(`could not load the tasks of ${env.name}`, error);
}
}
app.view.splatBase = `${BASE}environments/`;
// How the robot's rgba values are meant (robot.json "colorSpace"), for its objects too when it brought them.
const colorSpace = robotData.meta.colorSpace ?? "srgb";
// Lit's models (dressing.json: furniture, appliances, objects): where they go comes first, as the scenery
// they stand in for is drawn apart; the models themselves load while the scene already runs.
const envDir = `${BASE}environments/${env.xml.slice(0, env.xml.lastIndexOf("/") + 1)}`;
let dressing = env.dressing ? await json(`${envDir}${env.dressing}`).catch((error) => console.warn(`no furniture models for ${env.name}: ${error.message}`)) : null;
// A photographic room (tools/home) has the furniture and the appliances in it: only the objects' models remain.
if (dressing && env.home) dressing = { ...dressing, items: [], parts: [] };
app.view.setScene(sim, {
robotRoots: robot.roots ?? (robot.root >= 0 ? [robot.root] : []),
env,
cameras: robotData.meta.cameras ?? {},
robot,
colorSpaces: { robot: colorSpace, object: withObjects ? colorSpace : "srgb" },
dressing: dressing ?? null,
});
app.view.frameRobot(robot.pose(), robot instanceof G1Robot ? { distance: 3.0, height: 1.9 } : env.id === "kitchen" ? { distance: 2.4, height: 1.8 } : {});
// The environment's photographic room or baked light for Lit (tools/home, tools/bake_light.mjs), loaded while
// the scene already runs (app.looksLoading: until they are there, for a camera picture or an MCP client).
const looks = [];
if (env.home) looks.push(app.view.loadHome(`${envDir}${env.home}`).catch((error) => console.warn(`no photographic room for ${env.name}: ${error.message}`)));
else if (env.light) looks.push(app.view.loadLight(`${envDir}${env.light}`).catch((error) => console.warn(`no baked light for ${env.name}: ${error.message}`)));
if (dressing) looks.push(app.view.loadDressing(`${envDir}${env.dressing.slice(0, env.dressing.lastIndexOf("/") + 1)}`).catch((error) => console.warn(`no furniture models for ${env.name}: ${error.message}`)));
app.looksLoading = Promise.all(looks);
if (app.view.style === "splat" && !env.splat) await setStyle("lit");
else if (app.view.style === "splat" || app.view.style === "pixel") await setStyle(app.view.style); // this environment's splat
refreshSceneUi();
$("loading").hidden = true;
const url = new URL(location.href);
url.searchParams.set("env", env.id);
history.replaceState(null, "", url);
}
function resetScene() {
app.skills.cancel("reset");
app.sim.restore(app.settled);
app.robot.home();
app.sim.forward();
app.household?.reset();
app.episode = null;
renderTask();
}
/** An environment's household: its tasks' registry and BDDL problems, tied to the simulation. */
async function loadHousehold(env, sim, robot) {
const base = `${BASE}environments/${env.xml.slice(0, env.xml.lastIndexOf("/") + 1)}`;
const registry = await json(`${base}${env.tasks}`);
const dir = env.tasks.slice(0, env.tasks.lastIndexOf("/") + 1);
const texts = await Promise.all(registry.tasks.map((t) => text(`${base}${dir}${t.file}`)));
return new Household(sim, robot, registry, Object.fromEntries(registry.tasks.map((t, k) => [t.file, texts[k]])));
}
/** Movable objects: free bodies that are not the robot. */
function objects() {
if (!app.sim) return [];
return app.sim.freeBodies(app.robot?.roots ?? (app.robot?.root >= 0 ? [app.robot.root] : []));
}
/** Height of the highest static box top under a world point, below `below` (for placing things). */
function surfaceBelow(point, below = Infinity) {
const { model, data } = app.sim;
let best = 0;
for (let g = 0; g < model.ngeom; g++) {
if (model.geom_type[g] !== 6 || model.body_weldid[model.geom_bodyid[g]] !== 0 || !model.geom_contype[g]) continue;
const c = data.geom_xpos.subarray(3 * g, 3 * g + 3);
const R = data.geom_xmat.subarray(9 * g, 9 * g + 9);
const s = model.geom_size.subarray(3 * g, 3 * g + 3);
const d = [point[0] - c[0], point[1] - c[1], 0];
const lx = R[0] * d[0] + R[3] * d[1];
const ly = R[1] * d[0] + R[4] * d[1];
if (Math.abs(lx) > s[0] || Math.abs(ly) > s[1]) continue;
const top = c[2] + Math.abs(R[6]) * s[0] + Math.abs(R[7]) * s[1] + Math.abs(R[8]) * s[2];
if (top < below && top > best) best = top;
}
return best;
}
// ---------------------------------------------------------------------------------------------
// Renderer, cameras, keys, sliders
const styleButtons = [...document.querySelectorAll("[data-style]")];
const STYLES = styleButtons.map((b) => b.dataset.style);
const pressStyle = (style) => {
for (const b of styleButtons) b.setAttribute("aria-pressed", String(b.dataset.style === style));
};
/**
* Switch renderer: "toon", "lit", "splat" or "pixel" (pixel art of the splat, or of the Toon scene where
* the environment has none). If the 3DGS renderer cannot load, the scene keeps running, in Lit or in
* Pixel's modelled scene, and the panel says why.
*/
async function setStyle(style) {
const env = app.envs.find((e) => e.id === app.envId);
if (style === "simple") style = "toon"; // its earlier name, maybe in an old link
if (style === "splat" && !env?.splat) style = "lit";
pressStyle(style);
$("style-note").hidden = true;
let loading = (style === "splat" || style === "pixel") && Boolean(env?.splat);
if (loading) app.activity = "Loading the 3D Gaussian splat";
const onBytes = (got, total) => {
if (loading && total) app.activity = `Loading the 3D Gaussian splat, ${Math.round((100 * got) / total)}%`;
};
try {
await app.view.setStyle(style, { onBytes });
} catch (error) {
console.error(error);
if (style === "pixel") {
$("style-note").textContent = `Could not load the 3DGS scene (${error.message}). Pixel shows the modelled scene instead.`;
} else {
await app.view.setStyle("lit");
pressStyle("lit");
$("style-note").textContent = `Could not load the 3DGS renderer (${error.message}). Showing Lit instead.`;
}
$("style-note").hidden = false;
} finally {
if (loading) app.activity = null;
loading = false; // a download that outlives a failure reports nothing
}
}
function refreshSceneUi() {
const env = app.envs.find((e) => e.id === app.envId);
$("env").value = app.envId;
$("env-note").textContent = env.description ?? "";
for (const b of styleButtons) if (b.dataset.style === "splat") b.disabled = !env.splat;
// Robot cameras
const cams = app.view.robotCameras;
$("cameras-section").hidden = Object.keys(cams).length === 0;
// None by default: each draws the scene again (in 3DGS, the splat too). A visitor's choice is kept.
const saved = (store.get("views") ?? "").split(",").filter(Boolean);
$("cameras").innerHTML = Object.entries(cams)
.map(([name, c]) => ``)
.join("");
const boxes = [...document.querySelectorAll("[data-view]")];
// Saved when the visitor ticks a box, not here: a robot without some cameras keeps the choice for others.
const setViews = (save) => {
const names = boxes.filter((b) => b.checked).map((b) => b.dataset.view);
app.view.setViews(names);
if (save) store.set("views", names.join(","));
};
for (const b of boxes) b.addEventListener("change", () => setViews(true));
setViews(false);
// Keys or sliders
const xl = app.robot instanceof XLeRobot;
const g1 = app.robot instanceof G1Robot;
$("keys-section").hidden = !xl && !g1;
$("keys").innerHTML = (g1 ? G1_KEYS : TELEOP_KEYS).map(([k, what]) => `
${k}
${what}
`).join("");
$("sliders-section").hidden = xl || g1;
if (!xl && !g1) {
$("sliders").innerHTML = app.robot.actuators
.map((a) => ``)
.join("");
for (const input of $("sliders").querySelectorAll("input")) input.addEventListener("input", () => app.robot.set(input.dataset.act, Number(input.value)));
}
for (const b of document.querySelectorAll("[data-skill]")) b.disabled = !xl;
$("skill-status").textContent = xl ? "" : "Skills, the pick policy and the agent drive XLeRobot; choose it under Scene → Robot.";
refreshObjects();
refreshTasks();
// State table
$("state").innerHTML = "";
stateCells = [];
if (xl) {
for (const name of Object.keys(app.robot.qpos)) {
const row = document.createElement("tr");
row.innerHTML = `
${name}
0
`;
$("state").append(row);
stateCells.push([name, row.lastChild]);
}
}
}
let stateCells = [];
function refreshObjects() {
const list = objects();
const keep = $("object").value;
$("object").innerHTML = list.map((o) => ``).join("");
if (list.some((o) => o.name === keep)) $("object").value = keep;
const keepTarget = $("place-target").value;
$("place-target").innerHTML = `` + list.map((o) => ``).join("");
if ([...$("place-target").options].some((o) => o.value === keepTarget)) $("place-target").value = keepTarget;
}
// ---------------------------------------------------------------------------------------------
// Policy
async function loadPolicy() {
if (app.policy) return app.policy;
app.policyLoading ??= (async () => {
const list = await json(`${BASE}policies/index.json`);
const entry = list.find((p) => p.robot === "xlerobot");
if (!entry) throw new Error("no policy for this robot in policies/index.json");
const dir = `${BASE}policies/${entry.dir}/`;
const meta = await json(`${dir}policy.json`);
const status = $("policy-status");
const track = progress({ ort: 3.8e6, onnx: 17e6 }, (f) => (status.textContent = `Loading the policy… ${Math.round(f * 100)}%`));
const [ort, bytes] = await Promise.all([onnxRuntime(track("ort")), download(`${dir}${meta.onnx}`, track("onnx"))]);
app.policy = await PolicyRunner.load(ort, bytes, meta);
status.textContent = `${meta.name}: ${(meta.parameters / 1e6).toFixed(1)} M parameters, chunks of ${meta.chunk_size} actions at ${meta.fps} Hz, ${meta.n_action_steps} executed per inference.`;
return app.policy;
})();
try {
return await app.policyLoading;
} catch (error) {
app.policyLoading = null;
$("policy-status").textContent = `Could not load the policy: ${error.message}`;
throw error;
}
}
/** A walking robot's locomotion policy: ONNX Runtime and a session on its ONNX file, loaded once. */
function walkingPolicy(robotData) {
const id = robotData.name;
app.walking[id] ??= (async () => {
const track = progress({ ort: 3.8e6, onnx: 0.9e6 }, (f) => setLoading(`Loading ${robotData.meta.name}'s walking policy…`, f));
const [ort, bytes] = await Promise.all([onnxRuntime(track("ort")), download(robotData.policyUrl, track("onnx"))]);
const session = await ort.InferenceSession.create(bytes, { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
return { ort, session };
})();
app.walking[id].catch(() => delete app.walking[id]); // try again next time
return app.walking[id];
}
// ---------------------------------------------------------------------------------------------
// Skills tab and agent tools
const tools = createTools({
get sim() {
return app.sim;
},
get robot() {
return app.robot;
},
get skills() {
return app.skills;
},
objects,
loadPolicy,
get household() {
return app.household;
},
get episode() {
return app.episode;
},
surfaceBelow: (p) => surfaceBelow(p),
snapshot: (name) => app.view.snapshot(name),
envInfo: () => {
const env = app.envs.find((e) => e.id === app.envId);
return `${env.name}: ${env.description}`;
},
cameras: () => Object.keys(app.view?.robotCameras ?? {}),
picture: (name, width) => picture(name, width),
lastPicture: (name) => app.pictures[name] ?? null,
perception: () => ({ key: geminiKey(), model: GEMINI_MODEL, thinking: $("locate-thinking").value || "low", cameraOnly: $("camera-only").checked }),
});
/**
* A robot camera's picture and the camera's pose and lens as it was taken (for locate, which maps points in
* it to positions); the last one of each camera is kept, for points an agent finds in it itself.
*/
async function picture(name, width = 512) {
if (!app.view?.robotCameras?.[name]) return null;
await app.looksLoading; // the scene as it will look, not as it looked while its models loaded
if (app.view.sim !== app.sim) return null; // a new scene is loading
app.view.update(); // a hidden tab has drawn nothing since the physics moved
const frame = app.view.cameraFrame(name, width);
const image = await app.view.snapshot(name, width);
if (!image) return null;
app.pictures[name] = { image, frame, time: performance.now() };
return { image, frame };
}
/** The Gemini API key for locate and the Gemini agent: this browser's, else the MCP server's (GEMINI_API_KEY). */
const geminiKey = () => $("gemini-key").value.trim() || bridge.geminiKey || "";
// The Skills tab's buttons name objects, whatever an agent's perception.
const HUMAN = { human: true };
async function runSkill(label, promise) {
$("skill-status").textContent = `${label}…`;
const result = await promise;
$("skill-status").textContent = `${label}: ${result.message ?? (result.ok ? "done" : "failed")}`;
return result;
}
for (const button of document.querySelectorAll("[data-skill]")) {
button.addEventListener("click", async () => {
const object = $("object").value;
const kind = button.dataset.skill;
if (kind === "stop") return app.skills.cancel("stopped");
if (kind === "go_to") return runSkill(`Go to the ${object}`, tools.call("go_to", { object }, HUMAN));
if (kind === "pick") return runSkill(`Pick the ${object}`, tools.call("pick", { object }, HUMAN));
if (kind === "pick_policy") return runSkill(`Policy picks the ${object}`, tools.call("pick", { object, method: "policy" }, HUMAN));
if (kind === "home") return runSkill("Rest the arms", tools.call("home_arms", {}, HUMAN));
if (kind === "place") {
const side = ["left", "right"].find((s) => objects().some((o) => holding(app.robot, s, o.id)));
if (!side) return ($("skill-status").textContent = "Neither gripper holds anything.");
const on = $("place-target").value;
return runSkill("Place", tools.call("place", on ? { arm: side, on } : { arm: side, forward_m: 0.3, left_m: side === "left" ? 0.05 : -0.05 }, HUMAN));
}
});
}
// ---------------------------------------------------------------------------------------------
// Tasks tab: household tasks in the style of the BEHAVIOR Challenge
function refreshTasks() {
const h = app.household;
$("tasks-none").hidden = Boolean(h);
$("tasks-body").hidden = !h;
if (!h) return;
const keep = $("task").value || store.get("task");
$("task").innerHTML = h.tasks.map((t) => ``).join("");
if (h.task(keep)) $("task").value = keep;
renderTask();
}
/** The selected task: its instruction and BDDL, and the episode's goal, score and measures if it is this one's. */
function renderTask() {
const h = app.household;
const t = h?.task($("task").value);
if (!t) return;
const e = app.episode?.task === t ? app.episode : null;
$("task-instruction").textContent = t.instruction;
$("task-bddl").textContent = t.problem.text;
const goals = e ? e.goals : t.goals.map((expr) => ({ label: h.describe(expr), done: false }));
$("task-goals").innerHTML = goals.map((g) => `