The first exam for code agents in the physical world: frozen robot tasks from many benchmark suites, each answered with a program and verified in a separate sandbox. Runs on Harbor.
Python ai-agentsbenchmarkcoding-agentsembodied-aievaluationharborllm-agentsrobot-learningroboticssimulation
Merge pull request #58 from JamesKrW/dev/changhe-playground-quadruped-shared (+1 more)
Changhe Chenf8f400975cea
diff --git a/README.md b/README.mdindex 02c7d6ad21..51890909dd 100644--- a/README.md+++ b/README.md@@ -37,7 +37,7 @@ measures the same thing under real-robot constraints. The standard-mode wire pro| robosuite example (`robosuite-cube-stack-i00-privileged`) | robosuite (MuJoCo) · Franka Panda | 1 (privileged) | full || RoboTwin 2.0 (`robotwin_2_0_<task>`) | SAPIEN 3 + CuRobo · ALOHA-AgileX dual arm | 47 of 50 | full (upstream expert) || DexToolBench (`dextoolbench_<cat>_<obj>_<task>`) | MuJoCo 3.3.7 · KUKA iiwa14 + Sharpa HA4 hand | 21 of 24 | full on 6, partial on 15 |-| MuJoCo Playground (`mujoco_playground_<env>`) | MuJoCo · ALOHA, Franka Panda | 4 | full (scripted IK) |+| MuJoCo Playground (`mujoco_playground_<env>`) | MuJoCo · ALOHA, Franka Panda; quadrupeds: Unitree Go1, Boston Dynamics Spot, Google Barkour vB | 4 manipulation + 9 quadruped | full (manipulation: scripted IK; quadrupeds: Playground's Go1 policy or policies trained on its rewards) || KinDER (`kinder-<family>-i00`) | MuJoCo 3.3 / PyBullet · TidyBot++ mobile manipulator | 11 | full on 1, none on 10 (human review) || HumanoidBench (`humanoidbench-<family>-i00`) | MuJoCo · Unitree H1 humanoid | 24 | full on 1, none on 23 (human review) || MetaWorld+ (`metaworldplus-<env>-i00`) | MuJoCo (Meta-World v3) · Rethink Sawyer | 50 | full |@@ -112,9 +112,9 @@ harbor view jobsoracle agent alone. Upstream experts are removed from the agent's images.- **Recorded evidence in standard mode.** The simulator service records the episode, replays it in a fresh simulator,and writes the verdict inputs. The agent never holds the simulator.-- **Network policy.** DexToolBench, KinDER, HumanoidBench, MetaWorld+, RoboPaint, RoboPaint-strict, VLABench, MyoSuite and the three- RoboCasa benchmarks restrict agent egress to model APIs by default, because their reference policies, demonstrations or- baselines are public. RoboTwin, MuJoCo Playground, robosuite, RoboWits, RoboLab and BEHAVIOR-1K use Harbor's default+- **Network policy.** DexToolBench, KinDER, HumanoidBench, MetaWorld+, RoboPaint, RoboPaint-strict, VLABench, MyoSuite, the three+ RoboCasa benchmarks and MuJoCo Playground's quadruped tasks restrict agent egress to model APIs by default, because their reference policies, demonstrations or+ baselines are public. RoboTwin, MuJoCo Playground's manipulation tasks, robosuite, RoboWits, RoboLab and BEHAVIOR-1K use Harbor's default(public) and can be switched with `scripts/set_agent_egress.py allowlist`. Separately, the harness's own web search isoff by default in batch runs (it runs at the model provider, past any allowlist).- **Reproducibility.** Base images are pinned by tag (pinning every pip dependency is part of the migration). A task's identity is its digest in `tasks/dataset.toml`,diff --git a/docs/STANDARD_MODE_2_2.md b/docs/STANDARD_MODE_2_2.mdindex 0d9014deb3..9584b51940 100644--- a/docs/STANDARD_MODE_2_2.md+++ b/docs/STANDARD_MODE_2_2.md@@ -6,7 +6,8 @@> before (plus parts and keys an old client ignores). Which parts are required is listed in PROTOCOL §4.**Who serves it.** The standard twins of seven benchmarks: BEHAVIOR-1K, RoboLab, RoboWits, RoboPaint, ManiGuard, MolmoSpaces-and MyoSuite ([docs/benchmarks/](benchmarks/); MyoSuite: MuJoCo on the CPU, resume class `exact`). The RoboTwin and MuJoCo standard tasks serve 2.1.+and MyoSuite ([docs/benchmarks/](benchmarks/); MyoSuite: MuJoCo on the CPU, resume class `exact`), and MuJoCo Playground's+quadruped tasks. The RoboTwin and the other MuJoCo standard tasks (DexToolBench, MuJoCo Playground's manipulation tasks) serve 2.1.**One implementation.** The source is [`scripts/eai_standard/`](../scripts/eai_standard/), the D9 shared source of these sixbenchmarks: the service layer `rcb_limited.py` (HTTP, RCB1 responses, the protocol helpers, the `/spec` self-check, crashdiff --git a/docs/TAXONOMY.md b/docs/TAXONOMY.mdindex dc693026bb..992cf6c3e5 100644--- a/docs/TAXONOMY.md+++ b/docs/TAXONOMY.md@@ -7,9 +7,9 @@ Known values; a new value is added by pull request (CI validation of these vocab| `author_name` | the author's name (an organization may go in `author_org`) || `task_type` | `trajectory` · `policy` || `mode` | `privileged` · `standard` (formerly `unlimited` / `limited`) |-| `protocol` | standard mode only: `eai-standard/2.1` · `eai-standard/2.2` (BEHAVIOR-1K, RoboLab, RoboWits, RoboPaint, ManiGuard, MolmoSpaces, MyoSuite; [STANDARD_MODE_2_2.md](STANDARD_MODE_2_2.md)) |+| `protocol` | standard mode only: `eai-standard/2.1` · `eai-standard/2.2` (BEHAVIOR-1K, RoboLab, RoboWits, RoboPaint, ManiGuard, MolmoSpaces, MyoSuite, MuJoCo Playground's quadruped tasks; [STANDARD_MODE_2_2.md](STANDARD_MODE_2_2.md)) || `simulator` | `robosuite` · `robotwin` (RoboTwin 2.0 = SAPIEN 3 + CuRobo) · `mujoco` · `kinder` (KinDER: MuJoCo and PyBullet) · `humanoidbench` (HumanoidBench: MuJoCo + dm_control) · `robowits` (RoboWits on Genesis) · `robolab` (NVIDIA RoboLab on Isaac Lab) · `behavior` (BEHAVIOR-1K: OmniGibson on Isaac Sim) · `maniskill` (ManiSkill 3 / SAPIEN: RoboPaint) · `vlabench` (VLABench: MuJoCo + dm_control) · `maniguard` (ManiGuard: BEHAVIOR-1K 3.7.2, OmniGibson on Isaac Sim 4.5) · `molmospaces` (Ai2 MolmoSpaces: MuJoCo) · `myosuite` (MyoSuite: musculoskeletal models on MuJoCo) — the simulator, not the image: benchmarks on one simulator may use different images and versions (PROTOCOL D5) |-| `robot` | `franka-panda` · `aloha-agilex` · `aloha-2` · `kuka-iiwa14-sharpa-ha4` · `tidybot-plus-plus` · `unitree-h1` · `unitree-h1hand` (H1 with two Shadow hands) · `sawyer` (Rethink Robotics Sawyer, as in Meta-World) · `marvin-bimanual` (RoboWits) · `franka-robotiq-2f85` (a Franka arm with a Robotiq 2F-85, the DROID setup: RoboLab, MolmoSpaces' FR3) · `r1pro` (BEHAVIOR-1K) · `franka-panda-omron` (RoboCasa's PandaOmron: Franka Panda on an Omron mobile base with a lift torso) · `fourier-gr1` (Fourier GR1 humanoid: two arms, waist and two Fourier dexterous hands, fixed base; RoboCasa-GR1) · `franka-panda-longfinger` (ManiGuard: Franka Panda with long fin-ray fingers) · `rainbow-rby1` (Rainbow Robotics RB-Y1: holonomic base, 6-joint torso, two 7-joint arms with parallel grippers; MolmoSpaces) · `myohand` (MyoSuite's MyoHand: a musculoskeletal human forearm and hand, 39 muscles) · `myoarm` (MyoSuite's MyoArm: a musculoskeletal human shoulder, arm and hand, 34 or 63 muscles) · `myoarm-torso` (MyoSuite's table-tennis player: torso, right arm and hand on a sliding pelvis) · `myoarm-mpl` (MyoSuite's MyoArm next to the Modular Prosthetic Limb, a motorized arm) · `myolegs` (MyoSuite's MyoLegs: a free-standing musculoskeletal torso and both legs) · `myoleg-osl` (MyoSuite's MyoLeg with an Open-Source Leg knee-ankle prosthesis) |+| `robot` | `franka-panda` · `aloha-agilex` · `aloha-2` · `kuka-iiwa14-sharpa-ha4` · `tidybot-plus-plus` · `unitree-h1` · `unitree-h1hand` (H1 with two Shadow hands) · `sawyer` (Rethink Robotics Sawyer, as in Meta-World) · `marvin-bimanual` (RoboWits) · `franka-robotiq-2f85` (a Franka arm with a Robotiq 2F-85, the DROID setup: RoboLab, MolmoSpaces' FR3) · `r1pro` (BEHAVIOR-1K) · `franka-panda-omron` (RoboCasa's PandaOmron: Franka Panda on an Omron mobile base with a lift torso) · `fourier-gr1` (Fourier GR1 humanoid: two arms, waist and two Fourier dexterous hands, fixed base; RoboCasa-GR1) · `franka-panda-longfinger` (ManiGuard: Franka Panda with long fin-ray fingers) · `rainbow-rby1` (Rainbow Robotics RB-Y1: holonomic base, 6-joint torso, two 7-joint arms with parallel grippers; MolmoSpaces) · `myohand` (MyoSuite's MyoHand: a musculoskeletal human forearm and hand, 39 muscles) · `myoarm` (MyoSuite's MyoArm: a musculoskeletal human shoulder, arm and hand, 34 or 63 muscles) · `myoarm-torso` (MyoSuite's table-tennis player: torso, right arm and hand on a sliding pelvis) · `myoarm-mpl` (MyoSuite's MyoArm next to the Modular Prosthetic Limb, a motorized arm) · `myolegs` (MyoSuite's MyoLegs: a free-standing musculoskeletal torso and both legs) · `myoleg-osl` (MyoSuite's MyoLeg with an Open-Source Leg knee-ankle prosthesis) · `unitree-go1` (Unitree Go1 quadruped; MuJoCo Playground) · `boston-dynamics-spot` (Boston Dynamics Spot quadruped; MuJoCo Playground) · `google-barkour-vb` (Google Barkour vB quadruped; MuJoCo Playground) || `family` | free-form slug naming the scene/goal, shared by its instances (e.g. `cube_stack`, `dextoolbench/brush/blue_brush/sweep_forward`) || `oracle` | `full` (oracle scores 1) · `partial` (oracle reaches part of the goal) · `none` — see PROTOCOL §2.7 || `oracle_evidence` | required unless `oracle = "full"`: where the evidence for solvability is (PR, results site, upstream record) |diff --git a/docs/benchmarks/mujoco-playground.md b/docs/benchmarks/mujoco-playground.mdnew file mode 100644index 0000000000..4ab9df2eef--- /dev/null+++ b/docs/benchmarks/mujoco-playground.md@@ -0,0 +1,135 @@+# MuJoCo Playground++GPU-scale RL environments from Google DeepMind, here in plain MuJoCo on the CPU. This page covers the quadruped+locomotion tasks (`scripts/mujoco-playground/`); the four manipulation tasks (`mujoco_playground_{aloha,panda}_*`,+ALOHA and Franka Panda, scripted IK references, `eai-standard/2.1`) predate it and are made by hand.++| | |+|---|---|+| upstream | [MuJoCo Playground](https://playground.mujoco.org/) (Apache-2.0) @ `4057c14`, with MuJoCo Menagerie @ `1b86ece` (the commit Playground pins) |+| simulator | MuJoCo 3.3.7, CPU physics (bit-exact replay); EGL rendering on a GPU, else OSMesa |+| robots | `unitree-go1` (Unitree Go1), `boston-dynamics-spot` (Boston Dynamics Spot), `google-barkour-vb` (Google Barkour vB); 12 joint position actuators each |+| score | binary, defined here from Playground's termination rules and reward targets (Playground has shaped RL rewards only) |+| tasks | Playground's 9 quadruped environments × 2 modes: `tasks/mujoco_playground_<env>-privileged` and `-standard` (`eai-standard/2.2`) |+| image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` (`images/mujoco/`: 0.1.2 plus Playground's `locomotion/{go1,spot}` scenes and Menagerie's Go1, Spot and Barkour; every 0.1.2 file is unchanged) |+| oracle | full, both modes |++## Tasks++| robot | environment | what it asks | horizon | instance | reference |+|---|---|---|---|---|---|+| Go1 | Go1JoystickFlatTerrain | track a joystick schedule (4 segments) on flat ground | 1000 steps, 20 s | seed 0 | Playground's Go1 policy |+| | Go1JoystickRoughTerrain | the same (7 segments) on a 20 x 20 m heightfield, bumps up to 5 cm | 1000, 20 s | seed 1 | Playground's Go1 policy |+| | Go1Getup | get up from a drop (lying tilted 110 deg) and stand | 300, 6 s | seed 5 | trained policy + scripted stand |+| | Go1Handstand | balance on the front legs, nose down, for 2 s | 500, 10 s | seed 0 | trained policy |+| | Go1Footstand | stand on the hind legs, nose up, for 2 s | 500, 10 s | seed 0 | trained policy (training-only changes) |+| Spot | SpotFlatTerrainJoystick | track a joystick schedule (5 segments) | 1000, 20 s | seed 0 | trained policy |+| | SpotGetup | get up from a 1 m drop (lying tilted 128 deg) and stand | 300, 6 s | seed 1 | trained policy |+| | SpotJoystickGaitTracking | joystick tracking with a commanded gait (here pace at 3.66 Hz, 0.129 m swing) | 1000, 20 s | seed 0 | trained policy (command observed) |+| Barkour | BarkourJoystick | joystick tracking (2 segments) through 12 pushes of up to 35 N | 1000, 10 s | seed 2 | trained policy |++## Task definition+- **Scene.** Playground's scene XML and asset set, loaded the way Playground's `get_assets()` does (bare file names from+ its `xmls/` and Menagerie's robot directory; Barkour: Menagerie's scene plus the foot-contact sensors its environment+ adds), with the drive gains Playground's environment sets (`Kp` as the actuator gain, `Kd` as joint damping; an+ actuator's own `kv` stays). One control step = 5 physics steps: 20 ms (Go1, Spot), 10 ms (Barkour, see below).+- **Instance.** One episode as Playground's own `reset` draws it with `jax.random.PRNGKey(seed)` (`make_instances.py`,+ Playground's code): the start state and, for the joystick tasks, the command schedule (and Barkour's pushes, Spot gait+ tracking's gait) that the environment's command process draws over the episode, its per-step key splits replayed+ exactly; the draws do not depend on the physics while the episode does not terminate. Getup: the drop's start state;+ the 0.5 s settle runs in the task's own MuJoCo. `instance.json` holds the start, the schedule, the t = 0 state hash+ and the numbers the texts quote.+- **Selection** (`select_instances.py`, never looking at an agent's result): seeds in order; skip a joystick schedule+ that is mostly standstill (under half the episode commanding |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s), Barkour pushes+ that are null or weak (peak under 20% of the torso's weight), a getup start that is not a fall (no drop, or tilted+ under 90 deg), and any seed whose reference fails. Every task's skipped seeds and why: `scripts/mujoco-playground/selection/`.+- **Actions.** 12 absolute joint position targets per control step, in actuator order; clipped to the actuator ranges.++## Success+- **Joystick.** T = horizon rows; the robot never meets its environment's termination rule (Go1: the trunk's up axis+ below the horizon; Spot: tilted by more than about 32 deg; Barkour: up axis below the horizon, a joint outside its box+ or the torso under 0.18 m); in every command segment, after its first 25 control steps, the mean planar velocity error+ |v_xy - cmd_xy| <= 0.2 m/s (the IMU's velocimeter, trunk frame) and the mean yaw-rate error |w_z - cmd_wz| <= 0.3 rad/s+ (the IMU's gyro). Gait tracking adds: the mean RMS height error of the feet to Playground's gait curve+ (`gait.get_rz`) at most 0.05 m.+- **Getup.** The trajectory ends with 25 control steps in a row with the trunk tilted at most 10 deg and the IMU at least+ 0.22 m (Go1; it stands at 0.255-0.26 m with Playground's gains) or 0.40 m (Spot; 0.44 m) above the floor.+- **Hand/footstand.** The trajectory ends with 100 control steps (2 s) in a row with the trunk's forward axis within 30 deg+ of straight down (handstand) or up (footstand), the IMU at least 0.40 m high (Playground aims at 0.55 / 0.53 m) and the+ feet of the lifted pair off the ground; no termination before: the up axis below -0.25, or a front leg's thigh, calf+ or hip on the floor (Playground's rule), and for the footstand the same for a hind leg (see below).+- Standard episodes end on success (getup, hand/footstand), at the horizon, on a termination (a failure), on `done` or+ on timeout. The joystick schedule is in `spec["command_schedule"]` and every response's `meta["command_now"]`; the gait+ in `spec["gait"]`. Pushes are not announced in standard mode.++## Modes++| mode | the agent gets | resets | graded |+|---|---|---|---|+| privileged | the simulator (`rcb_quadruped.Session`) and its full state | unlimited | its `trajectory.npz`, replayed in two fresh processes |+| standard (2.2) | cameras (Go1, Spot: four that follow the robot; Barkour: one that follows it and its head camera; RGB, optional depth), joints, IMU (gyro, accelerometer, gravity's direction, velocimeter), foot contacts; the feet's FK/IK in the trunk frame | none | the service's record of the one episode: live check, two fresh-process replays, determinism |++## Reference solutions+- **Go1 joystick:** MuJoCo Playground's own Go1 joystick policy (`experimental/sim2sim/onnx/go1_policy.onnx`, the one its+ `play_go1_joystick.py` runs in native MuJoCo), closed loop on the frozen instance, its targets recorded (`oracle.py`).+- **The rest:** Playground ships no other quadruped policy. Policies are trained here with PPO on the CPU+ (`scripts/mujoco-playground/train/`: rsl_rl with Playground's hyperparameters; each environment re-implemented in numpy+ with Playground's reset, action mapping, observations and rewards), then run closed loop on the frozen instance.+ - Go1 getup: the policy turns the robot belly-down and level but stops in a crouch (a local optimum of the reward); the+ reference then moves the joint targets linearly to `home` in 1 s.+ - Go1 footstand: trained with three training-only changes: the hind-leg termination this task uses, half of the episodes+ starting in Playground's `footstand` keyframe, and a steeper height reward (with Playground's own it squats at 0.2 m).+ - Spot gait tracking: trained with the command added to the observation (see below).+- Every reference row is float32-exact: the standard client sends actions as float32, so the standard oracle (streaming+ the rows through the client) records exactly the privileged reference.+- Policies only make the references: no image contains one, and the agent's egress is the model APIs only (Playground's+ policies are public).++## Playground behaviour kept, and where these tasks depart from it+- **Barkour's control step is 10 ms.** Its environment loads Menagerie's scene as is (2 ms timestep) while it takes+ round(ctrl_dt / sim_dt) = 5 substeps with sim_dt = 4 ms, so one step advances 10 ms. Kept: the robot's dynamics are the+ environment's (the push formula still uses ctrl_dt = 20 ms, as upstream).+- **A 1-step Barkour push is zero.** The push is 0.5 sin(pi i / duration) for i = 0 .. duration - 1. Kept; selection skips+ instances whose pushes are null or weak.+- **Footstand's termination reads the front-leg list.** `Footstand._post_init` assigns the hind-leg geoms to+ `_unwanted_contact_geom_ids`, but the termination reads the front-leg sensors it inherits. A policy trained on that+ sits on a hind hip with its feet in the air. The task adds the hind-leg rule.+- **Spot gait tracking does not observe the command.** Its observation (69) has no command, yet its reward tracks one;+ a policy trained on it marches in place. The task keeps the command (the agent sees it); the reference's policy+ observes it.+- **Hand/footstand targets accumulate** (ctrl + 0.3 action, unclipped); the references follow that, the task's actions+ are absolute targets.++## Verification (2026-10-06, eai-mujoco:0.1.3, Harbor)++| | oracle | nop |+|---|---|---|+| all 9 environments, privileged | 1 (both fresh-process replays succeed, deterministic, video) | 0 (no trajectory) |+| all 9 environments, standard | 1 (live check, both replays, deterministic, replays end in the live state, video) | 0 |++The references' own margins (worst joystick segment, end pose):++| environment | reference |+|---|---|+| Go1JoystickFlatTerrain | 0.073 m/s, 0.091 rad/s |+| Go1JoystickRoughTerrain | 0.079 m/s, 0.114 rad/s |+| Go1Getup | upright after 136 steps, IMU 0.257 m |+| Go1Handstand | 115 steps, 13.8 deg from straight down, IMU 0.531 m |+| Go1Footstand | 113 steps, 9.6 deg from straight up, IMU 0.541 m |+| SpotFlatTerrainJoystick | 0.156 m/s, 0.072 rad/s |+| SpotGetup | upright after 63 steps, IMU 0.478 m |+| SpotJoystickGaitTracking | 0.183 m/s, 0.136 rad/s, foot height 0.038 m |+| BarkourJoystick | 0.033 m/s, 0.028 rad/s |++Outside Harbor, the standard service run on each reference (`std_local` check): live verdict success, and a+fresh-process replay of its record ends in the live state hash. Generator: `python3 scripts/mujoco-playground/generate.py --check`.++## Files+| | |+|---|---|+| `scripts/mujoco-playground/shared/rcb_quadruped.py` | the tooling (privileged), the verifier's replay CLI and the service's simulator |+| `shared/standard/server.py` | the 2.2 adapter on `scripts/eai_standard/rcb_limited.py`; `finalize.sh`, the collect hook |+| `make_instances.py`, `select_instances.py`, `oracle.py` | candidates (Playground's code, JAX), selection and freezing, references |+| `instances/`, `oracles/`, `selection/` | the frozen instances, the reference rows, every candidate tried |+| `train/` | the reference-policy training (CPU PPO), not used by any task |+| `generate.py`, `templates/` | the task directories (`--check` compares) |diff --git a/scripts/mujoco-playground/README.md b/scripts/mujoco-playground/README.mdnew file mode 100644index 0000000000..9667ed30a5--- /dev/null+++ b/scripts/mujoco-playground/README.md@@ -0,0 +1,21 @@+# MuJoCo Playground quadruped tasks: how they are made++docs/benchmarks/mujoco-playground.md describes the tasks; this is the pipeline that makes them. Only `generate.py` runs+in CI (standard library only); the rest needs MuJoCo 3.3.7 and the asset tree of `eai-mujoco`+(`RCB_MJ_ROOT`, built by `images/mujoco/prepare_assets.sh`; `RCB_MJ_OUT=<dir>` writes it elsewhere).++1. **Candidates** (Playground's own code, JAX on the CPU; a checkout of MuJoCo Playground at 4057c14 installed with+ `pip install -e <playground> "jax[cpu]"`):+ `python make_instances.py Go1JoystickFlatTerrain --seeds 0-39 --out cand/`+2. **Reference policies** for the environments without a pretrained one (`train/`, PPO with rsl_rl on the CPU, plain+ MuJoCo in worker processes; `pip install torch rsl-rl-lib tensordict mujoco==3.3.7`):+ `train/run_capped.sh Go1Getup --iters 1000 --envs 2048 --workers 14 --out runs/go1_getup` (a 48 GB memory cap via a+ systemd user scope; ~3 GB used). `train/qenv.py` mirrors each Playground environment's reset, action mapping,+ observations and rewards. Go1 joystick needs none: Playground ships its policy (`RCB_PLAYGROUND=<checkout>`).+3. **Selection and freezing**: `python select_instances.py Go1Getup --cand cand/ --policy runs/go1_getup/policy.pt`+ writes `instances/<Env>.json` (with its t = 0 state hash and the numbers the texts quote), `oracles/<Env>.npy` (the+ reference rows, float32-exact) and `selection/<Env>.json` (every candidate tried and why it was skipped).+4. **Tasks**: `python3 generate.py` (and `--check`).++`shared/rcb_quadruped.py` is the one simulator module: the privileged tooling, the verifier's replay CLI and the+standard service's simulator (`shared/standard/server.py`, the 2.2 adapter).diff --git a/scripts/mujoco-playground/generate.py b/scripts/mujoco-playground/generate.pynew file mode 100644index 0000000000..9b6eda0083--- /dev/null+++ b/scripts/mujoco-playground/generate.py@@ -0,0 +1,511 @@+#!/usr/bin/env python3+"""Generate MuJoCo Playground's quadruped tasks: tasks/mujoco_playground_<env>-privileged and ...-standard.++ python3 scripts/mujoco-playground/generate.py # every instance in instances/+ python3 scripts/mujoco-playground/generate.py --check # exit 1 if tasks/ differs from what this would write++Inputs: instances/<Env>.json (the frozen instance with the numbers the texts quote: make_instances.py, then+select_instances.py), oracles/<Env>.npy (the reference rows), the templates in templates/, the shared sources in shared/+and the eai-standard/2.2 layer with the standard client's base image and pins (scripts/eai_standard/), all copied byte+for byte. Each task directory is written from scratch and finished with scripts/task_conventions.py (normalize,+PROTOCOL v1.0.1); a quadruped task directory this does not write is removed. Only the standard library is needed.+The four manipulation tasks of this benchmark (tasks/mujoco_playground_{aloha,panda}_*) are not generated here.+"""+import filecmp+import json+import re+import shutil+import sys+import tempfile+from pathlib import Path++HERE = Path(__file__).resolve().parent+ROOT = HERE.parents[1]+sys.path.insert(0, str(ROOT / "scripts"))+from task_conventions import normalize # noqa: E402 (protocol v1.0.1 conventions)++TASKS_DIR = ROOT / "tasks"+SHARED = HERE / "shared"+TEMPLATES = HERE / "templates"+LAYER = ROOT / "scripts/eai_standard"+IMAGE = "ghcr.io/mll-lab-nu/eai-mujoco:0.1.3" # images/mujoco: 0.1.3 = 0.1.2 + the quadruped assets (prepare_assets.sh)+_ENV = dict(ln.split("=", 1) for ln in (LAYER / "client.env").read_text().splitlines() if "=" in ln and ln[0] != "#")+CLIENT_IMAGE = _ENV["CLIENT_IMAGE"].strip()+AUTHOR, ORG = "Changhe Chen", "MLL Lab"+HOSTS = [+ "chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com",+ "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com",+] # fmt: skip+PREFIXES = ("mujoco_playground_go1_", "mujoco_playground_spot_", "mujoco_playground_barkour_")+CAMERAS = {"go1": "`track`, `side`, `back`, `top` (they follow the robot)", "spot": "`track`, `side`, `back`, `top` (they follow the robot)",+ "barkour": "`track` (follows the robot) and `realsense/rgb` (on its head)"}+GO1_FALL = "the trunk's up axis pointing below the horizon (the z component of the IMU frame's z axis negative)"+SPOT_FALL = "the trunk tilted by more than about 32 deg (the z component of the IMU frame's z axis below 0.85)"+BARKOUR_FALL = ("the trunk's up axis pointing below the horizon, a joint outside its box (abduction [-0.7, 0.52], hip "+ "[-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m")+GO1_RESAMPLE = "a new draw after Exp(1) x 5 s; a draw may keep a component"+SPOT_RESAMPLE = "a new draw every 201 control steps, zero with probability 0.1"+BARKOUR_RESAMPLE = "a new draw after 501 control steps"+GO1_JOY_DIFF = ("Torque limits and a soft PD drive leave little margin; Playground trains a neural policy with 200 M steps of "+ "PPO for this.")+GO1_JOY_REF = ("MuJoCo Playground's own Go1 joystick policy (`experimental/sim2sim/onnx/go1_policy.onnx` @4057c14, not in the "+ "image) run closed loop on this instance with the observation of Playground's `play_go1_joystick.py`")+ROBOTS = {+ "go1": {"name": "Unitree Go1", "short": "Go1", "tax": "unitree-go1", "menagerie": "unitree_go1", "feet": "FR, FL, RR, RL",+ "joints": "FR, FL, RR, RL legs, each hip (abduction), thigh (hip pitch), calf (knee)"},+ "barkour": {"name": "Google Barkour vB", "short": "Barkour", "tax": "google-barkour-vb", "menagerie": "google_barkour_vb",+ "feet": "foot_front_left, foot_hind_left, foot_front_right, foot_hind_right",+ "joints": "front-left, hind-left, front-right, hind-right legs, each abduction, hip, knee"},+ "spot": {"name": "Boston Dynamics Spot", "short": "Spot", "tax": "boston-dynamics-spot",+ "menagerie": "boston_dynamics_spot", "feet": "FL, FR, HL, HR",+ "joints": "FL, FR, HL, HR legs, each hx (abduction), hy (hip pitch), kn (knee)"},+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "kp": 35, "kd": 0.5, "sim_dt": 0.004,+ "dt": 0.02, "start": "random", "fall": GO1_FALL, "resample": GO1_RESAMPLE,+ "difficulty": GO1_JOY_DIFF, "reference": GO1_JOY_REF,+ "xml": "locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "kp": 35, "kd": 0.5, "sim_dt": 0.004,+ "dt": 0.02, "start": "random", "fall": GO1_FALL, "resample": GO1_RESAMPLE,+ "difficulty": GO1_JOY_DIFF, "reference": GO1_JOY_REF,+ "xml": "locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "kp": 35, "kd": 0.5, "sim_dt": 0.004, "min_h": 0.22, "stand_h": "0.255-0.26",+ "lie_h": 0.15, "drop": "0.5 m in a random orientation with random joint angles and a random base velocity",+ "xml": "locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml",+ "difficulty": "A trained policy reaches a level crouch easily; standing up from it at the right moment is the rest.",+ "reference": "A policy trained here on Playground's Go1Getup reward (PPO on the CPU, `scripts/mujoco-playground/"+ "train/`, not in the image) turns the robot belly-down and level; then the joint targets go "+ "linearly to the `home` pose in 1 s and hold until the check completes"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "kp": 400, "kd": 20, "sim_dt": 0.004, "min_h": 0.40, "stand_h": "0.44",+ "lie_h": 0.38, "drop": "1 m in a random orientation with random joint angles (no base velocity)",+ "xml": "locomotion/spot/xmls/scene_mjx_flat_terrain.xml",+ "difficulty": "Spot's trunk alone weighs 33 kg and its legs are long: a turn has to be timed against gravity.",+ "reference": "A policy trained here on Playground's SpotGetup reward (PPO on the CPU, `scripts/mujoco-"+ "playground/train/`, not in the image), run closed loop until the check completes"},+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "kp": 300, "kd": 1, "kv": 20,+ "sim_dt": 0.004, "dt": 0.02, "start": "home", "fall": SPOT_FALL, "resample": SPOT_RESAMPLE,+ "xml": "locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml",+ "difficulty": "Spot is large and heavy, and Playground stops the episode once its trunk tilts "+ "by about 32 deg, so the gait has to stay level.",+ "reference": "A policy trained here on Playground's SpotFlatTerrainJoystick reward (PPO on the "+ "CPU, `scripts/mujoco-playground/train/`, not in the image)"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "kp": 400, "kd": 10, "kv": 20,+ "sim_dt": 0.004, "dt": 0.02, "start": "home", "fall": SPOT_FALL, "resample": SPOT_RESAMPLE,+ "gait": True, "xml": "locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml",+ "difficulty": "On top of the velocity commands the feet have to follow a commanded gait: "+ "which feet swing together, at a fixed frequency and to a commanded height.",+ "reference": "A policy trained here on Playground's SpotJoystickGaitTracking reward (PPO on "+ "the CPU, `scripts/mujoco-playground/train/`, not in the image), with the "+ "command added to its observation (`train/qenv.py` SpotJoystickGaitTrackingCmd: "+ "Playground's observation leaves the command out, so a policy trained on it "+ "marches in place and cannot track the joystick its reward asks for)"},+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "kp": 35, "kd": 0.5239, "kv": 0.5,+ "sim_dt": 0.002, "dt": 0.01, "start": "home", "fall": BARKOUR_FALL, "resample": BARKOUR_RESAMPLE,+ "pushes": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "difficulty": "Random pushes on the torso come at fixed but unannounced times; the gait has to "+ "absorb them without a joint leaving its box.",+ "reference": "A policy trained here on Playground's BarkourJoystick reward, pushes included (PPO on "+ "the CPU, `scripts/mujoco-playground/train/`, not in the image)"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "kp": 35, "kd": 0.5, "sim_dt": 0.004, "min_h": 0.40,+ "pose": "handstand", "on": "front", "air": "hind (RR, RL)", "dir": "down", "z_des": 0.55,+ "xml": "locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "kp": 35, "kd": 0.5, "sim_dt": 0.004, "min_h": 0.40,+ "pose": "footstand", "on": "hind", "air": "front (FR, FL)", "dir": "up", "z_des": 0.53, "hind": True,+ "train_note": " with three training-only changes (`train/qenv.py` Go1FootstandStrict3): this task's "+ "hind-leg termination (with Playground's rule alone it learns to sit on a hind hip), half "+ "of the episodes starting in Playground's `footstand` keyframe, and a steeper height reward "+ "(with Playground's it settles in a squat at 0.2 m)",+ "xml": "locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+}+SETTLE, LIN_TOL, YAW_TOL, HOLD, TILT, POSE_HOLD, POSE_TOL, GAIT_TOL = 25, 0.2, 0.3, 25, 10, 100, 30, 0.05++PRIV_ENV_DOCKERFILE = f"""# MuJoCo Playground quadruped task (privileged): plain MuJoCo with Playground's and Menagerie's assets+# (images/mujoco/prepare_assets.sh), the task's tooling and its frozen instance.+FROM {IMAGE}+COPY instance.json /app/instance.json+COPY rcb_quadruped.py /opt/tools/rcb_quadruped.py+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /app+"""+PRIV_TESTS_DOCKERFILE = f"""# Separate verifier sandbox (PROTOCOL §4): the same image with the verifier's own copies of the tooling and the frozen+# instance. Nothing the agent did in its container reaches this one: Harbor uploads only the declared artifacts.+FROM {IMAGE}+COPY grade.py instance.json rcb_quadruped.py test.sh /tests/+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier+ENV PYTHONPATH=/tests+WORKDIR /tests+"""+STD_ENV_DOCKERFILE = f"""# Standard mode: the agent container has NO simulator and no Playground code, only Python and the client, on the shared+# pinned client base with the shared pins (scripts/eai_standard/client.env, client-requirements.txt).+FROM {CLIENT_IMAGE}+COPY client-requirements.txt /tmp/client-requirements.txt+RUN pip install --no-cache-dir -r /tmp/client-requirements.txt+COPY rcb_client.py rcb1.py /opt/tools/+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /app+"""+STD_TESTS_DOCKERFILE = f"""# Separate verifier sandbox: grades the sim service's own artifacts; needs nothing but python (the shared client base).+FROM {CLIENT_IMAGE}+COPY test.sh /tests/test.sh+COPY grade.py /tests/grade.py+RUN chmod +x /tests/test.sh+"""+STD_COMPOSE = f"""# Standard mode: the simulator runs in the `sim` sidecar (the agent cannot open it); the agent only reaches port 8000.+# No `expose`/`ports` on sim: under Harbor's egress control it shares main's network namespace (localhost:8000).+# CPU only: MuJoCo physics and rendering (EGL when a GPU is there, else OSMesa); no GPU reservation.+# Crash recovery (docs/STANDARD_MODE_2_2.md §13): run.sh exits non-zero when the service crashes, compose restarts the+# container (same container, same /data) and the service replays its journal into the same episode, never a reset.+services:+ main:+ depends_on: [sim]+ sim:+ image: {IMAGE}+ volumes:+ - ./sim:/srv:ro+ working_dir: /tmp+ command: sh /srv/run.sh+ restart: on-failure:6 # N >= 3 (PROTOCOL §4.1); a resume continues the episode+ environment:+ RCB_INSTANCE: /srv/instance.json+ RCB_TOOL: /srv/rcb_quadruped.py+ RCB_DATA: /data+ RCB_WALL_CLOCK_S: "3600"+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in about a second+ PYTHONPATH: /srv+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction log+"""+++def snake(env: str) -> str:+ return re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", env).lower()+++def render(template: str, values: dict) -> str:+ text = (TEMPLATES / template).read_text()+ for k, v in values.items():+ text = text.replace("{{" + k + "}}", str(v))+ if "{{" in text:+ raise ValueError(f"{template}: unfilled placeholder near {text[text.index('{{'):][:40]!r}")+ return text+++def reset_dir(d: Path) -> None:+ """A task directory is written from scratch: what is not rendered here does not belong (no results/, PROTOCOL D3)."""+ if d.exists():+ shutil.rmtree(d)+ d.mkdir(parents=True)+++def put(path: Path, text: str | None = None, src: Path | None = None, mode: int = 0o644) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ if src is not None:+ shutil.copyfile(src, path)+ else:+ path.write_text(text)+ path.chmod(mode)+++def f(x, d=2) -> str:+ return f"{x:.{d}f}".rstrip("0").rstrip(".") if isinstance(x, float) else str(x)+++def schedule_table(inst: dict, dt: float = 0.02) -> str:+ rows = ["| from (s) | vx (m/s) | vy (m/s) | yaw rate (rad/s) |", "|---:|---:|---:|---:|"]+ for c in inst["commands"]:+ rows.append(f"| {c['start_step'] * dt:.2f} | {c['vx']:+.3f} | {c['vy']:+.3f} | {c['wz']:+.3f} |")+ return "\n".join(rows)+++def gains(e: dict) -> str:+ """The drive as Playground sets it: Kp as the actuators' gain, Kd as joint damping (an actuator's own kv stays)."""+ kv = f", plus the actuators' own damping of {e['kv']:g} N m s/rad" if e.get("kv") else ""+ return f"kp = {e['kp']:g} N m/rad, joint damping {e['kd']:g} N m s/rad{kv}"+++def selection_text(env: str) -> str:+ sel = json.loads((HERE / "selection" / f"{env}.json").read_text())["candidates"]+ chosen = next(c["seed"] for c in sel if c.get("chosen"))+ skipped = [f"{c['seed']}: {c['skipped']}" for c in sel if c.get("skipped")]+ return f"seed {chosen}" + (f"; skipped {'; '.join(skipped)}" if skipped else "; the first candidate")+++def values(env: str, inst: dict) -> dict:+ e = ENVS[env]+ rb = ROBOTS[e["robot"]]+ fa = inst["facts"]+ H = int(inst["horizon"])+ v = {+ "name": f"mujoco_playground_{snake(env)}", "env": env, "kind": e["kind"], "seed": inst["seed"],+ "robot_name": rb["name"], "robot_tax": rb["tax"], "menagerie": rb["menagerie"], "feet": rb["feet"],+ "joint_text": rb["joints"], "foot0": rb["feet"].split(", ")[0], "task": inst["text"], "task_toml": json.dumps(inst["text"])[1:-1],+ "kp": e["kp"], "kd": e["kd"], "sim_dt": e["sim_dt"], "dt": f"{e.get('dt', 0.02):g}",+ "substeps": round(e.get("dt", 0.02) / e["sim_dt"]), "xml": e["xml"], "gains": gains(e),+ "cameras": CAMERAS[e["robot"]], "n_rows": fa["reference_rows"], "selection": selection_text(env), "author": AUTHOR,+ "org": ORG, "allowed_hosts": ", ".join(json.dumps(h) for h in HOSTS),+ }+ if e["kind"] == "joystick":+ rough = "Rough" in env+ dt = e["dt"]+ T = H * dt+ ground = ("The ground is Playground's rough terrain: a 20 x 20 m heightfield (`hfield.png`, up to 5 cm high) "+ "centred on the world origin, with nothing beyond its edge." if rough else "The ground is flat.")+ if e["start"] == "random":+ start = (f"The robot starts at Playground's `home` pose, its base moved to ({f(fa['start_xy_m'][0], 3)}, "+ f"{f(fa['start_xy_m'][1], 3)}) m and turned to a yaw of {f(fa['start_yaw_deg'], 1)} deg, with a random "+ "base velocity (Playground's reset).")+ else:+ start = "The robot starts standing still at Playground's `home` pose (this environment's reset does not move it)."+ quirk = (" One control step is 10 ms of simulated time: Playground's Barkour environment keeps Menagerie's 2 ms "+ "timestep and takes 5 substeps." if dt != 0.02 else "")+ sched = (f"For {T:g} s ({H} control steps) it is given this command schedule, drawn by Playground's command "+ f"process ({e['resample']}). A command is a velocity in the robot's own frame: vx forward, vy to the left "+ "(the trunk's planar velocity), and the yaw rate:")+ extra, extra_std, gait_rule, gait_std = "", "", "", ""+ if e.get("pushes"):+ ks = inst["kicks"]+ fmax = max(0.5 * fa["torso_mass_kg"] * k["velocity_mps"] / (k["duration_steps"] * 0.02) for k in ks)+ extra = (f"\n\nThe torso is pushed {len(ks)} times (Playground's kicks): each push lasts "+ f"{ks[0]['duration_steps']} control steps, a half-sine of horizontal force up to {fmax:.0f} N in a random "+ "direction; `instance.json` (`kicks`) lists when and where, and `s.push_force(t)` gives the force of "+ "control step t.")+ extra_std = (f"\n\nThe torso is pushed {len(ks)} times at moments you are not told (Playground's kicks: "+ f"half-sine pushes of up to {fmax:.0f} N lasting {ks[0]['duration_steps'] * dt:g} s, in random "+ "horizontal directions).")+ if e.get("gait"):+ g = inst["gait"]+ extra = extra_std = (f"\n\nThe feet must also follow a **{g['name']}** gait at {g['frequency_hz']:.2f} Hz with a "+ f"swing height of {g['foot_height_m']:.3f} m: foot i's target height at control step t is "+ "Playground's `gait.get_rz(wrap(phase0[i] + t * phase_dt), foot_height)` (a cubic Bezier up "+ f"over the first half of the phase, then down), with phase0 = {[round(x, 4) for x in g['phase0']]} "+ f"(feet {rb['feet']}) and phase_dt = {g['phase_dt']:.4f} rad.")+ gait_rule = (f"; and the mean, over the same steps, of the feet's RMS height error to their target heights is "+ f"at most {GAIT_TOL} m")+ gait_std = f", and a mean RMS foot-height error to the gait's targets of at most {GAIT_TOL} m"+ v.update(+ episode_md=f"## The episode\n{start} {ground}{quirk}\n{sched}\n\n{schedule_table(inst, dt)}{extra}\n\n`s.commands` "+ "holds the schedule per control step; `s.state()[\"command\"]` is the current one.",+ episode_md_std=f"## The episode\n{start} {ground}{quirk}\n{sched}\n\n{schedule_table(inst, dt)}{extra_std}\n\nThe "+ "same schedule is `spec[\"command_schedule\"]`; every response's `meta[\"command_now\"]` is the "+ "current command." + (" The gait is `spec[\"gait\"]`." if e.get("gait") else ""),+ success_md=(f"The episode lasts exactly {H} control steps: the trajectory must have T = {H} rows. Success iff\n"+ f"1. the robot never meets Playground's termination rule for this environment: {e['fall']}; and\n"+ f"2. in every command segment, over its control steps after the first {SETTLE} ({SETTLE * dt:g} s): the "+ f"mean planar velocity error |v_xy - cmd_xy| is at most {LIN_TOL} m/s, with v the IMU's velocimeter "+ f"(`local_linvel`, trunk frame), and the mean yaw-rate error |w_z - cmd_wz| at most {YAW_TOL} "+ f"rad/s, with w the IMU's gyro{gait_rule}.\n\n`s.check()` reports `fell_at`, each segment's errors "+ "and `success`."),+ rows_rule=f"T = {H} (the whole schedule)",+ state_cmd=", command", spec_cmd=", command_schedule" + (", gait" if e.get("gait") else ""),+ std_end=(f"after {H} control steps, the whole schedule (`spec[\"max_control_steps\"]`, counted by "+ f"`meta[\"control_steps\"]`), when the robot meets its termination rule ({e['fall']}: a failure), "+ "when you submit `done`, or when your time is up (before the end of the schedule, both are failures)."),+ std_success=(f"is judged on the whole schedule: no termination, and in every command segment, after its first "+ f"{SETTLE} control steps, a mean |v_xy - cmd_xy| of at most {LIN_TOL} m/s (`imu_linvel`) and a mean "+ f"|w_z - cmd_wz| of at most {YAW_TOL} rad/s (`imu_gyro`){gait_std}."),+ task_detail=(f"For {T:g} s the robot gets a joystick command schedule ({len(inst['commands'])} segments: "+ "planar velocity and yaw rate in its own frame) and must track it without falling over."+ + (" The ground is a 20 x 20 m heightfield with bumps up to 5 cm." if rough else "")+ + (f" Its torso is pushed {len(inst['kicks'])} times." if e.get("pushes") else "")+ + (f" Its feet must follow a {inst['gait']['name']} gait." if e.get("gait") else "")),+ grading_toml=f"velocity tracking over the whole {T:g} s schedule without a fall (two fresh-process replays).",+ difficulty=(f"Velocity tracking for {T:g} s: the agent has to make a 12-joint quadruped walk (a gait, not one "+ "motion) and steer it through the schedule's changes of speed, direction and turning rate, and an "+ f"open-loop trajectory of {H} steps only works if it is computed against the simulator. "+ f"{e['difficulty']}"+ + (" On the heightfield the feet land at unpredictable heights: Playground's own Go1 policy, which "+ "made the reference, falls or loses track on some of the candidate seeds (select_instances.py "+ "skips them)." if rough else "")),+ reference=(f"{e['reference']}, its targets recorded (`scripts/mujoco-playground/oracle.py`): worst segment errors "+ f"{fa['reference_worst_lin_err']:.3f} m/s and {fa['reference_worst_yaw_err']:.3f} rad/s"+ + (f", foot height {fa['reference_worst_gait_err']:.3f} m" if e.get("gait") else "") + "."),+ check_short=(f"Oracle: success, worst segment errors {fa['reference_worst_lin_err']:.3f} m/s and "+ f"{fa['reference_worst_yaw_err']:.3f} rad/s."),+ oracle_end=f"after the {H} steps of the schedule, with success",+ instance_extra=f" and Playground's command process over the {H} steps" + (" (and its pushes)" if e.get("pushes") else ""),+ expert_hours="3.0", expert_hours_std="4.0",+ )+ elif e["kind"] == "getup":+ name = rb["short"]+ v.update(+ episode_md=(f"## The episode\nPlayground's reset dropped the robot from {e['drop']}, then let it settle for "+ f"0.5 s with its joints held: at t = 0 it lies with its trunk tilted {f(fa['start_tilt_deg'], 1)} deg "+ f"from upright. You have {H} control steps ({H * 0.02:g} s)."),+ episode_md_std=(f"## The episode\nThe robot was dropped from {e['drop']} and settled for 0.5 s with its joints "+ f"held: at the start it lies with its trunk tilted {f(fa['start_tilt_deg'], 1)} deg from upright. "+ f"You have {H} control steps ({H * 0.02:g} s)."),+ success_md=(f"Success iff the trajectory (at most {H} rows) ends with {HOLD} control steps in a row (0.5 s) after "+ f"each of which the trunk is upright, tilted at most {TILT} deg (the angle between the IMU frame's z "+ f"axis and world z), and the IMU is at least {e['min_h']} m above the floor (the {name} stands at "+ f"{e['stand_h']} m; lying down is below {e['lie_h']} m). End the trajectory once that holds. "+ "`s.check()` reports the last tilt, height and `success`."),+ rows_rule=f"1 <= T <= {H}",+ state_cmd="", spec_cmd="",+ std_end=(f"the moment the robot has been upright for {HOLD} control steps in a row (success), after {H} control "+ "steps (`spec[\"max_control_steps\"]`, counted by `meta[\"control_steps\"]`), when you submit `done`, or "+ "when your time is up."),+ std_success=(f"is {HOLD} control steps in a row with the trunk within {TILT} deg of upright and the IMU at least "+ f"{e['min_h']} m above the floor (the {name} stands at {e['stand_h']} m), judged after every control "+ "step; when the episode ends otherwise, it is judged on its last control steps."),+ task_detail=(f"It starts lying with its trunk tilted {f(fa['start_tilt_deg'], 1)} deg (Playground's random drop, "+ f"then a 0.5 s settle) and has {H * 0.02:g} s to stand upright at its standing height."),+ grading_toml="an upright stance held for the trajectory's last 0.5 s (two fresh-process replays).",+ difficulty=(f"Recovery from a fall: the robot lies on its side or back and has to turn itself over with its legs "+ f"and then stand up within {H * 0.02:g} s, with the trunk, thighs and calves all in contact with the "+ "floor (full collisions). The motion is whole-body and contact-rich, and a turn that fails leaves "+ f"it on its back. {e['difficulty']}"),+ reference=(f"{e['reference']} (`scripts/mujoco-playground/oracle.py`): upright after {fa['reference_rows']} control "+ f"steps, IMU at {fa['reference_imu_height']:.3f} m."),+ check_short=f"Oracle: success after {fa['reference_rows']} control steps.",+ oracle_end=f"with success after {fa['reference_rows']} control steps",+ instance_extra=" (a drop; the 0.5 s settle runs in the task's own MuJoCo)",+ expert_hours="2.0", expert_hours_std="3.0",+ )+ else:+ pose = (f"the trunk's forward axis (the IMU frame's x axis) within {POSE_TOL} deg of straight {e['dir']}, the IMU "+ f"at least {e['min_h']} m above the floor, and the {e['air']} feet off the ground")+ pose_is = (f"the trunk's forward axis (the IMU frame's x axis) is within {POSE_TOL} deg of straight {e['dir']}, the "+ f"IMU is at least {e['min_h']} m above the floor and the {e['air']} feet are off the ground")+ term = ("the trunk's up axis below -0.25 (z component of the IMU frame's z axis), or any part of a front leg other "+ "than its foot (thigh, calf, hip) touching the floor"+ + (" (Playground's rule as its code reads it), or the same for a hind leg (the list its Footstand sets "+ "up but never reads; without it, sitting on a hind hip would count)" if e.get("hind") else ""))+ v.update(+ episode_md=(f"## The episode\nThe robot starts at Playground's `home` pose, its base moved to "+ f"({f(fa['start_xy_m'][0], 3)}, {f(fa['start_xy_m'][1], 3)}) m, turned to a yaw of "+ f"{f(fa['start_yaw_deg'], 1)} deg, with a random base velocity (Playground's reset). You have {H} "+ f"control steps ({H * 0.02:g} s)."),+ episode_md_std=(f"## The episode\nThe robot starts standing at Playground's `home` pose with a random base "+ f"velocity (Playground's reset). You have {H} control steps ({H * 0.02:g} s)."),+ success_md=(f"Success iff the trajectory (at most {H} rows) ends with {POSE_HOLD} control steps in a row (2 s) "+ f"after each of which {pose_is}; and no control step before its end meets Playground's termination "+ f"rule: {term}. End the trajectory once the hold is complete. `s.check()` reports `fell_at`, the "+ "last pose angle and height, and `success`."),+ rows_rule=f"1 <= T <= {H}",+ state_cmd="", spec_cmd="",+ std_end=(f"the moment the pose has been held for {POSE_HOLD} control steps in a row (success), when the robot "+ f"meets the termination rule ({term}: a failure), after {H} control steps (`spec[\"max_control_steps\"]`), "+ "when you submit `done`, or when your time is up."),+ std_success=(f"is {POSE_HOLD} control steps in a row (2 s) with {pose}, without a termination before; judged "+ "after every control step."),+ task_detail=(f"From standing, it has {H * 0.02:g} s to get into a {e['pose']} on its {e['on']} legs and hold it "+ f"for 2 s (Playground's {e['pose']} reward aims at the IMU {e['z_des']} m high)."),+ grading_toml=f"a {e['pose']} held for the trajectory's last 2 s, without a termination (two fresh-process replays).",+ difficulty=(f"Dynamic balance on two legs: the robot has to throw its weight onto its {e['on']} legs, lift the "+ f"other pair and then balance an inverted, top-heavy body on two small feet with 35 N m/rad position "+ "drives, correcting continuously; a front leg touching the floor or a tip-over ends it. Playground's "+ f"{e['pose']} is trained with 100 M steps of PPO."),+ reference=(f"A policy trained here on Playground's Go1{e['pose'].capitalize()} reward (PPO on the CPU, "+ f"`scripts/mujoco-playground/train/`, not in the image){e.get('train_note', '')}, run closed loop with "+ "Playground's action semantics (targets accumulate) until the hold completes "+ "(`scripts/mujoco-playground/oracle.py`): "+ f"{fa['reference_rows']} control steps, pose angle {fa['reference_pose_angle_deg']:.1f} deg and IMU at "+ f"{fa['reference_imu_height']:.3f} m at the end."),+ check_short=f"Oracle: success after {fa['reference_rows']} control steps.",+ oracle_end=f"with success after {fa['reference_rows']} control steps",+ instance_extra=" (xy, yaw and base velocity)",+ expert_hours="3.0", expert_hours_std="4.0",+ )+ return v+++def make(env: str, out: Path) -> tuple[Path, Path]:+ inst_path = HERE / "instances" / f"{env}.json"+ inst = json.loads(inst_path.read_text())+ v = values(env, inst)+ oracle = HERE / "oracles" / f"{env}.npy"++ p = out / f"{v['name']}-privileged"+ reset_dir(p)+ put(p / "task.toml", render("task.toml", v))+ put(p / "instruction.md", render("instruction.md", v))+ put(p / "README.md", render("README.md", v))+ put(p / "environment/Dockerfile", PRIV_ENV_DOCKERFILE)+ put(p / "environment/instance.json", src=inst_path)+ put(p / "environment/rcb_quadruped.py", src=SHARED / "rcb_quadruped.py")+ put(p / "tests/Dockerfile", PRIV_TESTS_DOCKERFILE)+ put(p / "tests/test.sh", src=SHARED / "test.sh", mode=0o755)+ put(p / "tests/grade.py", src=SHARED / "grade.py")+ put(p / "tests/rcb_quadruped.py", src=SHARED / "rcb_quadruped.py")+ put(p / "tests/instance.json", src=inst_path)+ put(p / "solution/solve.sh", src=SHARED / "solve_privileged.sh", mode=0o755)+ put(p / "solution/oracle_replay.py", src=SHARED / "oracle_privileged.py")+ put(p / "solution/oracle.npy", src=oracle)++ s = out / f"{v['name']}-standard"+ reset_dir(s)+ put(s / "task.toml", render("standard/task.toml", v))+ put(s / "instruction.md", render("standard/instruction.md", v))+ put(s / "README.md", render("standard/README.md", v))+ put(s / "environment/Dockerfile", STD_ENV_DOCKERFILE)+ put(s / "environment/docker-compose.yaml", STD_COMPOSE)+ put(s / "environment/client-requirements.txt", src=LAYER / _ENV.get("CLIENT_REQUIREMENTS", "client-requirements.txt").strip())+ put(s / "environment/rcb_client.py", src=LAYER / "rcb_client.py")+ put(s / "environment/rcb1.py", src=LAYER / "rcb1.py")+ for name in ("rcb_limited.py", "rcb1.py"):+ put(s / "environment/sim" / name, src=LAYER / name)+ put(s / "environment/sim/run.sh", src=LAYER / "run.sh", mode=0o755)+ put(s / "environment/sim/server.py", src=SHARED / "standard/server.py")+ put(s / "environment/sim/finalize.sh", src=SHARED / "standard/finalize.sh", mode=0o755)+ put(s / "environment/sim/rcb_quadruped.py", src=SHARED / "rcb_quadruped.py")+ put(s / "environment/sim/instance.json", src=inst_path)+ put(s / "tests/Dockerfile", STD_TESTS_DOCKERFILE)+ put(s / "tests/test.sh", src=SHARED / "standard/test.sh", mode=0o755)+ put(s / "tests/grade.py", src=SHARED / "standard/grade.py")+ put(s / "solution/solve.sh", src=SHARED / "standard/solve.sh", mode=0o755)+ put(s / "solution/oracle_replay.py", src=SHARED / "standard/oracle_replay.py")+ put(s / "solution/oracle.npy", src=oracle)+ normalize(p)+ normalize(s)+ return p, s+++def render_all(out: Path) -> list[str]:+ done = []+ for inst in sorted((HERE / "instances").glob("*.json")):+ done += [d.name for d in make(inst.stem, out)]+ return done+++def ours(d: Path) -> bool:+ return d.is_dir() and d.name.startswith(PREFIXES)+++def check() -> int:+ """tasks/ must be exactly what render_all writes (contents and modes), with no other quadruped task directory."""+ with tempfile.TemporaryDirectory() as tmp:+ names = set(render_all(Path(tmp)))+ have = {d.name for d in TASKS_DIR.iterdir() if ours(d)}+ bad = sorted(have ^ names)+ for name in sorted(names & have):+ stack = [filecmp.dircmp(TASKS_DIR / name, Path(tmp) / name, ignore=["__pycache__"])]+ while stack:+ c = stack.pop()+ diff = filecmp.cmpfiles(c.left, c.right, c.common_files, shallow=False)[1]+ modes = [x for x in c.common_files if (Path(c.left) / x).stat().st_mode != (Path(c.right) / x).stat().st_mode]+ if c.left_only or c.right_only or c.funny_files or diff or modes:+ bad.append(name)+ break+ stack += list(c.subdirs.values())+ for name in sorted(set(bad)):+ print(f"FAIL tasks/{name}: differs from scripts/mujoco-playground/generate.py (re-run it)")+ if not bad:+ print(f"{len(names)} task directories match")+ return 1 if bad else 0+++def main(args: list[str]) -> int:+ if args == ["--check"]:+ return check()+ names = render_all(TASKS_DIR)+ for d in sorted(TASKS_DIR.iterdir()):+ if ours(d) and d.name not in names:+ shutil.rmtree(d)+ print(f"removed stale {d.relative_to(ROOT)}")+ print(f"generated {len(names)} task directories")+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/scripts/mujoco-playground/instances/BarkourJoystick.json b/scripts/mujoco-playground/instances/BarkourJoystick.jsonnew file mode 100644index 0000000000..4aba72fed1--- /dev/null+++ b/scripts/mujoco-playground/instances/BarkourJoystick.json@@ -0,0 +1,192 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "BarkourJoystick",+ "seed": 2,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 0.2800000011920929,+ 1.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.5,+ 1.0,+ 0.0,+ 0.5,+ 1.0,+ 0.0,+ 0.5,+ 1.0,+ 0.0,+ 0.5,+ 1.0+ ],+ "qvel0": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 0.4594014286994934,+ "vy": 0.22121715545654297,+ "wz": 0.016074633225798607+ },+ {+ "start_step": 501,+ "vx": 0.0903209000825882,+ "vy": -0.3885873854160309,+ "wz": 0.6428412795066833+ }+ ],+ "kicks": [+ {+ "start_step": 80,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.8203420823732267,+ -0.5718731221936891+ ]+ },+ {+ "start_step": 160,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.788163164239454,+ -0.6154663488250608+ ]+ },+ {+ "start_step": 240,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.9131765428086646,+ -0.4075642301085992+ ]+ },+ {+ "start_step": 320,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.3721731613746436,+ 0.9281633142677013+ ]+ },+ {+ "start_step": 400,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.9775782732872876,+ -0.2105723619011887+ ]+ },+ {+ "start_step": 480,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.8350665582365031,+ 0.5501489283049099+ ]+ },+ {+ "start_step": 581,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.7430595752025673,+ 0.6692252742535807+ ]+ },+ {+ "start_step": 661,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.8082263256570713,+ 0.5888719780350138+ ]+ },+ {+ "start_step": 741,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.22144795284761612,+ -0.9751721920664063+ ]+ },+ {+ "start_step": 821,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.9990854215709072,+ -0.042758863461072875+ ]+ },+ {+ "start_step": 901,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.821963866092448,+ -0.5695396411474414+ ]+ },+ {+ "start_step": 981,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.4999078076804545,+ -0.8660786245024881+ ]+ }+ ],+ "text": "Make Google's Barkour quadruped follow the joystick command schedule for the whole 10 s episode, through random pushes, without falling over.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": 0.0,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.22,+ "reference_rows": 1000,+ "torso_mass_kg": 14.496,+ "reference_worst_lin_err": 0.0329,+ "reference_worst_yaw_err": 0.0276+ },+ "state_sha": "90c7b858534f",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s), when its pushes (Barkour) are null or\n weak (peak under 20% of the torso's weight), or when the reference trajectory (oracle.py) fails the task's\n success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 3+ }+}\ No newline at end of filediff --git a/scripts/mujoco-playground/instances/Go1Footstand.json b/scripts/mujoco-playground/instances/Go1Footstand.jsonnew file mode 100644index 0000000000..51305c694d--- /dev/null+++ b/scripts/mujoco-playground/instances/Go1Footstand.json@@ -0,0 +1,68 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1Footstand",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ -0.3957096338272095,+ -0.1560124158859253,+ 0.27799999713897705,+ 0.2572470009326935,+ 0.0,+ 0.0,+ -0.9663457870483398,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842+ ],+ "qvel0": [+ -0.4893399477005005,+ 0.021045565605163574,+ 0.45396435260772705,+ -0.16251015663146973,+ -0.030068635940551758,+ -0.1645064353942871,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "text": "Make the Unitree Go1 stand up on its hind legs, nose up, front legs in the air, and balance there for 2 s.",+ "facts": {+ "start_xy_m": [+ -0.396,+ -0.156+ ],+ "start_yaw_deg": -150.2,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.272,+ "reference_rows": 113,+ "torso_mass_kg": 12.743,+ "reference_imu_height": 0.5408,+ "reference_pose_angle_deg": 9.62+ },+ "state_sha": "edd665f20ded",+ "horizon": 500,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s), when its pushes (Barkour) are null or\n weak (peak under 20% of the torso's weight), or when the reference trajectory (oracle.py) fails the task's\n success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/scripts/mujoco-playground/instances/Go1Getup.json b/scripts/mujoco-playground/instances/Go1Getup.jsonnew file mode 100644index 0000000000..094f52130b--- /dev/null+++ b/scripts/mujoco-playground/instances/Go1Getup.json@@ -0,0 +1,68 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1Getup",+ "seed": 5,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 0.5,+ -0.6548677086830139,+ 0.061879757791757584,+ 0.69452303647995,+ -0.2914724051952362,+ -0.6954456567764282,+ -0.038879625499248505,+ -2.5283195972442627,+ -0.7643543481826782,+ 1.2582777738571167,+ -1.5951141119003296,+ 0.12876635789871216,+ 4.084576606750488,+ -1.8947221040725708,+ 0.6868290305137634,+ 0.7969384789466858,+ -2.1358203887939453+ ],+ "qvel0": [+ -0.41757500171661377,+ 0.08125269412994385,+ 0.36997389793395996,+ -0.26620352268218994,+ 0.33868932723999023,+ -0.43405938148498535,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "dropped": true,+ "text": "The Unitree Go1 has fallen over. Make it get up and stand upright at its standing height.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": -312.0,+ "start_tilt_deg": 110.0,+ "start_imu_height_m": 0.295,+ "reference_rows": 136,+ "reference_tilt_deg": 2.34,+ "reference_imu_height": 0.2568+ },+ "state_sha": "c59d44064135",+ "horizon": 300,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.",+ "candidates_tried": 6+ }+}\ No newline at end of filediff --git a/scripts/mujoco-playground/instances/Go1Handstand.json b/scripts/mujoco-playground/instances/Go1Handstand.jsonnew file mode 100644index 0000000000..253a2a549f--- /dev/null+++ b/scripts/mujoco-playground/instances/Go1Handstand.json@@ -0,0 +1,67 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1Handstand",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ -0.3957096338272095,+ -0.1560124158859253,+ 0.27799999713897705,+ 0.2572470009326935,+ 0.0,+ 0.0,+ -0.9663457870483398,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842+ ],+ "qvel0": [+ -0.4893399477005005,+ 0.021045565605163574,+ 0.45396435260772705,+ -0.16251015663146973,+ -0.030068635940551758,+ -0.1645064353942871,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "text": "Make the Unitree Go1 do a handstand: balance on its front legs, nose down, hind legs in the air, for 2 s.",+ "facts": {+ "start_xy_m": [+ -0.396,+ -0.156+ ],+ "start_yaw_deg": -150.2,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.272,+ "reference_rows": 115,+ "reference_imu_height": 0.5314,+ "reference_pose_angle_deg": 13.82+ },+ "state_sha": "edd665f20ded",+ "horizon": 500,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/scripts/mujoco-playground/instances/Go1JoystickFlatTerrain.json b/scripts/mujoco-playground/instances/Go1JoystickFlatTerrain.jsonnew file mode 100644index 0000000000..20aecf51c1--- /dev/null+++ b/scripts/mujoco-playground/instances/Go1JoystickFlatTerrain.json@@ -0,0 +1,93 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1JoystickFlatTerrain",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ -0.49270617961883545,+ -0.4791088104248047,+ 0.27799999713897705,+ 0.32240399718284607,+ 0.0,+ 0.0,+ -0.9466021656990051,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842+ ],+ "qvel0": [+ -0.4173961877822876,+ 0.2807871103286743,+ 0.4382798671722412,+ 0.4672558307647705,+ -0.3059135675430298,+ -0.2901715040206909,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 1.4129691123962402,+ "vy": -0.611178994178772,+ "wz": 0.7116400003433228+ },+ {+ "start_step": 42,+ "vx": -0.2525142431259155,+ "vy": -0.611178994178772,+ "wz": 0.7116400003433228+ },+ {+ "start_step": 238,+ "vx": -0.2525142431259155,+ "vy": -0.611178994178772,+ "wz": 0.0+ },+ {+ "start_step": 298,+ "vx": -0.552196741104126,+ "vy": -0.611178994178772,+ "wz": 0.0+ }+ ],+ "text": "Make the Unitree Go1 follow the joystick command schedule on flat ground for the whole 20 s episode without falling over.",+ "facts": {+ "start_xy_m": [+ -0.493,+ -0.479+ ],+ "start_yaw_deg": -142.4,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.272,+ "reference_rows": 1000,+ "reference_worst_lin_err": 0.0732,+ "reference_worst_yaw_err": 0.0914+ },+ "state_sha": "086e8c16c213",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/scripts/mujoco-playground/instances/Go1JoystickRoughTerrain.json b/scripts/mujoco-playground/instances/Go1JoystickRoughTerrain.jsonnew file mode 100644index 0000000000..dc3a670238--- /dev/null+++ b/scripts/mujoco-playground/instances/Go1JoystickRoughTerrain.json@@ -0,0 +1,111 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1JoystickRoughTerrain",+ "seed": 1,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ -0.09635365009307861,+ 0.04889500141143799,+ 0.3499999940395355,+ 0.5138856768608093,+ 0.0,+ 0.0,+ 0.8578586578369141,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842+ ],+ "qvel0": [+ 0.043613314628601074,+ -0.24152767658233643,+ -0.45936477184295654,+ -0.09444129467010498,+ -0.01504206657409668,+ -0.4573014974594116,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 1.136733055114746,+ "vy": 0.16791878640651703,+ "wz": -0.7027067542076111+ },+ {+ "start_step": 17,+ "vx": 1.136733055114746,+ "vy": 0.0,+ "wz": -0.7027067542076111+ },+ {+ "start_step": 138,+ "vx": -1.078402042388916,+ "vy": -0.701647937297821,+ "wz": 0.0+ },+ {+ "start_step": 548,+ "vx": -1.078402042388916,+ "vy": 0.0,+ "wz": 0.7865484356880188+ },+ {+ "start_step": 594,+ "vx": 0.0,+ "vy": -0.35900041460990906,+ "wz": 0.7865484356880188+ },+ {+ "start_step": 611,+ "vx": 0.0,+ "vy": -0.35900041460990906,+ "wz": 0.0+ },+ {+ "start_step": 674,+ "vx": -0.03617405891418457,+ "vy": 0.0,+ "wz": -0.08692560344934464+ }+ ],+ "text": "Make the Unitree Go1 follow the joystick command schedule on rough terrain (a 20 x 20 m heightfield, up to 5 cm high) for the whole 20 s episode without falling over.",+ "facts": {+ "start_xy_m": [+ -0.096,+ 0.049+ ],+ "start_yaw_deg": 118.2,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.344,+ "reference_rows": 1000,+ "reference_worst_lin_err": 0.0788,+ "reference_worst_yaw_err": 0.1137+ },+ "state_sha": "4e94a33d805a",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.",+ "candidates_tried": 2+ }+}\ No newline at end of filediff --git a/scripts/mujoco-playground/instances/SpotFlatTerrainJoystick.json b/scripts/mujoco-playground/instances/SpotFlatTerrainJoystick.jsonnew file mode 100644index 0000000000..3ea273b2b3--- /dev/null+++ b/scripts/mujoco-playground/instances/SpotFlatTerrainJoystick.json@@ -0,0 +1,100 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "SpotFlatTerrainJoystick",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 0.46000000834465027,+ 1.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842+ ],+ "qvel0": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 0.7129874229431152,+ "vy": 0.045435335487127304,+ "wz": 0.6093337535858154+ },+ {+ "start_step": 201,+ "vx": -0.18540263175964355,+ "vy": -0.40133342146873474,+ "wz": -0.4772922992706299+ },+ {+ "start_step": 402,+ "vx": 0.6049041748046875,+ "vy": 0.11546879261732101,+ "wz": 0.04899191856384277+ },+ {+ "start_step": 603,+ "vx": 0.0,+ "vy": 0.0,+ "wz": 0.0+ },+ {+ "start_step": 804,+ "vx": -0.28104639053344727,+ "vy": -0.7415485382080078,+ "wz": -0.6673171520233154+ }+ ],+ "text": "Make Boston Dynamics Spot follow the joystick command schedule on flat ground for the whole 20 s episode without falling over.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": 0.0,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.46,+ "reference_rows": 1000,+ "torso_mass_kg": 50.34,+ "reference_worst_lin_err": 0.1555,+ "reference_worst_yaw_err": 0.072+ },+ "state_sha": "53128662ae17",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/scripts/mujoco-playground/instances/SpotGetup.json b/scripts/mujoco-playground/instances/SpotGetup.jsonnew file mode 100644index 0000000000..56466186bb--- /dev/null+++ b/scripts/mujoco-playground/instances/SpotGetup.json@@ -0,0 +1,68 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "SpotGetup",+ "seed": 1,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 1.0,+ -0.6340193152427673,+ -0.3534443974494934,+ 0.6828494071960449,+ -0.08253868669271469,+ 0.5247290134429932,+ 0.13331857323646545,+ -1.1727977991104126,+ 0.7449409365653992,+ -0.023556871339678764,+ -2.530365228652954,+ 0.40282249450683594,+ 0.9718838334083557,+ -2.2890756130218506,+ -0.15391281247138977,+ 1.0196685791015625,+ -2.621039390563965+ ],+ "qvel0": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "dropped": true,+ "text": "Boston Dynamics Spot has fallen over. Make it get up and stand upright at its standing height.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": -345.2,+ "start_tilt_deg": 128.4,+ "start_imu_height_m": 0.381,+ "reference_rows": 63,+ "reference_tilt_deg": 0.47,+ "reference_imu_height": 0.4782+ },+ "state_sha": "b569d03708a2",+ "horizon": 300,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 2+ }+}\ No newline at end of filediff --git a/scripts/mujoco-playground/instances/SpotJoystickGaitTracking.json b/scripts/mujoco-playground/instances/SpotJoystickGaitTracking.jsonnew file mode 100644index 0000000000..51247a4914--- /dev/null+++ b/scripts/mujoco-playground/instances/SpotJoystickGaitTracking.json@@ -0,0 +1,114 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "SpotJoystickGaitTracking",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 0.46000000834465027,+ 1.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842+ ],+ "qvel0": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 0.9938757419586182,+ "vy": 0.37067461013793945,+ "wz": 0.44742894172668457+ },+ {+ "start_step": 201,+ "vx": 0.9238066673278809,+ "vy": -0.3616582155227661,+ "wz": -0.32676148414611816+ },+ {+ "start_step": 402,+ "vx": -0.9385867118835449,+ "vy": 0.09156465530395508,+ "wz": 0.44982028007507324+ },+ {+ "start_step": 603,+ "vx": -0.9596819877624512,+ "vy": -0.29509055614471436,+ "wz": 0.5688352584838867+ },+ {+ "start_step": 804,+ "vx": 0.8662233352661133,+ "vy": 0.1854252815246582,+ "wz": -0.2966732978820801+ }+ ],+ "gait": {+ "type": 2,+ "name": "pace",+ "frequency_hz": 3.6585731506347656,+ "foot_height_m": 0.12916938960552216,+ "phase0": [+ 0.0,+ 3.1415927410125732,+ 0.0,+ 3.1415927410125732+ ],+ "phase_dt": 0.45974987745285034+ },+ "text": "Make Boston Dynamics Spot follow the joystick command schedule for the whole 20 s episode with the commanded gait (the feet's swing pattern, frequency and height) without falling over.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": 0.0,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.46,+ "reference_rows": 1000,+ "torso_mass_kg": 50.34,+ "reference_worst_lin_err": 0.1827,+ "reference_worst_yaw_err": 0.1358,+ "reference_worst_gait_err": 0.0383+ },+ "state_sha": "53128662ae17",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s), when its pushes (Barkour) are null or\n weak (peak under 20% of the torso's weight), or when the reference trajectory (oracle.py) fails the task's\n success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/scripts/mujoco-playground/make_instances.py b/scripts/mujoco-playground/make_instances.pynew file mode 100644index 0000000000..8d46b7e0b8--- /dev/null+++ b/scripts/mujoco-playground/make_instances.py@@ -0,0 +1,157 @@+"""Draw a candidate instance per seed with MuJoCo Playground's own code (@4057c14, JAX on the CPU).++ python make_instances.py Go1JoystickFlatTerrain --seeds 0-49 --out cand/+writes cand/<Env>/seed<k>.json with the episode's start (qpos0, qvel0) and, for the joystick tasks, the command schedule.+Needs `pip install -e <playground>` and `jax[cpu]` (not part of any task image). freeze.py then settles and hashes the+start in the task's own MuJoCo, and the selection rule (select.py) picks the instance.++Joystick: `env.reset(PRNGKey(seed))` gives the start and the first command; the schedule continues Playground's command+process exactly as `Joystick.step` draws it (each step: five obs-noise splits of info["rng"], then rng, key1, key2 =+split(rng, 3); when the timer runs out, sample_command(key1) and a new timer round(Exp(key2) * 5 s / dt)). The draws do+not depend on the physics as long as the episode does not terminate, which success requires.+Getup: reset's draws (drop with p = 0.6: random orientation and joints at z = 0.5 m, else home; base velocity U(-0.5,+0.5)) before its settle, which freeze.py runs in the task's MuJoCo."""+import argparse+import json+import os++import jax+import jax.numpy as jp+import numpy as np+from mujoco_playground import registry+++def seeds(s: str) -> list[int]:+ a, _, b = s.partition("-")+ return list(range(int(a), int(b or a) + 1))+++def joystick(env, seed: int, horizon: int) -> dict:+ st = jax.jit(env.reset)(jax.random.PRNGKey(seed))+ rng, cmd, timer = st.info["rng"], st.info["command"], int(st.info["steps_until_next_cmd"])+ segs = [{"start_step": 0, "vx": float(cmd[0]), "vy": float(cmd[1]), "wz": float(cmd[2])}]+ split = jax.jit(jax.random.split, static_argnums=1)+ sample = jax.jit(env.sample_command)+ for t in range(horizon - 1): # after step t, the command for step t + 1+ for _ in range(5): # _get_obs: gyro, gravity, joint_pos, joint_vel, linvel noise+ rng, _ = split(rng, 2)+ rng, key1, key2 = split(rng, 3)+ timer -= 1+ if timer <= 0:+ cmd = sample(key1, cmd)+ timer = int(jp.round(jax.random.exponential(key2) * 5.0 / env.dt))+ c = {"start_step": t + 1, "vx": float(cmd[0]), "vy": float(cmd[1]), "wz": float(cmd[2])}+ if any(c[k] != segs[-1][k] for k in ("vx", "vy", "wz")): # a redraw can keep the command: one segment+ segs.append(c)+ return {"qpos0": np.asarray(st.data.qpos).tolist(), "qvel0": np.asarray(st.data.qvel).tolist(), "commands": segs}+++def seg(t: int, cmd) -> dict:+ return {"start_step": t, "vx": float(cmd[0]), "vy": float(cmd[1]), "wz": float(cmd[2])}+++def spot_joystick(env, seed: int, horizon: int, n_split: int) -> dict:+ """spot/joystick.py (n_split 4) and joystick_gait_tracking.py (3): each step splits info["rng"] into n_split keys,+ the first the next rng, the second the command key; after the step counter passes 200 the command is redrawn."""+ st = jax.jit(env.reset)(jax.random.PRNGKey(seed))+ rng, cmd, count = st.info["rng"], st.info["command"], 0+ segs = [seg(0, cmd)]+ split = jax.jit(jax.random.split, static_argnums=1)+ sample = jax.jit(env.sample_command)+ for t in range(horizon - 1):+ keys = split(rng, n_split)+ rng, cmd_rng = keys[0], keys[1]+ count += 1+ if count > 200:+ cmd, count = sample(cmd_rng), 0+ c = seg(t + 1, cmd)+ if any(c[k] != segs[-1][k] for k in ("vx", "vy", "wz")):+ segs.append(c)+ out = {"qpos0": np.asarray(st.data.qpos).tolist(), "qvel0": np.asarray(st.data.qvel).tolist(), "commands": segs}+ if "gait" in st.info:+ out["gait"] = {"type": int(st.info["gait"]), "name": ["trot", "walk", "pace", "bound", "pronk"][int(st.info["gait"])],+ "frequency_hz": float(st.info["gait_freq"]), "foot_height_m": float(st.info["foot_height"]),+ "phase0": np.asarray(st.info["phase"]).tolist(), "phase_dt": float(st.info["phase_dt"])}+ return out+++def barkour_joystick(env, seed: int, horizon: int) -> dict:+ """barkour/joystick.py: each step splits info["rng"] into (rng, cmd, noise, pert); a push starts when the step+ counter is a nonzero multiple of kick_wait_steps (direction U(0, 2 pi) from the pert key) and lasts+ kick_duration_steps; the counter passes 500 -> a new command and the counter restarts."""+ st = jax.jit(env.reset)(jax.random.PRNGKey(seed))+ rng, cmd, count = st.info["rng"], st.info["command"], 0+ wait, dur = int(st.info["kick_wait_steps"][0]), int(st.info["kick_duration_steps"][0])+ vel = float(st.info["vel_kick"])+ segs, kicks = [seg(0, cmd)], []+ split = jax.jit(jax.random.split, static_argnums=1)+ sample = jax.jit(env.sample_command)+ for t in range(horizon):+ rng, cmd_rng, _noise, pert_rng = split(rng, 4)+ if count % wait == 0 and count != 0:+ ang = float(jax.random.uniform(pert_rng, minval=0.0, maxval=jp.pi * 2))+ kicks.append({"start_step": t, "duration_steps": dur, "velocity_mps": vel,+ "direction_xy": [float(np.cos(ang)), float(np.sin(ang))]})+ count += 1+ if count > 500:+ cmd, count = sample(cmd_rng), 0+ if t + 1 < horizon:+ segs.append(seg(t + 1, cmd))+ return {"qpos0": np.asarray(st.data.qpos).tolist(), "qvel0": np.asarray(st.data.qvel).tolist(), "commands": segs,+ "kicks": kicks}+++def reset_state(env, seed: int) -> dict:+ """Playground's reset as is (no settle, no command): handstand.py draws xy, yaw and the base velocity."""+ st = jax.jit(env.reset)(jax.random.PRNGKey(seed))+ return {"qpos0": np.asarray(st.data.qpos).tolist(), "qvel0": np.asarray(st.data.qvel).tolist()}+++def spot_getup(env, seed: int) -> dict:+ rng = jax.random.PRNGKey(seed)+ rng, _noise, key1, key2 = jax.random.split(rng, 4) # spot/getup.py reset, before its settle; base velocity zero+ drop = bool(jax.random.bernoulli(key1, env._config.drop_from_height_prob))+ qpos = env._get_random_qpos(key2) if drop else env._init_q+ return {"qpos0": np.asarray(qpos).tolist(), "qvel0": [0.0] * env.mjx_model.nv, "dropped": drop}+++def getup(env, seed: int) -> dict:+ rng = jax.random.PRNGKey(seed)+ rng, key1, key2 = jax.random.split(rng, 3) # getup.py reset, before mjx_env.step(..., settle_steps)+ drop = bool(jax.random.bernoulli(key1, env._config.drop_from_height_prob))+ qpos = env._get_random_qpos(key2) if drop else env._init_q+ rng, key = jax.random.split(rng)+ qvel = jp.zeros(env.mjx_model.nv).at[0:6].set(jax.random.uniform(key, (6,), minval=-0.5, maxval=0.5))+ return {"qpos0": np.asarray(qpos).tolist(), "qvel0": np.asarray(qvel).tolist(), "dropped": drop}+++def main() -> None:+ ap = argparse.ArgumentParser()+ ap.add_argument("env")+ ap.add_argument("--seeds", default="0-49")+ ap.add_argument("--out", default="cand")+ a = ap.parse_args()+ env = registry.load(a.env, config_overrides={"impl": "jax"})+ horizon = int(env._config.episode_length)+ os.makedirs(os.path.join(a.out, a.env), exist_ok=True)+ for k in seeds(a.seeds):+ rec = {"benchmark": "MuJoCo Playground", "env": a.env, "seed": k, "playground": "4057c14",+ "jax": jax.__version__}+ if a.env == "SpotFlatTerrainJoystick":+ rec.update(spot_joystick(env, k, horizon, 4))+ elif a.env == "SpotJoystickGaitTracking":+ rec.update(spot_joystick(env, k, horizon, 3))+ elif a.env == "BarkourJoystick":+ rec.update(barkour_joystick(env, k, horizon))+ elif "Joystick" in a.env:+ rec.update(joystick(env, k, horizon))+ elif a.env in ("Go1Handstand", "Go1Footstand"):+ rec.update(reset_state(env, k))+ else:+ rec.update(spot_getup(env, k) if a.env == "SpotGetup" else getup(env, k))+ json.dump(rec, open(os.path.join(a.out, a.env, f"seed{k}.json"), "w"), indent=1)+ print(a.env, k, len(rec.get("commands", [])), "segments" if "commands" in rec else f"dropped={rec.get('dropped')}")+++if __name__ == "__main__":+ main()diff --git a/scripts/mujoco-playground/oracle.py b/scripts/mujoco-playground/oracle.pynew file mode 100644index 0000000000..f3c68b93f2--- /dev/null+++ b/scripts/mujoco-playground/oracle.py@@ -0,0 +1,236 @@+"""Reference trajectories: a policy run closed loop on the frozen instance in the task's own MuJoCo, its targets recorded.++ python oracle.py <instance.json> --out traj.npz [--policy P]+Go1 joystick: MuJoCo Playground's own Go1 joystick policy (experimental/sim2sim/onnx/go1_policy.onnx @4057c14), with the+observation of play_go1_joystick.py (no noise): local linvel, gyro, gravity, q - home, qd, last action, command;+targets = home + 0.5 * action. Getup and the other tasks: a policy trained here (train/), TorchScript, observation as+in its env (train/qenv.py). Policies are used only to make the reference; no task image contains one.+Prints the replayed verdict of the recorded trajectory (a fresh Session), which is what the oracle check needs."""+import argparse+import json+import os+import sys++import numpy as np++sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "shared"))+import rcb_quadruped as Q # noqa: E402++# A MuJoCo Playground checkout at 4057c14 (its pretrained Go1 policy); never part of a task image.+GO1_ONNX = os.path.join(os.environ.get("RCB_PLAYGROUND", "playground"), "mujoco_playground/experimental/sim2sim/onnx/go1_policy.onnx")+++def f32(row) -> np.ndarray:+ """Every reference row is exactly representable in float32: the standard client sends actions as float32, so the+ privileged replay and the standard episode then execute the very same targets."""+ return np.asarray(row, dtype=np.float32).astype(np.float64)+++def go1_joystick(s: Q.Session) -> np.ndarray:+ import onnxruntime as ort+ sess = ort.InferenceSession(GO1_ONNX, providers=["CPUExecutionProvider"])+ name = sess.get_inputs()[0].name+ last = np.zeros(12, np.float32)+ rows = []+ while not s.done:+ d = s.data+ obs = np.concatenate([s.sensor("local_linvel"), s.sensor("gyro"), s.gravity(), d.qpos[7:] - s.home, d.qvel[6:],+ last, s.command_now()]).astype(np.float32)+ a = sess.run(None, {name: obs[None]})[0][0]+ last = a.astype(np.float32)+ row = f32(s.home + 0.5 * a)+ rows.append(row)+ s.step(row)+ return np.array(rows)+++def torch_policy(s: Q.Session, path: str, obs_fn, act_fn, stop_fn=None) -> np.ndarray:+ import torch+ pol = torch.jit.load(path).eval()+ last = np.zeros(12)+ rows = []+ while not s.done:+ o = obs_fn(s, last)+ with torch.no_grad():+ a = np.clip(pol(torch.as_tensor(o, dtype=torch.float32)[None])[0].numpy().astype(np.float64), -1, 1)+ row = f32(act_fn(s, a))+ last = a+ rows.append(row)+ s.step(row)+ if stop_fn and stop_fn(s):+ break+ return np.array(rows)+++def go1_getup_obs(s, last):+ d = s.data+ return np.concatenate([s.sensor("gyro"), s.gravity(), d.qpos[7:] - s.home, d.qvel[6:], last])+++def go1_getup_act(s, a):+ return s.data.qpos[7:] + 0.5 * a # getup.py: current joints + 0.5 * action+++def spot_getup_obs(s, last):+ return np.concatenate([s.sensor("gyro"), s.sensor("upvector"), s.data.qpos[7:] - s.home, last])+++def spot_getup_act(s, a):+ return np.clip(s.data.qpos[7:] + 0.6 * a, s.lower, s.upper) # spot/getup.py: current joints + 0.6 * action, clipped+++def stand_on_two_policy(s: Q.Session, path: str) -> np.ndarray:+ """go1/handstand.py's policy, closed loop: observation local linvel, gyro, gravity, q - home, qd, last action;+ targets accumulate as Playground's do (ctrl + 0.3 * action, kept unclipped; the tooling clips what it applies, as+ MuJoCo clamps ctrl). Stops once the hold is complete."""+ import torch+ pol = torch.jit.load(path).eval()+ last = np.zeros(12)+ acc = s.targets.copy()+ rows = []+ while not s.done:+ d = s.data+ o = np.concatenate([s.sensor("local_linvel"), s.sensor("gyro"), s.gravity(), d.qpos[7:] - s.home, d.qvel[6:], last])+ with torch.no_grad():+ a = np.clip(pol(torch.as_tensor(o, dtype=torch.float32)[None])[0].numpy().astype(np.float64), -1, 1)+ acc = acc + 0.3 * a+ last = a+ rows.append(f32(np.clip(acc, s.lower, s.upper)))+ s.step(rows[-1])+ if s.check()["success"] or s.fell_at:+ break+ return np.array(rows)+++class JoystickObs:+ """The observation the queue-trained joystick policies saw (train/qenv.py), without noise, built step by step."""++ def __init__(self, s: Q.Session, scale: float, lo, hi):+ self.s, self.scale, self.lo, self.hi = s, scale, np.asarray(lo), np.asarray(hi)+ self.last = np.zeros(12)+ self.motor = np.zeros(12)+ self.err = np.zeros(36)+ self.hist = np.zeros(15 * 31)++ def act(self, a) -> np.ndarray:+ self.motor = np.clip(self.s.home + a * self.scale, self.lo, self.hi)+ self.last = a+ return self.motor++ def spot(self) -> np.ndarray: # spot/joystick.py state (81)+ s = self.s+ q = s.data.qpos[7:]+ self.err = np.roll(self.err, 12)+ self.err[:12] = q - self.motor+ feet = np.concatenate([s.sensor(f"{f}_pos") for f in s.robot["feet"]])+ return np.concatenate([s.sensor("gyro"), s.sensor("upvector"), q - s.home, self.err, feet, self.last, s.command_now()])++ def spot_gait(self) -> np.ndarray: # spot/joystick_gait_tracking.py state (69)+ s, g = self.s, self.s.gait+ q = s.data.qpos[7:]+ self.err = np.roll(self.err, 12)+ self.err[:12] = q - self.motor+ ph = np.fmod(np.asarray(g["phase0"]) + s.steps * g["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ return np.concatenate([s.sensor("gyro"), s.sensor("upvector"), q, self.err, s.foot_contacts(), np.cos(ph), np.sin(ph),+ [g["frequency_hz"], g["type"], g["foot_height_m"]]])++ def spot_gait_cmd(self) -> np.ndarray: # the reference's policy: Playground's 69 + the command+ return np.concatenate([self.spot_gait(), self.s.command_now()])++ def barkour(self) -> np.ndarray: # barkour/joystick.py state: 15 frames of 31, newest first+ s = self.s+ o = np.concatenate([s.sensor("gyro")[2:3] * 0.25, s.sensor("upvector"), s.command_now() * np.array([2.0, 2.0, 0.25]),+ s.data.qpos[7:] - s.home, self.last])+ self.hist = np.roll(self.hist, o.size)+ self.hist[:o.size] = np.clip(o, -100, 100)+ return self.hist.copy()+++JOYSTICK = { # env -> (action scale, limits(s) -> (lo, hi), observation builder)+ "SpotFlatTerrainJoystick": (0.3, lambda s: (s.lower, s.upper), JoystickObs.spot),+ "SpotJoystickGaitTracking": (0.6, lambda s: (s.lower, s.upper), JoystickObs.spot_gait_cmd),+ "BarkourJoystick": (0.3, lambda s: (np.tile([-0.7, -1.0, 0.05], 4), np.tile([0.52, 2.1, 2.1], 4)), JoystickObs.barkour),+}+++def joystick_policy(s: Q.Session, path: str) -> np.ndarray:+ import torch+ pol = torch.jit.load(path).eval()+ scale, lim, build = JOYSTICK[s.env]+ ob = JoystickObs(s, scale, *lim(s))+ rows = []+ while not s.done:+ o = build(ob)+ with torch.no_grad():+ a = np.clip(pol(torch.as_tensor(o, dtype=torch.float32)[None])[0].numpy().astype(np.float64), -1, 1)+ rows.append(f32(ob.act(a)))+ s.step(rows[-1])+ if s.fell_at:+ break+ return np.array(rows)+++def getup_stop(s):+ return s.check()["success"] # end the trajectory once the hold is complete+++def getup_flip_then_stand(s: Q.Session, path: str, obs_fn, act_fn, flip_max: int = 200, stand_steps: int = 50) -> np.ndarray:+ """The trained getup policies turn the robot belly-down and level but stop there, crouched (a local optimum of+ Playground's getup reward). So: the policy until the trunk is level (tilt < 8 deg) and still (base speeds < 0.3) for+ 20 steps in a row, then the joint targets interpolated linearly to the home pose over stand_steps, then held until+ the success hold is complete."""+ import torch+ pol = torch.jit.load(path).eval()+ last = np.zeros(12)+ rows = []+ calm = 0+ while s.steps < flip_max:+ o = obs_fn(s, last)+ with torch.no_grad():+ a = np.clip(pol(torch.as_tensor(o, dtype=torch.float32)[None])[0].numpy().astype(np.float64), -1, 1)+ row = f32(act_fn(s, a))+ last = a+ rows.append(row)+ s.step(row)+ calm = calm + 1 if (s.log[-1][2] < 8 and np.abs(s.data.qvel[:6]).max() < 0.3) else 0+ if calm >= 20:+ break+ q0 = s.targets.copy()+ for i in range(1, stand_steps + 1):+ rows.append(f32(q0 + (s.home - q0) * i / stand_steps))+ s.step(rows[-1])+ while not s.check()["success"] and not s.done:+ rows.append(f32(s.home))+ s.step(rows[-1])+ return np.array(rows)+++def main() -> None:+ ap = argparse.ArgumentParser()+ ap.add_argument("instance")+ ap.add_argument("--out")+ ap.add_argument("--policy")+ a = ap.parse_args()+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Q.Session(a.instance, check_hash=False)+ if s.env.startswith("Go1Joystick"):+ rows = go1_joystick(s)+ elif s.env == "Go1Getup":+ rows = getup_flip_then_stand(s, a.policy, go1_getup_obs, go1_getup_act)+ elif s.env == "SpotGetup":+ rows = torch_policy(s, a.policy, spot_getup_obs, spot_getup_act, getup_stop)+ elif s.env in ("Go1Handstand", "Go1Footstand"):+ rows = stand_on_two_policy(s, a.policy)+ elif s.env in JOYSTICK:+ rows = joystick_policy(s, a.policy)+ else:+ raise SystemExit(f"no reference for {s.env}")+ r = Q.Session(a.instance, check_hash=False).replay(rows)+ if a.out:+ np.save(a.out, rows)+ print(json.dumps({"instance": a.instance, "n_rows": len(rows), **{k: v for k, v in r.items() if k != "segments"},+ "segments": r.get("segments")}))+++if __name__ == "__main__":+ main()diff --git a/scripts/mujoco-playground/oracles/BarkourJoystick.npy b/scripts/mujoco-playground/oracles/BarkourJoystick.npynew file mode 100644index 0000000000..56910d0997Binary files /dev/null and b/scripts/mujoco-playground/oracles/BarkourJoystick.npy differdiff --git a/scripts/mujoco-playground/oracles/Go1Footstand.npy b/scripts/mujoco-playground/oracles/Go1Footstand.npynew file mode 100644index 0000000000..32569d8ff9Binary files /dev/null and b/scripts/mujoco-playground/oracles/Go1Footstand.npy differdiff --git a/scripts/mujoco-playground/oracles/Go1Getup.npy b/scripts/mujoco-playground/oracles/Go1Getup.npynew file mode 100644index 0000000000..dc3c74e7b0Binary files /dev/null and b/scripts/mujoco-playground/oracles/Go1Getup.npy differdiff --git a/scripts/mujoco-playground/oracles/Go1Handstand.npy b/scripts/mujoco-playground/oracles/Go1Handstand.npynew file mode 100644index 0000000000..92f939ea5bBinary files /dev/null and b/scripts/mujoco-playground/oracles/Go1Handstand.npy differdiff --git a/scripts/mujoco-playground/oracles/Go1JoystickFlatTerrain.npy b/scripts/mujoco-playground/oracles/Go1JoystickFlatTerrain.npynew file mode 100644index 0000000000..0e3688d4fbBinary files /dev/null and b/scripts/mujoco-playground/oracles/Go1JoystickFlatTerrain.npy differdiff --git a/scripts/mujoco-playground/oracles/Go1JoystickRoughTerrain.npy b/scripts/mujoco-playground/oracles/Go1JoystickRoughTerrain.npynew file mode 100644index 0000000000..7ca581e9d7Binary files /dev/null and b/scripts/mujoco-playground/oracles/Go1JoystickRoughTerrain.npy differdiff --git a/scripts/mujoco-playground/oracles/SpotFlatTerrainJoystick.npy b/scripts/mujoco-playground/oracles/SpotFlatTerrainJoystick.npynew file mode 100644index 0000000000..ce4a22921dBinary files /dev/null and b/scripts/mujoco-playground/oracles/SpotFlatTerrainJoystick.npy differdiff --git a/scripts/mujoco-playground/oracles/SpotGetup.npy b/scripts/mujoco-playground/oracles/SpotGetup.npynew file mode 100644index 0000000000..1198383fb3Binary files /dev/null and b/scripts/mujoco-playground/oracles/SpotGetup.npy differdiff --git a/scripts/mujoco-playground/oracles/SpotJoystickGaitTracking.npy b/scripts/mujoco-playground/oracles/SpotJoystickGaitTracking.npynew file mode 100644index 0000000000..565259883eBinary files /dev/null and b/scripts/mujoco-playground/oracles/SpotJoystickGaitTracking.npy differdiff --git a/scripts/mujoco-playground/select_instances.py b/scripts/mujoco-playground/select_instances.pynew file mode 100644index 0000000000..81c0a0156c--- /dev/null+++ b/scripts/mujoco-playground/select_instances.py@@ -0,0 +1,140 @@+"""Pick and freeze each task's instance from make_instances.py's candidates, with a fixed rule that never looks at an+agent's result:++ joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than+ half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s), when its pushes (Barkour) are null or+ weak (peak under 20% of the torso's weight), or when the reference trajectory (oracle.py) fails the task's+ success check; the first remaining seed is the instance.+ getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the+ settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.+ stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.++ python select_instances.py Go1JoystickFlatTerrain --cand <dir> [--policy P]+writes instances/<Env>.json (the frozen instance with its t = 0 state hash) and oracles/<Env>.npy (the reference+trajectory), and selection/<Env>.json (every candidate tried, with why it was skipped)."""+import argparse+import json+import os+import sys++import numpy as np++HERE = os.path.dirname(os.path.abspath(__file__))+sys.path.insert(0, os.path.join(HERE, "shared"))+sys.path.insert(0, HERE)+import oracle # noqa: E402+import rcb_quadruped as Q # noqa: E402++TEXT = {+ "Go1JoystickFlatTerrain": "Make the Unitree Go1 follow the joystick command schedule on flat ground for the whole "+ "20 s episode without falling over.",+ "Go1JoystickRoughTerrain": "Make the Unitree Go1 follow the joystick command schedule on rough terrain (a 20 x 20 m "+ "heightfield, up to 5 cm high) for the whole 20 s episode without falling over.",+ "Go1Getup": "The Unitree Go1 has fallen over. Make it get up and stand upright at its standing height.",+ "SpotGetup": "Boston Dynamics Spot has fallen over. Make it get up and stand upright at its standing height.",+ "SpotFlatTerrainJoystick": "Make Boston Dynamics Spot follow the joystick command schedule on flat ground for the whole "+ "20 s episode without falling over.",+ "SpotJoystickGaitTracking": "Make Boston Dynamics Spot follow the joystick command schedule for the whole 20 s episode with "+ "the commanded gait (the feet's swing pattern, frequency and height) without falling over.",+ "BarkourJoystick": "Make Google's Barkour quadruped follow the joystick command schedule for the whole 10 s episode, "+ "through random pushes, without falling over.",+ "Go1Handstand": "Make the Unitree Go1 do a handstand: balance on its front legs, nose down, hind legs in the air, for 2 s.",+ "Go1Footstand": "Make the Unitree Go1 stand up on its hind legs, nose up, front legs in the air, and balance there for 2 s.",+}+++def activity(inst: dict) -> float:+ cmd = Q.schedule_of(inst, Q.ENVS[inst["env"]]["horizon"])+ return float(np.mean((np.linalg.norm(cmd[:, :2], axis=1) >= 0.3) | (np.abs(cmd[:, 2]) >= 0.3)))+++def facts(s0: Q.Session, inst: dict, rows, r: dict) -> dict:+ """The numbers the task texts quote (generate.py reads them; it runs without MuJoCo)."""+ q = np.asarray(inst["qpos0"])+ w, z = q[3], q[6]+ out = {"start_xy_m": [round(float(q[0]), 3), round(float(q[1]), 3)],+ "start_yaw_deg": round(float(np.degrees(2 * np.arctan2(z, w))), 1),+ "start_tilt_deg": round(float(np.degrees(np.arccos(np.clip(s0.data.site_xmat[s0._imu][8], -1, 1)))), 1),+ "start_imu_height_m": round(float(s0.data.site_xpos[s0._imu][2]), 3),+ "reference_rows": int(len(rows)), "torso_mass_kg": round(s0._root_mass, 3)}+ for k in ("worst_lin_err", "worst_yaw_err", "worst_gait_err", "tilt_deg", "imu_height", "pose_angle_deg"):+ if r.get(k) is not None:+ out[f"reference_{k}"] = r[k]+ return out+++def main() -> None:+ ap = argparse.ArgumentParser()+ ap.add_argument("env")+ ap.add_argument("--cand", default="cand")+ ap.add_argument("--policy")+ ap.add_argument("--max", type=int, default=40)+ a = ap.parse_args()+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ os.environ["RCB_SESSION_LOG"] = ""+ for d in ("instances", "oracles", "selection"):+ os.makedirs(os.path.join(HERE, d), exist_ok=True)+ tried = []+ for k in range(a.max):+ path = os.path.join(a.cand, a.env, f"seed{k}.json")+ inst = json.load(open(path))+ inst["text"] = TEXT[a.env]+ rec = {"seed": k}+ if "commands" in inst:+ rec["activity"] = round(activity(inst), 3)+ if rec["activity"] < 0.5:+ tried.append({**rec, "skipped": "mostly standstill"})+ continue+ if "kicks" in inst:+ mass = Q.Session(path, check_hash=False)._root_mass+ peak = max((0.5 * mass * k["velocity_mps"] / (k["duration_steps"] * 0.02) if k["duration_steps"] >= 2 else 0.0)+ for k in inst["kicks"])+ rec["push_peak_n"] = round(peak, 1)+ if peak < 0.2 * mass * 9.81:+ tried.append({**rec, "skipped": "pushes null or weak (peak under 20% of the torso's weight; a 1-step "+ "kick is zero in Playground's half-sine)"})+ continue+ elif "dropped" in inst:+ if not inst["dropped"]:+ tried.append({**rec, "skipped": "not dropped (starts standing)"})+ continue+ tilt = Q.Session(path, check_hash=False).state()+ rec["start_tilt_deg"] = round(float(np.degrees(np.arccos(np.clip(tilt["imu_mat"][2, 2], -1, 1)))), 1)+ if rec["start_tilt_deg"] < 90:+ tried.append({**rec, "skipped": "tilted less than 90 degrees after the settle"})+ continue+ s = Q.Session(path, check_hash=False)+ if a.env.startswith("Go1Joystick"):+ rows = oracle.go1_joystick(s)+ elif a.env == "Go1Getup":+ rows = oracle.getup_flip_then_stand(s, a.policy, oracle.go1_getup_obs, oracle.go1_getup_act)+ elif a.env == "SpotGetup":+ rows = oracle.torch_policy(s, a.policy, oracle.spot_getup_obs, oracle.spot_getup_act, oracle.getup_stop)+ elif a.env in ("Go1Handstand", "Go1Footstand"):+ rows = oracle.stand_on_two_policy(s, a.policy)+ elif a.env in oracle.JOYSTICK:+ rows = oracle.joystick_policy(s, a.policy)+ r1 = Q.Session(path, check_hash=False).replay(rows)+ r2 = Q.Session(path, check_hash=False).replay(rows)+ keep = {k2: r1[k2] for k2 in ("success", "fell_at", "worst_lin_err", "worst_yaw_err", "tilt_deg", "imu_height", "pose_angle_deg",+ "steps") if k2 in r1}+ if not (r1["success"] and r2["success"] and r1["state_sha"] == r2["state_sha"]):+ tried.append({**rec, **keep, "skipped": "reference fails"})+ continue+ s0 = Q.Session(path, check_hash=False)+ inst["facts"] = facts(s0, inst, rows, r1)+ inst["state_sha"] = s0.state_sha()+ inst["horizon"] = s0.horizon+ inst["selection"] = {"rule": __doc__.split("\n\n")[1].strip(), "candidates_tried": len(tried) + 1}+ json.dump(inst, open(os.path.join(HERE, "instances", f"{a.env}.json"), "w"), indent=1)+ np.save(os.path.join(HERE, "oracles", f"{a.env}.npy"), rows)+ tried.append({**rec, **keep, "chosen": True})+ json.dump({"env": a.env, "candidates": tried}, open(os.path.join(HERE, "selection", f"{a.env}.json"), "w"), indent=1)+ print(json.dumps({"env": a.env, "seed": k, "state_sha": inst["state_sha"], "n_rows": len(rows), **keep}))+ return+ json.dump({"env": a.env, "candidates": tried}, open(os.path.join(HERE, "selection", f"{a.env}.json"), "w"), indent=1)+ raise SystemExit(f"{a.env}: no candidate among the first {a.max} seeds")+++if __name__ == "__main__":+ main()diff --git a/scripts/mujoco-playground/selection/BarkourJoystick.json b/scripts/mujoco-playground/selection/BarkourJoystick.jsonnew file mode 100644index 0000000000..73d66ab724--- /dev/null+++ b/scripts/mujoco-playground/selection/BarkourJoystick.json@@ -0,0 +1,28 @@+{+ "env": "BarkourJoystick",+ "candidates": [+ {+ "seed": 0,+ "activity": 1.0,+ "push_peak_n": 0.0,+ "skipped": "pushes null or weak (peak under 20% of the torso's weight; a 1-step kick is zero in Playground's half-sine)"+ },+ {+ "seed": 1,+ "activity": 1.0,+ "push_peak_n": 9.1,+ "skipped": "pushes null or weak (peak under 20% of the torso's weight; a 1-step kick is zero in Playground's half-sine)"+ },+ {+ "seed": 2,+ "activity": 1.0,+ "push_peak_n": 35.4,+ "success": true,+ "fell_at": null,+ "worst_lin_err": 0.0329,+ "worst_yaw_err": 0.0276,+ "steps": 1000,+ "chosen": true+ }+ ]+}\ No newline at end of filediff --git a/scripts/mujoco-playground/selection/Go1Footstand.json b/scripts/mujoco-playground/selection/Go1Footstand.jsonnew file mode 100644index 0000000000..6528de4b79--- /dev/null+++ b/scripts/mujoco-playground/selection/Go1Footstand.json@@ -0,0 +1,14 @@+{+ "env": "Go1Footstand",+ "candidates": [+ {+ "seed": 0,+ "success": true,+ "fell_at": null,+ "imu_height": 0.5408,+ "pose_angle_deg": 9.62,+ "steps": 113,+ "chosen": true+ }+ ]+}\ No newline at end of filediff --git a/scripts/mujoco-playground/selection/Go1Getup.json b/scripts/mujoco-playground/selection/Go1Getup.jsonnew file mode 100644index 0000000000..2d927a7b2a--- /dev/null+++ b/scripts/mujoco-playground/selection/Go1Getup.json@@ -0,0 +1,37 @@+{+ "env": "Go1Getup",+ "candidates": [+ {+ "seed": 0,+ "start_tilt_deg": 74.8,+ "skipped": "tilted less than 90 degrees after the settle"+ },+ {+ "seed": 1,+ "start_tilt_deg": 25.5,+ "skipped": "tilted less than 90 degrees after the settle"+ },+ {+ "seed": 2,+ "skipped": "not dropped (starts standing)"+ },+ {+ "seed": 3,+ "start_tilt_deg": 39.5,+ "skipped": "tilted less than 90 degrees after the settle"+ },+ {+ "seed": 4,+ "skipped": "not dropped (starts standing)"+ },+ {+ "seed": 5,+ "start_tilt_deg": 110.0,+ "success": true,+ "tilt_deg": 2.34,+ "imu_height": 0.2568,+ "steps": 136,+ "chosen": true+ }+ ]+}\ No newline at end of filediff --git a/scripts/mujoco-playground/selection/Go1Handstand.json b/scripts/mujoco-playground/selection/Go1Handstand.jsonnew file mode 100644index 0000000000..da2e68ad91--- /dev/null+++ b/scripts/mujoco-playground/selection/Go1Handstand.json@@ -0,0 +1,14 @@+{+ "env": "Go1Handstand",+ "candidates": [+ {+ "seed": 0,+ "success": true,+ "fell_at": null,+ "imu_height": 0.5314,+ "pose_angle_deg": 13.82,+ "steps": 115,+ "chosen": true+ }+ ]+}\ No newline at end of filediff --git a/scripts/mujoco-playground/selection/Go1JoystickFlatTerrain.json b/scripts/mujoco-playground/selection/Go1JoystickFlatTerrain.jsonnew file mode 100644index 0000000000..e765635596--- /dev/null+++ b/scripts/mujoco-playground/selection/Go1JoystickFlatTerrain.json@@ -0,0 +1,15 @@+{+ "env": "Go1JoystickFlatTerrain",+ "candidates": [+ {+ "seed": 0,+ "activity": 1.0,+ "success": true,+ "fell_at": null,+ "worst_lin_err": 0.0732,+ "worst_yaw_err": 0.0914,+ "steps": 1000,+ "chosen": true+ }+ ]+}\ No newline at end of filediff --git a/scripts/mujoco-playground/selection/Go1JoystickRoughTerrain.json b/scripts/mujoco-playground/selection/Go1JoystickRoughTerrain.jsonnew file mode 100644index 0000000000..2293f32f93--- /dev/null+++ b/scripts/mujoco-playground/selection/Go1JoystickRoughTerrain.json@@ -0,0 +1,25 @@+{+ "env": "Go1JoystickRoughTerrain",+ "candidates": [+ {+ "seed": 0,+ "activity": 1.0,+ "success": false,+ "fell_at": 858,+ "worst_lin_err": 2.8384,+ "worst_yaw_err": 0.6753,+ "steps": 1000,+ "skipped": "reference fails"+ },+ {+ "seed": 1,+ "activity": 0.674,+ "success": true,+ "fell_at": null,+ "worst_lin_err": 0.0788,+ "worst_yaw_err": 0.1137,+ "steps": 1000,+ "chosen": true+ }+ ]+}\ No newline at end of filediff --git a/scripts/mujoco-playground/selection/SpotFlatTerrainJoystick.json b/scripts/mujoco-playground/selection/SpotFlatTerrainJoystick.jsonnew file mode 100644index 0000000000..78798b976d--- /dev/null+++ b/scripts/mujoco-playground/selection/SpotFlatTerrainJoystick.json@@ -0,0 +1,15 @@+{+ "env": "SpotFlatTerrainJoystick",+ "candidates": [+ {+ "seed": 0,+ "activity": 0.799,+ "success": true,+ "fell_at": null,+ "worst_lin_err": 0.1555,+ "worst_yaw_err": 0.072,+ "steps": 1000,+ "chosen": true+ }+ ]+}\ No newline at end of filediff --git a/scripts/mujoco-playground/selection/SpotGetup.json b/scripts/mujoco-playground/selection/SpotGetup.jsonnew file mode 100644index 0000000000..b095970031--- /dev/null+++ b/scripts/mujoco-playground/selection/SpotGetup.json@@ -0,0 +1,18 @@+{+ "env": "SpotGetup",+ "candidates": [+ {+ "seed": 0,+ "skipped": "not dropped (starts standing)"+ },+ {+ "seed": 1,+ "start_tilt_deg": 128.4,+ "success": true,+ "tilt_deg": 0.47,+ "imu_height": 0.4782,+ "steps": 63,+ "chosen": true+ }+ ]+}\ No newline at end of filediff --git a/scripts/mujoco-playground/selection/SpotJoystickGaitTracking.json b/scripts/mujoco-playground/selection/SpotJoystickGaitTracking.jsonnew file mode 100644index 0000000000..77ab4bd3ac--- /dev/null+++ b/scripts/mujoco-playground/selection/SpotJoystickGaitTracking.json@@ -0,0 +1,15 @@+{+ "env": "SpotJoystickGaitTracking",+ "candidates": [+ {+ "seed": 0,+ "activity": 1.0,+ "success": true,+ "fell_at": null,+ "worst_lin_err": 0.1827,+ "worst_yaw_err": 0.1358,+ "steps": 1000,+ "chosen": true+ }+ ]+}\ No newline at end of filediff --git a/scripts/mujoco-playground/shared/grade.py b/scripts/mujoco-playground/shared/grade.pynew file mode 100644index 0000000000..e5668de85f--- /dev/null+++ b/scripts/mujoco-playground/shared/grade.py@@ -0,0 +1,126 @@+"""Verifier (privileged): replay /app/output/trajectory.npz from the frozen instance and write Harbor's rewards.++ python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz++Two replays, each in its own fresh process (`rcb_quadruped.py replay`: the frozen start, one control step per row, the+task's success check on the whole trajectory). success = both replays succeed and end in the same state. Writes+/logs/verifier/reward.txt (1/0) and reward.json (numbers only); then a third replay renders replay.mp4, after the+verdict is on disk (it never changes it).+"""+import argparse+import json+import os+import subprocess+import sys+import tempfile+import traceback++import numpy as np++LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")+TOOL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_quadruped.py")+REPLAY_TIMEOUT_S = 300 # a 1000-step replay takes a few seconds; the video replay renders 4 views every 2nd step+++def write(ok: bool, out: dict) -> None:+ os.makedirs(LOG_DIR, exist_ok=True)+ open(os.path.join(LOG_DIR, "reward.txt"), "w").write("1\n" if ok else "0\n")+ json.dump(out, open(os.path.join(LOG_DIR, "reward.json"), "w"))+ print(json.dumps(out), flush=True)+++def agent_cost() -> dict:+ """Self-reported cost from the tooling's log in the agent's container (accounting, not evidence)."""+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_replays": 0, "agent_cost_self_reported": 1}+ for path in ("/logs/agent/rcb/rcb_session_log.jsonl", "/app/output/rcb_session_log.jsonl"):+ if not os.path.exists(path):+ continue+ try:+ with open(path) as f:+ for i, line in enumerate(f):+ if i > 200_000 or len(line) > 10_000:+ break+ try:+ e = json.loads(line)+ ev = e.get("ev") if isinstance(e, dict) else None+ if ev == "session_start":+ cost["agent_sessions"] += 1+ elif ev == "reset":+ cost["agent_resets"] += 1+ elif ev == "replay":+ cost["agent_replays"] += 1+ elif ev == "session_end":+ cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)+ except Exception: # noqa: BLE001 -- one bad line must not sink the verdict+ continue+ except OSError:+ pass+ break+ return cost+++def replay(instance: str, traj: str, video: str | None) -> dict:+ """One replay in a fresh process; its result (`--out`), or {"error": ...}."""+ with tempfile.NamedTemporaryFile(suffix=".json") as out:+ cmd = [sys.executable, TOOL, "replay", "--instance", instance, "--traj", traj, "--out", out.name]+ try:+ p = subprocess.run(cmd + (["--video", video] if video else []), stdout=subprocess.DEVNULL, stderr=sys.stderr,+ timeout=REPLAY_TIMEOUT_S, env={**os.environ, "RCB_SESSION_LOG": "", "RCB_AGENT_TRACE_DIR": ""})+ except subprocess.TimeoutExpired:+ return {"error": f"replay took over {REPLAY_TIMEOUT_S} s"}+ try:+ return json.load(open(out.name))+ except ValueError:+ return {"error": f"replay process rc={p.returncode}"}+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--instance", required=True)+ ap.add_argument("--traj", default="/app/output/trajectory.npz")+ a = ap.parse_args()+ cost = agent_cost()+ if not os.path.isfile(a.traj):+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost})+ return 0+ try:+ horizon = int(json.load(open(a.instance))["horizon"])+ d = np.load(a.traj, allow_pickle=False)+ acts = np.asarray(d["actions"], dtype=np.float64) if "actions" in d.files else np.zeros((0, 0))+ if acts.ndim != 2 or acts.shape[1] != 12 or len(acts) > horizon or not np.all(np.isfinite(acts)):+ write(False, {"success": 0, "bad_trajectory": 1, "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0,+ "grader_error": 0, **cost})+ return 0+ runs = [replay(a.instance, a.traj, None), replay(a.instance, a.traj, None)]+ if any("error" in r and not r.get("bad_trajectory") for r in runs):+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ if not all(r.get("instance_ok") for r in runs): # the image no longer builds the frozen start: not the agent's 0+ write(False, {"success": 0, "grader_error": 1, "instance_mismatch": 1, **cost})+ return 0+ all_success = all(bool(r.get("success")) for r in runs)+ deterministic = runs[0].get("state_sha") == runs[1].get("state_sha")+ ok = all_success and deterministic+ r = runs[0]+ num = lambda k: float(r.get(k) if r.get(k) is not None else -1) # noqa: E731+ out = {"success": int(ok), "replay_success": int(all_success), "deterministic": int(deterministic),+ "n_actions": int(len(acts)), "horizon": horizon, "fell": int(r.get("fell_at") is not None),+ "fell_at_step": num("fell_at"), "worst_lin_err": num("worst_lin_err"), "worst_yaw_err": num("worst_yaw_err"),+ "end_tilt_deg": num("tilt_deg"), "end_imu_height": num("imu_height"), "end_pose_angle_deg": num("pose_angle_deg"),+ "grader_error": 0,+ "video_rendered": 0, **cost}+ write(ok, out) # the verdict, before any video+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ try: # the video, for humans: it never changes the verdict+ if replay(a.instance, a.traj, os.path.join(LOG_DIR, "replay.mp4")).get("video"):+ write(ok, {**out, "video_rendered": 1})+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/mujoco-playground/shared/oracle_privileged.py b/scripts/mujoco-playground/shared/oracle_privileged.pynew file mode 100644index 0000000000..46987df1d0--- /dev/null+++ b/scripts/mujoco-playground/shared/oracle_privileged.py@@ -0,0 +1,15 @@+"""Oracle (privileged): replay the reference rows in the tooling, check them, and save them as the deliverable."""+import json+import os+import sys++import numpy as np++sys.path.insert(0, "/opt/tools")+from rcb_quadruped import Session # noqa: E402++rows = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy"))+s = Session("/app/instance.json")+r = s.replay(rows)+s.save_trajectory(rows, "/app/output/trajectory.npz", meta={"source": "reference trajectory (solution/oracle.npy)"})+print(json.dumps({k: v for k, v in r.items() if k != "segments"}))diff --git a/scripts/mujoco-playground/shared/rcb_quadruped.py b/scripts/mujoco-playground/shared/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/scripts/mujoco-playground/shared/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/scripts/mujoco-playground/shared/solve_privileged.sh b/scripts/mujoco-playground/shared/solve_privileged.shnew file mode 100755index 0000000000..430ffb6017--- /dev/null+++ b/scripts/mujoco-playground/shared/solve_privileged.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Oracle (privileged): write the reference trajectory frozen at generation time (solution/oracle.npy; how it was made:+# scripts/mujoco-playground/oracle.py) as the deliverable.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/scripts/mujoco-playground/shared/standard/finalize.sh b/scripts/mujoco-playground/shared/standard/finalize.shnew file mode 100755index 0000000000..02048ddc74--- /dev/null+++ b/scripts/mujoco-playground/shared/standard/finalize.sh@@ -0,0 +1,80 @@+#!/bin/sh+# [[verifier.collect]] hook, run inside the `sim` sidecar once Harbor has stopped the agent's container.+# 1. `rcb_limited.py end` (docs/STANDARD_MODE_2_2.md §13.3): SIGUSR1 to the service, which ends the episode if the+# agent had not (reason "timeout"), writes trajectory.npz + episode.json (live verdict, final-state hash) and exits.+# It exits 2 when final.json already holds the verdict (the service gave up after crashes): that verdict stays.+# 2. replay the trajectory from the frozen instance in TWO fresh processes (`rcb_quadruped.py replay`, the privileged+# verifier's replay): determinism = fresh process == fresh process; live_matches_replay = live == replay.+# 3. merge everything into final.json, the only thing the verifier sandbox grades;+# 4. a third replay renders replay.mp4, after the verdict is on disk (it never changes it).+set -u+DATA="${RCB_DATA:-/data}"; TOOL="${RCB_TOOL:?}"; INSTANCE="${RCB_INSTANCE:?}"+python /srv/rcb_limited.py end "$DATA" --timeout "${RCB_COLLECT_END_TIMEOUT_S:-900}"; rc=$?+if [ "$rc" = 2 ]; then+ echo "[finalize] final.json already holds the verdict; no replay"; exit 0+fi+if [ "$rc" != 0 ]; then+ echo "[finalize] the service did not end and dump the episode in time (rc $rc): an infrastructure failure"+ python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data"); p = os.path.join(d, "final.json")+try:+ out = json.load(open(p))+except Exception:+ out = {}+out.update({"finalized": True, "success": False, "replay_success": False, "deterministic": False, "infra_error": 1,+ "error": "collect hook: the sim service did not end and dump the episode in time"})+json.dump(out, open(p, "w"))+print(json.dumps(out))+PY+ exit 0+fi+replay() { # <n> [--video FILE]: one replay in a fresh process, its result in $DATA/replay<n>.json+ n=$1; shift+ RCB_SESSION_LOG= python "$TOOL" replay --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --out "$DATA/replay$n.json" \+ "$@" > /dev/null 2> "$DATA/replay$n.log"+ echo "[finalize] replay $n exit $?"+}+echo "[finalize] episode dumped; replaying twice in fresh processes"+rm -f "$DATA/replay1.json" "$DATA/replay2.json" "$DATA/replay3.json"+replay 1+replay 2+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+def result(name):+ try:+ v = json.load(open(os.path.join(d, name)))+ except (OSError, ValueError):+ return {}+ return v if isinstance(v, dict) else {}+out = {"replay_success": False, "deterministic": False, "video": False}+try:+ out.update(json.load(open(os.path.join(d, "episode.json"))))+except Exception as exc:+ out["error"] = f"no episode.json: {exc!r}"+a, b = result("replay1.json"), result("replay2.json")+out["replay_success"] = bool(a.get("success")) and bool(b.get("success"))+out["replay_sha"], out["replay_sha2"] = a.get("state_sha"), b.get("state_sha")+out["deterministic"] = bool(a.get("state_sha")) and a.get("state_sha") == b.get("state_sha")+out["live_matches_replay"] = bool(a.get("state_sha")) and a.get("state_sha") == out.get("live_sha")+if not (a.get("state_sha") and b.get("state_sha")): # a replay process died (it crashed or timed out): not the agent's 0+ out.update({"replay_failed": 1, "infra_error": 1,+ "error": "a replay process gave no result (replay1.log / replay2.log)"})+elif not (a.get("instance_ok") and b.get("instance_ok")): # the image no longer builds the frozen start: not the agent's 0+ out.update({"instance_mismatch": 1, "infra_error": 1, "error": "a replay did not start in the instance's t = 0 state"})+out["finalized"] = True+json.dump(out, open(os.path.join(d, "final.json"), "w"))+print(json.dumps(out))+PY+replay 3 --video "$DATA/replay.mp4"+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+try:+ shown = json.load(open(os.path.join(d, "replay3.json"))).get("video")+except (OSError, ValueError):+ shown = False+if shown:+ p = os.path.join(d, "final.json"); out = json.load(open(p)); out["video"] = True; json.dump(out, open(p, "w"))+PYdiff --git a/scripts/mujoco-playground/shared/standard/grade.py b/scripts/mujoco-playground/shared/standard/grade.pynew file mode 100644index 0000000000..5b990bf458--- /dev/null+++ b/scripts/mujoco-playground/shared/standard/grade.py@@ -0,0 +1,64 @@+"""Standard-mode verifier (MuJoCo Playground quadrupeds): reads what the sim service (which the agent could not touch) wrote:+/data/final.json (live success, two fresh-process replays of the recorded trajectory, determinism, crash-recovery+fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, the+replays having started in the instance's t = 0 state. Numeric-only reward.json."""++import json, os, shutil++LOG = "/logs/verifier"+os.makedirs(LOG, exist_ok=True)+++def write(ok, out):+ open(f"{LOG}/reward.txt", "w").write("1\n" if ok else "0\n")+ json.dump(out, open(f"{LOG}/reward.json", "w"))+ print(out)+++p = "/data/final.json"+if not os.path.exists(p):+ write(False, {"success": 0, "missing_log": 1, "grader_error": 0, "infra_error": 0})+ raise SystemExit+d = json.load(open(p))+for f in ("replay.mp4", "trajectory.npz", "episode.jsonl"):+ if os.path.exists(f"/data/{f}"):+ shutil.copy(f"/data/{f}", f"{LOG}/{f}")+ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic"))+ok = ok and not d.get("instance_mismatch")+num = lambda k: float(d.get(k) or 0) # noqa: E731+write(+ ok,+ {+ "success": int(ok),+ "live_success": int(bool(d.get("success"))),+ "replay_success": int(bool(d.get("replay_success"))),+ "deterministic": int(bool(d.get("deterministic"))),+ "live_matches_replay": int(bool(d.get("live_matches_replay"))),+ "finalized": int(bool(d.get("finalized"))),+ "n_actions": int(d.get("n_actions") or 0),+ "sim_steps": int(d.get("control_steps") or 0),+ "physics_steps": int(d.get("physics_steps") or 0),+ "steps": int(d.get("steps") or 0),+ "elapsed_s": float(d.get("elapsed_s") or 0),+ "video_rendered": int(bool(d.get("video"))),+ "fell": int(d.get("fell_at") is not None),+ "worst_lin_err": float(d["worst_lin_err"]) if d.get("worst_lin_err") is not None else -1.0,+ "worst_yaw_err": float(d["worst_yaw_err"]) if d.get("worst_yaw_err") is not None else -1.0,+ "end_tilt_deg": float(d["tilt_deg"]) if d.get("tilt_deg") is not None else -1.0,+ "end_imu_height": float(d["imu_height"]) if d.get("imu_height") is not None else -1.0,+ "end_pose_angle_deg": float(d["pose_angle_deg"]) if d.get("pose_angle_deg") is not None else -1.0,+ # a replay process gave no result, or the image no longer builds the frozen start: not the agent's 0+ "grader_error": int(bool(d.get("replay_failed") or d.get("instance_mismatch"))),+ "instance_mismatch": int(bool(d.get("instance_mismatch"))),+ # an infrastructure failure, not the agent's (PROTOCOL §2.6): a give-up after crashes between calls or a failed+ # resume (docs/STANDARD_MODE_2_2.md §13), the service not ending its episode for the collect hook, a replay+ # process that gave no result, replays that did not start in the instance's t = 0 state+ "infra_error": int(bool(d.get("infra_error"))),+ "gave_up": int(bool(d.get("gave_up"))),+ "sim_error": int(d.get("reason") == "error"),+ "sim_startups": int(d.get("sim_startups") or 0),+ "resumes": int(d.get("resumes") or 0),+ "resume_state_mismatch": int(d.get("resume_state_mismatch") or 0),+ "resume_max_joint_dev": num("resume_max_joint_dev"),+ },+)diff --git a/scripts/mujoco-playground/shared/standard/oracle_replay.py b/scripts/mujoco-playground/shared/standard/oracle_replay.pynew file mode 100644index 0000000000..b6a9824592--- /dev/null+++ b/scripts/mujoco-playground/shared/standard/oracle_replay.py@@ -0,0 +1,42 @@+"""Oracle (standard mode): streams the reference rows (one per 1/50 s control step, `hold`) as `joint_position` chunks+through the client, the same interface an agent has. Uses no privileged information at run time; the service's recorded+trajectory is then exactly the privileged reference. If the service crashes it resumes the same episode+(spec["on_service_error"]): the oracle waits until it answers again and goes on from the control step it reports."""+import os+import sys+import time++import numpy as np+import requests++sys.path.insert(0, "/opt/tools")+from rcb_client import EpisodeOver, Robot # noqa: E402++Q = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy")).astype(np.float64)+r = Robot()+spec = r.spec()+dt = 1.0 / float(spec["control_hz"])+per_chunk = max(1, int(spec.get("max_chunk_s", 10) / dt + 1e-9))+print("spec:", spec["protocol"], "rows:", len(Q), flush=True)+t0, i = time.time(), 0+while i < len(Q):+ chunk = Q[i:i + per_chunk]+ try:+ res = r.submit("joint_position", chunk, dt=dt, interpolate="hold", cameras=["track"], video="none", note=f"oracle rows {i}+")+ except EpisodeOver as e:+ print("episode over:", e)+ break+ except requests.exceptions.RequestException as e: # the service crashed: it restarts and resumes the same episode+ print("service unreachable:", repr(e)[:200], "- waiting for it to resume", flush=True)+ st = r.wait_ready()+ n = int(st["control_steps"])+ if not i <= n <= i + len(chunk):+ raise SystemExit(f"resumed at control step {n}: outside the chunk in flight (rows {i}..{i + len(chunk)})")+ i = n+ continue+ n = int(res.meta["control_steps"])+ print(f"rows {i}..{n}: clipped={res.meta['n_clipped']} done={res.meta['done']} reason={res.meta['reason']}", flush=True)+ if res.meta["done"] or n <= i:+ break+ i = n+print("status:", r.status(), "wall %.0fs" % (time.time() - t0))diff --git a/scripts/mujoco-playground/shared/standard/server.py b/scripts/mujoco-playground/shared/standard/server.pynew file mode 100644index 0000000000..b0c774b183--- /dev/null+++ b/scripts/mujoco-playground/shared/standard/server.py@@ -0,0 +1,478 @@+"""eai-standard/2.2 sim service for MuJoCo Playground's quadruped tasks (docs/STANDARD_MODE_2_2.md): the adapter of the+shared layer rcb_limited.py; the simulator is rcb_quadruped.Session (plain MuJoCo on the CPU).+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to+/data/episode.jsonl.++The episode is the frozen instance's: one control step = 1/50 s. A joystick episode ends after the whole command schedule+(the horizon), when the robot meets Playground's termination rule (it falls over: a failure), when the agent submits+`done`, or when its time is over; success = the task's check on the steps executed. A getup episode ends the moment the+check holds (success), after the horizon, on `done` or on timeout.++Crash recovery (rcb_limited.Episode, resume class `exact`: MuJoCo on the CPU repeats bit for bit in a fresh process):+every executed row is journaled; after a crash the service rebuilds the episode and replays the journal. When the+episode ends the service writes /data/trajectory.npz + /data/episode.json; the collect hook (finalize.sh) makes it exit+and replays the trajectory in two fresh processes."""++import math+import os+import sys+import threading+import time+import traceback++import numpy as np++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import rcb_limited as L # noqa: E402++DATA = os.environ.get("RCB_DATA", "/data")+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.json"))+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "3600"))+MAX_CHUNK_S = float(os.environ.get("RCB_MAX_CHUNK_S", "10"))+MAX_WATCH_S = float(os.environ.get("RCB_MAX_WATCH_S", "30"))+CAM_W, CAM_H = 320, 240+LOCK = threading.Lock()+PID_FILE = os.path.join(DATA, "server.pid")+E = {"ready": False, "step": 0, "calls": 0, "done": False, "reason": None, "success": False, "t0": time.time(), "error": None}++os.environ["RCB_SESSION_LOG"] = ""+os.environ["RCB_AGENT_TRACE_DIR"] = ""+import rcb_quadruped as Q # noqa: E402 (first: it picks the rendering backend before mujoco loads)+import mujoco # noqa: E402++EP = L.Episode(DATA, dim=Q.N, resume="exact")+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()+S = Q.Session(INSTANCE)+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz+DT = S.control_dt # one control step of simulated time (Barkour: 10 ms, as Playground steps it)+CTRL_HZ = 1.0 / DT+SUBSTEPS = S.substeps+M = S.model+CAMS = list(S.cameras)+FEET = S.robot["feet"]+LIMITS = np.stack([S.lower, S.upper], axis=1)+GROUPS = [+ ("joint_pos", S.joint_names, "measured joint positions (rad), in the action's order"),+ ("joint_vel", [f"{j}_vel" for j in S.joint_names], "measured joint velocities (rad/s)"),+ ("joint_effort", [f"{j}_effort" for j in S.joint_names], "actuator torques of those joints (N m)"),+ ("gripper_opening", [], "none (no gripper)"),+ ("tcp_pose", [], "none (no gripper)"),+ ("imu_gyro", ["gyro_x", "gyro_y", "gyro_z"], "angular velocity of the trunk, IMU frame (rad/s)"),+ ("imu_accelerometer", ["acc_x", "acc_y", "acc_z"], "specific force at the IMU, IMU frame (m/s^2; +9.81 up at rest)"),+ ("imu_gravity", ["gravity_x", "gravity_y", "gravity_z"], "unit vector of gravity's direction in the IMU frame "+ "([0, 0, -1] when the trunk is level)"),+ ("imu_linvel", ["linvel_x", "linvel_y", "linvel_z"], "linear velocity of the trunk at the IMU, IMU frame (m/s; the "+ "IMU's velocimeter, what a state estimator gives)"),+ ("foot_contact", [f"{f}_contact" for f in FEET], "1 when the foot touches the ground, else 0"),+]+PROPRIO_LAYOUT = [n for _, names, _ in GROUPS for n in names]+PROPRIO_GROUPS, _i = {}, 0+for _g, _names, _meaning in GROUPS:+ PROPRIO_GROUPS[_g] = [_i, len(_names), _meaning]+ _i += len(_names)+++# ------------------------------------------------------------------------------------------------- cameras+def _intrinsic(cam: str) -> list:+ fovy = math.radians(float(M.cam_fovy[M.camera(cam).id]))+ f = 0.5 * CAM_H / math.tan(fovy / 2)+ return [[f, 0.0, CAM_W / 2], [0.0, f, CAM_H / 2], [0.0, 0.0, 1.0]]+++def camera_info(cam: str) -> dict:+ """World -> camera (OpenCV axes) and camera -> world (OpenGL axes) at the current state."""+ i = M.camera(cam).id+ R_gl = S.data.cam_xmat[i].reshape(3, 3) # camera axes (OpenGL: x right, y up, z back) in the world+ p = S.data.cam_xpos[i].copy()+ R_cv = R_gl @ np.diag([1.0, -1.0, -1.0])+ ext = np.zeros((3, 4))+ ext[:, :3] = R_cv.T+ ext[:, 3] = -R_cv.T @ p+ c2w = np.eye(4)+ c2w[:3, :3] = R_gl+ c2w[:3, 3] = p+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": ext.tolist(), "cam2world_gl": c2w.tolist(),+ "image_size": [CAM_W, CAM_H]}+++# ------------------------------------------------------------------------------------------------- kinematics+KD = mujoco.MjData(M) # kinematics only: the trunk at the origin, level; never stepped+_FOOT = {f: M.site(f).id for f in FEET}+_LEG_DOF = {f: [6 + 3 * k + j for j in range(3)] for k, f in enumerate(FEET)} # actuator order = leg order = FEET+++def _fk_kd(q) -> None:+ KD.qpos[:] = 0.0+ KD.qpos[3] = 1.0+ KD.qpos[7:] = q+ mujoco.mj_kinematics(M, KD)+++def _foot_pose(f: str) -> list:+ quat = np.zeros(4)+ mujoco.mju_mat2Quat(quat, KD.site_xmat[_FOOT[f]])+ return [*KD.site_xpos[_FOOT[f]].tolist(), *quat.tolist()]+++def do_kinematics(req: dict) -> dict:+ """Feet in the trunk frame (the trunk body's origin and axes; x forward, y left, z up). IK solves positions only, one+ leg (3 joints) per foot target, damped least squares within the joint ranges; a foot's orientation is ignored."""+ if req["op"] == "fk":+ _fk_kd(np.asarray(req["q"]))+ return L.fk_response({f: _foot_pose(f) for f in req["links"]}, "trunk")+ q = np.array(req["seed"] if req["seed"] is not None else S.data.qpos[7:], dtype=np.float64)+ errors = {}+ jac = np.zeros((3, M.nv))+ for f, pose in req["targets"].items():+ tgt = np.asarray(pose[:3])+ idx = _LEG_DOF[f]+ for _ in range(req["max_iters"]):+ _fk_kd(q)+ err = tgt - KD.site_xpos[_FOOT[f]]+ if np.linalg.norm(err) < req["tol_pos_m"]:+ break+ mujoco.mj_jacSite(M, KD, jac, None, _FOOT[f])+ J = jac[:, idx]+ dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(3), err)+ q[[i - 6 for i in idx]] = np.clip(q[[i - 6 for i in idx]] + dq, S.lower[[i - 6 for i in idx]],+ S.upper[[i - 6 for i in idx]])+ _fk_kd(q)+ errors[f] = (float(np.linalg.norm(tgt - KD.site_xpos[_FOOT[f]])), 0.0)+ ok = all(e[0] <= req["tol_pos_m"] for e in errors.values())+ return L.ik_response(q, ok, errors, "trunk", note="feet: position only (a foot is a sphere; its orientation is ignored)")+++# ------------------------------------------------------------------------------------------------- spec+def schedule_text() -> list:+ if S.commands is None:+ return []+ return [{"from_s": round(int(c["start_step"]) * DT, 2), "vx_mps": round(c["vx"], 4), "vy_mps": round(c["vy"], 4),+ "wz_radps": round(c["wz"], 4)} for c in S.inst["commands"]]+++TASK_EPISODE = {+ "joystick": f"one episode, no reset: it ends after {S.horizon} control steps (the {S.horizon * DT:g} s command "+ f"schedule), when the robot meets its termination rule ({S.spec.get('term_text')}: a failure), when you "+ "submit `done`, or when your time is over",+ "getup": f"one episode, no reset: it ends the moment the robot has stood upright for {Q.HOLD_STEPS} control steps in a "+ f"row (success), after {S.horizon} control steps, when you submit `done`, or when your time is over",+ "stand_on_two": f"one episode, no reset: it ends the moment the pose has been held for {Q.POSE_HOLD_STEPS} control steps "+ "in a row (success), when the robot meets the termination rule (a failure: its trunk's up axis below "+ f"-0.25, or {'a leg' if S.spec.get('hind_leg_contact') else 'a front leg'}'s thigh, calf or hip on the "+ f"floor), after {S.horizon} control steps, when you "+ "submit `done`, or when your time is over",+}[S.kind]+_ctl = {"type": "joint position actuators (PD)", "kp_nm_per_rad": float(M.actuator_gainprm[0, 0]),+ "kd_nms_per_rad": float(M.dof_damping[6] - M.actuator_biasprm[0, 2])}+SPEC = {+ "protocol": L.PROTOCOL,+ "protocol_compat": list(L.COMPAT),+ "simulator": "MuJoCo 3.3.7 (MuJoCo Playground's scene, plain MuJoCo on the CPU)",+ "robot": S.robot["name"],+ "task_text": S.inst["text"],+ "control_hz": CTRL_HZ,+ "physics_substeps": SUBSTEPS,+ "max_chunk_s": MAX_CHUNK_S,+ "max_watch_s": MAX_WATCH_S,+ "cameras": {c: {"rgb": True, "depth": True, "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),+ **({"mounted": "follows the robot", "mount": {"type": "link", "link": S.robot["root"], "note":+ "follows the robot's centre of mass at a fixed offset; it does not turn with the robot"}}+ if int(M.cam_mode[M.camera(c).id]) != 0 else+ {"mounted": "on the robot's head", "mount": {"type": "link", "link": M.body(M.cam_bodyid[M.camera(c).id]).name+ or S.robot["root"], "note": "fixed to the robot: moves and turns with it"}})}+ for c in CAMS},+ "default_cameras": ["track"],+ "action_types": {+ "joint_position": {+ "dim": Q.N,+ "layout": S.joint_names,+ "limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "units": "rad",+ "semantics": "absolute targets of the 12 joint position actuators, one per control step (1/50 s); rows `dt` "+ "apart (a multiple of the control period, at most 0.5 s), `hold` or `linear` between rows; values "+ "outside the limits are clipped and reported",+ },+ "done": {"dim": 0, "layout": [], "semantics": 'ends the episode now, in the current state (no physics); r.submit("done", [])'},+ "not_yet": ["joint_velocity", "joint_torque", "joint_delta"],+ },+ "proprio_layout": PROPRIO_LAYOUT,+ "proprio_groups": PROPRIO_GROUPS,+ "static": {},+ "world": {"frame": "z up; the robot starts where the episode puts it (no world coordinates are given)", "up": "+z",+ "units": {"length": "m", "angle": "rad", "time": "s"}, "quaternion_order": "wxyz",+ "camera_axes": "intrinsic_cv / extrinsic_cv: OpenCV camera axes (x right, y down, z forward); cam2world_gl: OpenGL axes"},+ "budget": {"reset": 0, "steps": None, "wall_clock_s": WALL_CLOCK_S},+ "max_control_steps": S.horizon,+ "episode": TASK_EPISODE,+ "command_schedule": schedule_text(),+ **({"gait": {k: S.gait[k] for k in ("name", "frequency_hz", "foot_height_m", "phase0", "phase_dt")} | {+ "feet": FEET, "rule": "foot i's target height at control step t is get_rz(wrap(phase0[i] + t * phase_dt)) with "+ "Playground's gait.get_rz (a cubic Bezier from 0 up to foot_height_m over the first half of the phase, then "+ "down); phases in rad, wrapped to [-pi, pi)"}} if S.gait else {}),+ "robot_spec": {"name": S.robot["name"], "joints": S.joint_names, "joint_limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "joint_order": S.robot["joint_text"], "home_pose": dict(zip(S.joint_names, S.home.tolist())),+ "feet": FEET, "controller": _ctl},+ "kinematics": {"endpoint": "/kinematics", "joint_names": S.joint_names, "frame": "trunk", "quaternion_order": "wxyz",+ "links": FEET, "tcp_frames": [], "ee_frames": FEET, "ik_targets": FEET,+ "ik": {"tol_pos_m": 0.002, "tol_rot_rad": 3.2, "max_iters": 100},+ "note": "poses of the feet in the trunk frame (x forward, y left, z up, metres) for joint positions q; "+ "ik: one leg per foot, positions only"},+ "depth": {"modes": list(L.DEPTH_MODES), "default": "none", "kind": "z-depth", "unit": "m", "invalid": 0,+ "max_m": L.DEPTH_MAX_M, "frames_encoding": "uint16 mm, zlib", "noise": L.DEPTH_NOISE},+}+L.check_spec(SPEC) # a spec that misses a 2.2 field or names a forbidden one never starts the episode+EP.scene_built()++_RENDER = {}+++def _renderer():+ if "r" not in _RENDER:+ _RENDER["r"] = mujoco.Renderer(M, CAM_H, CAM_W)+ return _RENDER["r"]+++def ctrl_steps() -> int:+ return S.steps+++def proprio_row() -> np.ndarray:+ d = S.data+ return np.concatenate([d.qpos[7:], d.qvel[6:], d.actuator_force, S.sensor("gyro"), S.sensor("accelerometer"), S.gravity(),+ S.sensor("local_linvel"), S.foot_contacts()]).astype(np.float32)+++def grab(cams, want_depth: bool):+ r = _renderer()+ rgb, dep = {}, {}+ for c in cams:+ r.update_scene(S.data, camera=c)+ rgb[c] = r.render().copy()+ if want_depth:+ r.enable_depth_rendering()+ r.update_scene(S.data, camera=c)+ dep[c] = r.render().astype(np.float32).copy()+ r.disable_depth_rendering()+ return rgb, dep+++def extrinsics(cams) -> dict:+ return {c: np.asarray(camera_info(c)["extrinsic_cv"], dtype=np.float64) for c in cams}+++def write_final() -> None:+ if L.final_verdict(DATA): # finalize.sh's verdict, or a give-up after crashes: never overwritten+ return+ L._write_json(os.path.join(DATA, "final.json"), {**summary(), "finalized": False, "live_sha": E.get("live_sha")})+++def summary() -> dict:+ n = int(E.get("episode_control_steps") or ctrl_steps())+ chk = E.get("check") or {}+ return {"success": bool(E["success"]), "steps": E["step"], "calls": E["calls"], "control_steps": n,+ "physics_steps": n * SUBSTEPS, "elapsed_s": round((E.get("t_end") or time.time()) - E["t0"], 1),+ "reason": E["reason"], "done": E["done"], "env": S.env, "protocol": L.PROTOCOL, "n_actions": len(ROWS),+ "fell_at": chk.get("fell_at"), "worst_lin_err": chk.get("worst_lin_err"), "worst_yaw_err": chk.get("worst_yaw_err"),+ "tilt_deg": chk.get("tilt_deg"), "imu_height": chk.get("imu_height"), "pose_angle_deg": chk.get("pose_angle_deg"),+ **EP.final_fields()}+++def finish(reason: str) -> None:+ """The episode is over: the task's check on the steps executed, then the record for the collect hook."""+ if E["done"]:+ return+ E["done"] = True+ E["reason"] = reason+ E["t_end"] = time.time()+ E["episode_control_steps"] = ctrl_steps()+ try:+ chk = S.check()+ E["check"] = {k: v for k, v in chk.items() if k != "segments"}+ E["success"] = bool(chk["success"])+ except Exception: # noqa: BLE001+ traceback.print_exc()+ EP.log({"ev": "end", "reason": reason, "step": E["step"], "control_steps": ctrl_steps(), "success": bool(E["success"])})+ dump()+++def dump() -> None:+ if E.get("dumped"):+ return+ E["dumped"] = True+ E["live_sha"] = S.state_sha()+ np.savez(os.path.join(DATA, "trajectory.npz"), actions=np.asarray(ROWS, dtype=np.float64).reshape(-1, Q.N),+ env=S.env, action_layout=",".join(S.joint_names))+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})+ write_final()+++def after_step() -> None:+ if S.kind in ("joystick", "stand_on_two") and S.fell_at is not None:+ finish("fell")+ elif S.kind in ("getup", "stand_on_two") and S.check()["success"]:+ finish("success")+ elif S.done:+ finish("horizon")+++def ctrl_step(a, rec) -> bool:+ """One executed control step, journaled. True when the call must stop here."""+ S.step(a)+ ROWS.append(np.asarray(a, dtype=np.float64))+ stop = EP.journal(a)+ rec.tick()+ after_step()+ return E["done"] or stop+++def recorder(cams, fps: int, meta: dict) -> L.Recorder:+ return L.Recorder(cams, max(1, int(round(CTRL_HZ / max(1, fps)))), grab, proprio_row, extrinsics, ctrl_steps,+ depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+++def video_fps(meta: dict) -> int:+ fps = meta.get("video_fps")+ if fps is None:+ return 10+ if isinstance(fps, bool) or not isinstance(fps, (int, float)) or not (1 <= fps <= 50):+ raise ValueError("video_fps must be in [1, 50]")+ return int(fps)+++def cameras_of(meta: dict) -> list:+ cams = meta.get("cameras") or ["track"]+ bad = [c for c in cams if c not in CAMS]+ if bad:+ raise ValueError(f"unknown cameras {bad}; cameras: {CAMS}")+ return list(cams)+++def meta_common(cams) -> dict:+ n = ctrl_steps()+ out = {"step": E["step"], "calls": E["calls"], "control_steps": n, "physics_steps": n * SUBSTEPS,+ "sim_time_s": round(n * DT, 3), "time_s": round(time.time() - E["t0"], 2),+ "time_left_s": max(0.0, round(WALL_CLOCK_S - (time.time() - E["t0"]), 1)),+ "proprio": {"layout": PROPRIO_LAYOUT, "now": proprio_row().tolist()}, "done": E["done"], "reason": E["reason"],+ "cameras": {c: camera_info(c) for c in cams}}+ if S.kind == "joystick":+ out["command_now"] = dict(zip(("vx_mps", "vy_mps", "wz_radps"), S.command_now().round(4).tolist()))+ return out+++def do_submit(meta: dict, A: np.ndarray):+ typ = meta.get("type")+ if typ == "done":+ rec = recorder(cameras_of(meta), 5, meta)+ rec.tick(force=True, last=True) # every response carries the last frames+ E["calls"] += 1+ finish("done")+ return {**meta_common(cameras_of(meta)), "chunk_id": E["calls"], "type": typ, "executed_rows": 0, "ok": True}, rec.parts("none", 5)+ if typ != "joint_position":+ raise ValueError(f"type must be joint_position or done (not yet: {SPEC['action_types']['not_yet']})")+ dt = float(meta.get("dt", DT))+ interp = meta.get("interpolate", "linear")+ video = meta.get("video", "mp4")+ cams, fps = cameras_of(meta), video_fps(meta)+ k = dt / DT+ if A.ndim != 2 or A.shape[1] != Q.N:+ raise ValueError(f"joint_position actions must be (T, {Q.N}), got {list(A.shape)}")+ if not np.all(np.isfinite(A)):+ raise ValueError("actions contain NaN/inf")+ if not (math.isfinite(dt) and dt <= 0.5 + 1e-9 and round(k) >= 1 and abs(k - round(k)) < 1e-6):+ raise ValueError(f"dt must be a whole multiple of the {DT:g} s control period and at most 0.5 s; got {dt}")+ if A.shape[0] * dt > MAX_CHUNK_S + 1e-9:+ raise ValueError(f"chunk longer than max_chunk_s={MAX_CHUNK_S}: {A.shape[0]} rows x {dt} s")+ if interp not in ("hold", "linear"):+ raise ValueError("interpolate must be hold|linear")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, clipped = recorder(cams, fps, meta), []+ E["calls"] += 1+ step0, before = E["step"], ctrl_steps()+ rec.tick(force=True)+ prev = S.targets.copy()+ for ri, row in enumerate(A):+ E["step"] += 1+ target = np.clip(row, LIMITS[:, 0], LIMITS[:, 1])+ for j in np.flatnonzero(target != row)[:20]:+ clipped.append({"row": ri, "index": int(j), "reason": f"{S.joint_names[j]} limit [{LIMITS[j, 0]:g}, {LIMITS[j, 1]:g}]"})+ n = int(round(k))+ stop = False+ for s in range(1, n + 1):+ a = target if interp == "hold" else prev + (target - prev) * (s / n)+ if ctrl_step(a, rec):+ stop = True+ break+ prev = target+ if stop:+ break+ rec.tick(force=True, last=True)+ out = {**meta_common(cams), "chunk_id": E["calls"], "type": typ, "executed_rows": E["step"] - step0,+ "control_steps_chunk": ctrl_steps() - before, "physics_steps_chunk": (ctrl_steps() - before) * SUBSTEPS,+ "clipped": clipped[:200], "n_clipped": len(clipped), "plan": [], "ok": True}+ EP.log({"ev": "submit", "call": E["calls"], "rows": E["step"] - step0, "dt": dt, "interpolate": interp, "cameras": cams,+ "control_steps": ctrl_steps() - before, "n_clipped": len(clipped), "note": (meta.get("note") or "")[:500],+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video, fps)+++def do_observe(meta: dict):+ cams, fps = cameras_of(meta), video_fps(meta)+ seconds = float(meta.get("seconds", 0))+ video = meta.get("video", "frames")+ if not math.isfinite(seconds) or seconds < 0 or seconds > MAX_WATCH_S:+ raise ValueError(f"seconds must be in [0, {MAX_WATCH_S}]")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, before = recorder(cams, fps, meta), ctrl_steps()+ if seconds > 0 and not E["done"]:+ rec.tick(force=True)+ hold = S.targets.copy()+ for _ in range(int(round(seconds / DT))):+ if ctrl_step(hold, rec):+ break+ rec.tick(force=True, last=True)+ E["calls"] += 1+ out = {**meta_common(cams), "obs_id": E["calls"], "seconds": seconds, "control_steps_watch": ctrl_steps() - before,+ "physics_steps_watch": (ctrl_steps() - before) * SUBSTEPS, "ok": True}+ EP.log({"ev": "observe", "call": E["calls"], "seconds": seconds, "cameras": cams, "control_steps": ctrl_steps() - before,+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video if seconds > 0 else ("frames" if video == "mp4" else video), fps)+++def status() -> dict:+ return {"step": E["step"], "calls": E["calls"], "control_steps": ctrl_steps(), "done": E["done"], "reason": E["reason"],+ "elapsed_s": round(time.time() - E["t0"], 1)}+++def end_from_signal() -> None:+ """The collect hook's SIGUSR1: end the episode (the agent's time is over), dump it, exit so the replays can start."""+ with LOCK:+ E["exiting"] = True+ if not E["done"]:+ finish("timeout")+ EP.log({"ev": "exit", "reason": "collect hook: episode dumped"})+ if not os.path.exists(PID_FILE):+ open(PID_FILE, "w").write(str(os.getpid()))+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(0)+++def replay_row(row) -> None:+ """A journaled row during a resume."""+ S.step(row)+ ROWS.append(np.asarray(row, dtype=np.float64))+++EP.begin(state=E, step=replay_row, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, on_end=end_from_signal,+ start_event={"env": S.env, "seed": S.inst.get("seed"), "cameras": CAMS})+if E["done"]:+ dump() # resumed after the episode had ended: the record is rewritten from the replay+E["ready"] = True+write_final()+open(PID_FILE, "w").write(str(os.getpid()))+print(f"{L.PROTOCOL} MuJoCo Playground quadruped sim ready ({S.env}; startup {EP.n_startups}, resumes {EP.resumes})", flush=True)+L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics, status=status,+ on_submit_error=lambda exc: finish("error"), log=EP.log, episode=EP, state_sha=S.state_sha,+ proprio=proprio_row), port=int(os.environ.get("RCB_PORT", "8000")))diff --git a/scripts/mujoco-playground/shared/standard/solve.sh b/scripts/mujoco-playground/shared/standard/solve.shnew file mode 100755index 0000000000..ecb1f6c954--- /dev/null+++ b/scripts/mujoco-playground/shared/standard/solve.sh@@ -0,0 +1,8 @@+#!/bin/bash+# Oracle (standard mode): streams the reference trajectory's joint targets (solution/oracle.npy, one row per control step)+# as `joint_position` chunks through the client. Uses no privileged information at run time (only the pre-recorded+# targets); the service's recorded trajectory is then exactly the privileged reference.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/scripts/mujoco-playground/shared/standard/test.sh b/scripts/mujoco-playground/shared/standard/test.shnew file mode 100755index 0000000000..bc608aa8b9--- /dev/null+++ b/scripts/mujoco-playground/shared/standard/test.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Verifier (separate sandbox): the sim sidecar's artifacts were uploaded to /data by Harbor.+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)+mkdir -p /logs/verifier+python /tests/grade.py 2> /logs/verifier/grade.logdiff --git a/scripts/mujoco-playground/shared/test.sh b/scripts/mujoco-playground/shared/test.shnew file mode 100755index 0000000000..1c3d2f767b--- /dev/null+++ b/scripts/mujoco-playground/shared/test.sh@@ -0,0 +1,9 @@+#!/bin/bash+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in two fresh processes (the+# verdict), then a third that renders replay.mp4.+# Writes /logs/verifier/reward.txt (1/0) and reward.json (numeric fields, docs/PROTOCOL.md §2.6).+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/*+mkdir -p /logs/verifier+python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz 2> /logs/verifier/grade.logdiff --git a/scripts/mujoco-playground/templates/README.md b/scripts/mujoco-playground/templates/README.mdnew file mode 100644index 0000000000..af89772958--- /dev/null+++ b/scripts/mujoco-playground/templates/README.md@@ -0,0 +1,31 @@+# {{name}}-privileged++## Task+MuJoCo Playground `{{env}}` ({{robot_name}}), rebuilt in plain MuJoCo from Playground's scene files: {{task}}+{{task_detail}} The deliverable is one replayable trajectory of joint position targets+(`/app/output/trajectory.npz`, `(T, 12)`, {{rows_rule}}).++## Difficulty+{{difficulty}}++## Reference solution+{{reference}} Replayed by `solution/solve.sh` (`solution/oracle.npy`, {{n_rows}} rows); the rows are float32-exact, so the+standard twin's client executes the same targets. Re-verified by `scripts/mujoco-playground/select_instances.py`: two+fresh-process replays succeed and end in the same state.++## Verification+`tests/grade.py` in a separate sandbox without network: two replays, each in a fresh process, from the verifier's own+copy of the instance (`tests/instance.json`; the start state is checked against its hash on every load); pass iff both+succeed and end in the same state (`deterministic`). {{check_short}} `nop`: no trajectory, reward 0.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `{{xml}}`; MuJoCo Menagerie @ 1b86ece (`{{menagerie}}`); simulated in MuJoCo 3.3.7 on the CPU |+| Instance | Playground's `reset` with `jax.random.PRNGKey({{seed}})`{{instance_extra}}; chosen by `scripts/mujoco-playground/select_instances.py` ({{selection}}) |+| Actions | 12 joint position targets per control step ({{dt}} s of simulated time); {{gains}} |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py` from `scripts/mujoco-playground/instances/{{env}}.json`+(`make_instances.py`, `select_instances.py`) and `scripts/mujoco-playground/oracles/{{env}}.npy` (`oracle.py`).diff --git a/scripts/mujoco-playground/templates/instruction.md b/scripts/mujoco-playground/templates/instruction.mdnew file mode 100644index 0000000000..ab5d56c276--- /dev/null+++ b/scripts/mujoco-playground/templates/instruction.md@@ -0,0 +1,47 @@+# MuJoCo Playground · {{env}} — frozen episode++**Task:** {{task}}++You control the {{robot_name}} quadruped in one episode of MuJoCo Playground's `{{env}}` environment, rebuilt in plain+MuJoCo 3.3.7 from Playground's own scene files (Apache-2.0, commit 4057c14) and the robot from MuJoCo Menagerie. The+episode is frozen: it starts the same way after every reset (Playground's `reset` with seed {{seed}}), and you may reset+as often as you like. Your deliverable is **one open-loop trajectory**, not a general policy.++{{episode_md}}++## Success+{{success_md}}++## Deliverable+`/app/output/trajectory.npz` with `actions`: float64 (T, 12), one row per control step ({{dt}} s): absolute targets of+the 12 joint position actuators, in `s.joint_names` order ({{joint_text}}), in radians; {{rows_rule}}. Values+outside the actuator ranges (`s.lower`, `s.upper`) are clipped. `s.save_trajectory(rows)` writes it. Also leave the+script that produced it at `/app/output/gen.py`. Save a working trajectory as soon as you have one and overwrite it as+you improve it: whatever is in `/app/output/` when your 3600 s are up is graded. The tooling logs your sessions and+resets (cost accounting, not graded).++## Tooling (installed; `python` from any directory)+```python+from rcb_quadruped import Session+s = Session("/app/instance.json") # the frozen episode at t = 0 (checked against the instance's state hash)+s.joint_names; s.lower; s.upper # the actuator order and ranges (rad)+s.home # Playground's standing pose (its `home` keyframe), in that order+s.step(row) # one control step: 12 joint targets, {{substeps}} physics steps of {{sim_dt}} s; returns s.check()+s.check() # the task's check on the steps so far (see Success)+s.state() # qpos, qvel, IMU (local_linvel, gyro, gravity, accelerometer, pose), feet, contacts{{state_cmd}}+s.sensor(name); s.gravity() # one MuJoCo sensor; gravity's direction in the IMU frame+s.model, s.data # the live MuJoCo model and data (read them; changing them is not part of the replay)+s.render(cam); s.cameras # uint8 (240, 320, 3) from cameras that follow the robot: {{cameras}}+s.reset() # back to t = 0+s.replay(rows) # reset, run the rows, return the check and the final state's hash+s.render_video(rows, "/app/output/try.mp4")+s.save_trajectory(rows, "/app/output/trajectory.npz")+```+The grader runs exactly this CLI in two fresh processes, so run it to check yourself:+`python /opt/tools/rcb_quadruped.py replay --instance /app/instance.json --traj /app/output/trajectory.npz`++## Conventions+- Joint position actuators (PD): {{gains}}, as Playground's environment sets them; the physics step is {{sim_dt}} s,+ the control step {{dt}} s ({{substeps}} physics steps); a row holds until the next one.+- World frame z up, metres; quaternions **wxyz**. The IMU frame is the trunk's: x forward, y left, z up.+- Physics is MuJoCo on the CPU: the same rows from the same start give the same result in every fresh process.diff --git a/scripts/mujoco-playground/templates/standard/README.md b/scripts/mujoco-playground/templates/standard/README.mdnew file mode 100644index 0000000000..972fb2e77a--- /dev/null+++ b/scripts/mujoco-playground/templates/standard/README.md@@ -0,0 +1,33 @@+# {{name}}-standard++## Task+MuJoCo Playground `{{env}}` ({{robot_name}}) on the same frozen instance as `{{name}}-privileged`: {{task}}+{{task_detail}} Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with only+the robot's own sensors and four cameras that follow it.++## Difficulty+Same instance and success check as `{{name}}-privileged`. In standard mode the agent loses resets, the simulator and+the world state: it sees camera images and proprioception (joints, IMU, foot contacts), acts in joint position chunks,+and gets one episode, so it has to close the loop on the robot's own sensors and recover from its own mistakes without+starting over.++## Reference solution+`solution/oracle_replay.py` streams the privileged reference's rows (`solution/oracle.npy`, {{n_rows}} rows, float32-exact)+through the client in `hold` chunks; it uses no privileged information at run time. The service's recorded trajectory+is then exactly the privileged reference, and the episode ends {{oracle_end}}.++## Verification+The sim service judges the episode live and records every executed control step; the collect hook+(`environment/sim/finalize.sh`) ends the service, replays the recorded trajectory in two fresh processes and writes+`final.json`; `tests/grade.py` (separate sandbox, no network) passes iff the live check succeeded, both replays succeed,+and they end in the same state. {{check_short}}++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `{{xml}}`; MuJoCo Menagerie @ 1b86ece (`{{menagerie}}`); MuJoCo 3.3.7 on the CPU |+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); cameras {{cameras}} (320 x 240), the feet's kinematics in the trunk frame |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py`, as its privileged twin.diff --git a/scripts/mujoco-playground/templates/standard/instruction.md b/scripts/mujoco-playground/templates/standard/instruction.mdnew file mode 100644index 0000000000..ec763e3dc7--- /dev/null+++ b/scripts/mujoco-playground/templates/standard/instruction.md@@ -0,0 +1,45 @@+# MuJoCo Playground · {{env}} — STANDARD MODE (robot as a service, eai-standard/2.2)++**Task:** {{task}}++You control the {{robot_name}} quadruped — **as if it were real hardware** — in one episode of MuJoCo Playground's+`{{env}}` environment (plain MuJoCo 3.3.7 with Playground's scene, commit 4057c14). The simulator runs in a service you+cannot open. You get one client and one episode.++{{episode_md_std}}++## Rules (real-robot rules)+- **No reset.** One episode. You see four cameras that follow the robot (RGB, depth if you ask) and the robot's own+ sensors: joint positions, velocities and torques, the IMU (gyro, accelerometer, gravity's direction, the trunk's+ velocity), foot contacts. No world positions, no success check.+- **The episode ends** {{std_end}}+- **Success** {{std_success}}+- Your wall-clock budget is 3600 s from your start. Simulated time only advances with your commands (and+ `get_obs(seconds=...)`, which holds the current targets).+- Nothing to hand in: the service records the episode and grades it. Leave your script at `/app/output/gen.py`.+- **If the service crashes**, a call fails with a connection error: it restarts and resumes the SAME episode (never a+ reset) in the state after the last call it completed. `r.wait_ready()` waits for it; then check `r.status()`.+- Nothing is put into your context automatically: images come back as arrays in Python objects.++## Client (`/opt/tools/rcb_client.py`)+```python+from rcb_client import Robot+r = Robot() # connects (waits while the service starts)+spec = r.spec() # action types, limits, cameras, robot_spec (home pose, gains), kinematics{{spec_cmd}}+obs = r.get_obs() # obs.last[cam] -> uint8 (240, 320, 3); obs.meta["proprio"] {"layout", "now"}+res = r.submit("joint_position", A, dt={{dt}}) # A: (T, 12) rows dt apart; res.proprio (one row per frame), res.meta+obs = r.get_obs(seconds=1.0, video="mp4") # hold the current targets and watch for 1 s (max 30)+r.fk(q); r.ik({"{{foot0}}": [x, y, z, 1, 0, 0, 0]}, seed=q) # feet in the trunk frame <-> joints (no physics)+r.submit("done", []) # end the episode now+r.status() # calls, control steps, done, reason, elapsed time+```+Cameras: {{cameras}}; `spec["cameras"]` gives each one's mounting and intrinsics, and every response carries its pose. Proprioception (`spec["proprio_groups"]`): `joint_pos`, `joint_vel`, `joint_effort` (12 each, action+order), `imu_gyro`, `imu_accelerometer`, `imu_gravity`, `imu_linvel` (3 each, IMU frame: x forward, y left, z up),+`foot_contact` ({{feet}}).++### `joint_position` (12)+{{joint_text}}: absolute targets of the joint position actuators (rad; {{gains}}).+Rows are `dt` apart (a whole multiple of the {{dt}} s control period, at most 0.5 s), `interpolate="linear"` (default) or+`"hold"` between rows; a chunk covers at most 10 s; values outside the limits+(`spec["action_types"]["joint_position"]["limits"]`) are clipped and listed in `res.meta["clipped"]`. Feedback control+means short chunks: each response tells you where the robot is now.diff --git a/scripts/mujoco-playground/templates/standard/task.toml b/scripts/mujoco-playground/templates/standard/task.tomlnew file mode 100644index 0000000000..4b17bbd772--- /dev/null+++ b/scripts/mujoco-playground/templates/standard/task.toml@@ -0,0 +1,54 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = [+ { source = "/data/final.json", service = "sim" },+ { source = "/data/episode.jsonl", service = "sim" },+ { source = "/data/trajectory.npz", service = "sim" },+ { source = "/data/replay.mp4", service = "sim" },+ { source = "/data/server.log", service = "sim" }, # the service's own output (Harbor keeps none)+ { source = "/data/journal.f64", service = "sim" }, # crash recovery: every executed control step (float64 rows)+ { source = "/data/startups.jsonl", service = "sim" }, # crash recovery: one line per service start+ { source = "/data/replay1.log", service = "sim" }, # the collect hook's two fresh-process replays+ { source = "/data/replay2.log", service = "sim" },+ { source = "/data/replay3.log", service = "sim" }, # and its third, which renders replay.mp4+ "/app/output/",+]++[task]+name = "robot-coding-bench/{{name}}-standard"+description = "STANDARD MODE (robot as a service, eai-standard/2.2): MuJoCo Playground {{env}} ({{robot_name}}) on the same frozen instance as {{name}}-privileged: {{task_toml}} The agent only gets a client: four cameras that follow the robot (RGB, optional depth), the robot's joints and IMU, joint position chunks at 50 Hz, the feet's kinematics; one episode, no reset, no world state; the sim service records the episode, replays it in fresh processes and grades it."+authors = [{ name = "{{author}}" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "{{robot_tax}}", "quadruped", "locomotion", "{{kind}}", "code-as-policy", "trajectory", "standard-mode"]++[metadata]+author_name = "{{author}}"+author_org = "{{org}}"+task_type = "trajectory"+simulator = "mujoco"+robot = "{{robot_tax}}"+family = "mujoco_playground/{{env}}"+mode = "standard"+protocol = "eai-standard/2.2"+oracle = "full"+instance_seed = {{seed}}+expert_time_estimate_hours = {{expert_hours_std}}++[verifier]+timeout_sec = 600.0+environment_mode = "separate"+network_mode = "no-network"++[[verifier.collect]]+service = "sim"+command = "sh /srv/finalize.sh" # end + dump + exit the service, replay twice in fresh processes, write final.json, video+timeout_sec = 1200++[agent]+timeout_sec = 3600.0+network_mode = "allowlist"+allowed_hosts = [{{allowed_hosts}}]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/scripts/mujoco-playground/templates/task.toml b/scripts/mujoco-playground/templates/task.tomlnew file mode 100644index 0000000000..355896741c--- /dev/null+++ b/scripts/mujoco-playground/templates/task.toml@@ -0,0 +1,43 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = ["/app/output/", "/logs/agent/rcb/"]++[task]+name = "robot-coding-bench/{{name}}-privileged"+description = "MuJoCo Playground {{env}} in plain MuJoCo ({{robot_name}}, joint position control every {{dt}} s): {{task_toml}} Produce one replayable trajectory of joint position targets on a frozen instance (Playground's reset with seed {{seed}}); graded by {{grading_toml}}"+authors = [{ name = "{{author}}" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "{{robot_tax}}", "quadruped", "locomotion", "{{kind}}", "code-as-policy", "trajectory", "privileged"]++[metadata]+author_name = "{{author}}"+author_org = "{{org}}"+task_type = "trajectory"+simulator = "mujoco"+robot = "{{robot_tax}}"+family = "mujoco_playground/{{env}}"+mode = "privileged"+oracle = "full"+instance_seed = {{seed}} # the PRNGKey of Playground's reset (and, for the joystick tasks, its command process)+expert_time_estimate_hours = {{expert_hours}}++[verifier]+timeout_sec = 1200.0+environment_mode = "separate"+network_mode = "no-network"++[verifier.environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192++[agent]+timeout_sec = 3600.0+# MuJoCo Playground's trained policies are public upstream, so the agent reaches the model APIs and nothing else+# (scripts/set_agent_egress.py HOSTS).+network_mode = "allowlist"+allowed_hosts = [{{allowed_hosts}}]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/scripts/mujoco-playground/train/README.md b/scripts/mujoco-playground/train/README.mdnew file mode 100644index 0000000000..c34b70bde2--- /dev/null+++ b/scripts/mujoco-playground/train/README.md@@ -0,0 +1,6 @@+# Reference-policy training (not part of any task)++`qenv.py`: Playground's quadruped environments in plain MuJoCo/numpy (one class per environment, citing its source);+`vecenv.py`: worker processes with shared-memory buffers, the rsl_rl `VecEnv` interface; `train.py`: rsl_rl PPO with+Playground's rsl_rl hyperparameters; `run_capped.sh`: one run under a memory cap (`RCB_MEM_MAX`, default 48G).+Each worker compiles its model once and its envs share it (an MjData is ~1 MB with the arena these scenes need).diff --git a/scripts/mujoco-playground/train/qenv.py b/scripts/mujoco-playground/train/qenv.pynew file mode 100644index 0000000000..2c5e7f4019--- /dev/null+++ b/scripts/mujoco-playground/train/qenv.py@@ -0,0 +1,659 @@+"""MuJoCo Playground's quadruped environments re-implemented in plain MuJoCo (CPU, numpy) for PPO training.++Each env mirrors its Playground source at 4057c14 (reset distribution, action mapping, observations, rewards,+termination); comments cite the file. Training only: the benchmark's own tool (rcb_quadruped.py) carries the frozen+instances and success checks, not these rewards.+"""+from __future__ import annotations++import glob+import os++import mujoco+import numpy as np++ROOT = os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj") # the asset tree of eai-mujoco (images/mujoco/prepare_assets.sh)+_MODELS: dict = {}+_GO1 = [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")]+_SPOT = [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")]+_BARKOUR = [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")]+BARKOUR_FEET = ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"]+SCENES = { # env -> (scene XML, the asset directories Playground's get_assets() reads)+ "Go1JoystickFlatTerrain": ("playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml", _GO1),+ "Go1JoystickRoughTerrain": ("playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml", _GO1),+ "Go1Getup": ("playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml", _GO1),+ "Go1Handstand": ("playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml", _GO1),+ "Go1Footstand": ("playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml", _GO1),+ "SpotFlatTerrainJoystick": ("playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml", _SPOT),+ "SpotGetup": ("playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml", _SPOT),+ "SpotJoystickGaitTracking": ("playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml", _SPOT),+ "BarkourJoystick": ("menagerie/google_barkour_vb/scene_mjx.xml", _BARKOUR),+}+++def load_model(env_name: str) -> mujoco.MjModel:+ """The scene as Playground builds it (its XML with an asset dict of bare file names), with a 1 MB arena per MjData+ (the default 14.7 MB is ~200x what these scenes use; physics unchanged)."""+ xml, dirs = SCENES[env_name]+ assets = {}+ for d, pat in dirs:+ for f in sorted(glob.glob(os.path.join(ROOT, d, pat))):+ if os.path.isfile(f):+ assets[os.path.basename(f)] = open(f, "rb").read()+ spec = mujoco.MjSpec.from_file(os.path.join(ROOT, xml), assets=assets) # includes resolve next to the XML+ spec.memory = 1 << 20+ if env_name == "BarkourJoystick": # barkour/joystick.py adds a foot-floor contact sensor per foot+ for g in BARKOUR_FEET:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ return spec.compile()+++class Env:+ """Shared plumbing: model, PD gains as Playground sets them, sensors, substeps."""++ name = ""+ episode_length = 1000+ ctrl_dt = 0.02+ kp = kd = None # None = keep the XML's+ obs_noise = True+ imu_site = "imu"+ scene = None # the SCENES entry, when it differs from `name`++ def __init__(self, seed: int = 0):+ self.rng = np.random.default_rng(seed)+ key = (type(self).__name__, self.name)+ if key not in _MODELS: # one compiled model per process, shared by its envs (each has its own MjData)+ m = load_model(self.scene or self.name)+ if self.kp is not None:+ m.dof_damping[6:] = self.kd+ m.actuator_gainprm[:, 0] = self.kp+ m.actuator_biasprm[:, 1] = -self.kp+ self.edit_model(m)+ _MODELS[key] = m+ self.m = _MODELS[key]+ self.d = mujoco.MjData(self.m)+ self.n_sub = round(self.ctrl_dt / self.m.opt.timestep)+ self.imu = self.m.site(self.imu_site).id+ self.lo, self.hi = self.m.jnt_range[1:].T.copy()+ self.ctrl_lo, self.ctrl_hi = self.m.actuator_ctrlrange.T.copy()+ self.home = self.m.keyframe("home").qpos.copy()+ self.default_pose = self.home[7:].copy()+ self._sens = {self.m.sensor(i).name: (self.m.sensor_adr[i], self.m.sensor_dim[i]) for i in range(self.m.nsensor)}++ def edit_model(self, m: mujoco.MjModel) -> None:+ """Per-env model changes Playground makes after loading (once per process)."""++ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.d.sensordata[a:a + n].copy()++ def imu_xmat(self) -> np.ndarray:+ return self.d.site_xmat[self.imu].reshape(3, 3)++ def noise(self, x: np.ndarray, scale: float) -> np.ndarray:+ if not self.obs_noise:+ return x+ return x + (2 * self.rng.random(x.shape) - 1) * scale++ def sim(self, ctrl: np.ndarray, n: int | None = None) -> None:+ self.d.ctrl[:] = ctrl+ mujoco.mj_step(self.m, self.d, nstep=n or self.n_sub)+++# ---------------------------------------------------------------------------------------------------------- Go1 getup+class Go1Getup(Env):+ """go1/getup.py: recover from a random drop (p = 0.6) or the home pose and stand at z_des."""++ name = "Go1Getup"+ episode_length = 300+ kp, kd = 35.0, 0.5+ action_scale = 0.5+ scales = dict(orientation=1.0, torso_height=1.0, posture=1.0, stand_still=1.0, action_rate=-0.001,+ dof_pos_limits=-0.1, torques=-1e-5, dof_acc=-2.5e-7, dof_vel=-0.1)+ noise_scales = dict(joint_pos=0.03, joint_vel=1.5, gyro=0.2, gravity=0.05)+ z_des = 0.275+ up = np.array([0.0, 0.0, -1.0])+ n_obs, n_priv = 42, 42 + 3 + 3 + 3 + 3 + 12 + 12 + 12 + 1++ def __init__(self, seed=0):+ super().__init__(seed)+ c = (self.lo + self.hi) / 2; r = self.hi - self.lo+ self.soft_lo, self.soft_hi = c - 0.5 * r * 0.95, c + 0.5 * r * 0.95++ def random_qpos(self) -> np.ndarray:+ q = np.zeros(self.m.nq); q[2] = 0.5+ quat = self.rng.normal(size=4); q[3:7] = quat / (np.linalg.norm(quat) + 1e-6)+ q[7:] = self.rng.uniform(self.lo, self.hi)+ return q++ def reset_to(self, qpos: np.ndarray, qvel: np.ndarray) -> None:+ mujoco.mj_resetData(self.m, self.d)+ self.d.qpos[:] = qpos; self.d.qvel[:] = qvel+ mujoco.mj_forward(self.m, self.d)+ self.sim(qpos[7:], n=round(0.5 / self.m.opt.timestep)) # settle 0.5 s with ctrl = joints (getup.py:189)+ self.d.time = 0.0++ def reset(self):+ qpos = self.random_qpos() if self.rng.random() < 0.6 else self.home.copy()+ qvel = np.zeros(self.m.nv); qvel[:6] = self.rng.uniform(-0.5, 0.5, 6)+ self.reset_to(qpos, qvel)+ self.last_act = np.zeros(12); self.last_last_act = np.zeros(12)+ return self.obs()++ def gravity(self):+ return self.imu_xmat().T @ np.array([0, 0, -1.0])++ def obs(self):+ ns = self.noise_scales+ gyro, grav = self.sensor("gyro"), self.gravity()+ q, qd = self.d.qpos[7:].copy(), self.d.qvel[6:].copy()+ state = np.concatenate([self.noise(gyro, ns["gyro"]), self.noise(grav, ns["gravity"]),+ self.noise(q, ns["joint_pos"]) - self.default_pose, self.noise(qd, ns["joint_vel"]),+ self.last_act])+ priv = np.concatenate([state, gyro, self.sensor("accelerometer"), self.sensor("local_linvel"),+ self.sensor("global_angvel"), q, qd, self.d.actuator_force, [self.d.site_xpos[self.imu][2]]])+ return state, priv++ def step(self, a):+ self.sim(self.d.qpos[7:] + a * self.action_scale)+ g = self.gravity(); h = self.d.site_xpos[self.imu][2]+ upright = np.sum((self.up - g) ** 2) < 0.01+ at_h = self.z_des - min(h, self.z_des) < 0.005+ q = self.d.qpos[7:]; tau = self.d.actuator_force+ r = dict(+ orientation=np.exp(-2.0 * np.sum((self.up - g) ** 2)),+ torso_height=np.exp(min(h, self.z_des)) - 1.0,+ posture=upright * np.exp(-0.5 * np.sum((q - self.default_pose) ** 2)),+ stand_still=upright * at_h * np.exp(-0.5 * np.sum(a ** 2)),+ action_rate=np.sum((a - self.last_act) ** 2) + np.sum((a - 2 * self.last_act + self.last_last_act) ** 2),+ torques=np.sqrt(np.sum(tau ** 2)) + np.sum(np.abs(tau)),+ dof_pos_limits=np.sum(-np.clip(q - self.soft_lo, None, 0) + np.clip(q - self.soft_hi, 0, None)),+ dof_acc=np.sum(self.d.qacc[6:] ** 2),+ dof_vel=np.sum(np.maximum(np.abs(self.d.qvel[6:]) - 2 * np.pi, 0) ** 2),+ )+ reward = float(np.clip(sum(self.scales[k] * v for k, v in r.items()) * self.ctrl_dt, 0, 1e4))+ self.last_last_act = self.last_act; self.last_act = a.copy()+ return (*self.obs(), reward, False)+++# ------------------------------------------------------------------------------------------------- Go1 hand/footstand+class Go1Handstand(Env):+ """go1/handstand.py: from home (random xy/yaw/base velocity), balance on the front legs, nose down, at z_des."""++ name = "Go1Handstand"+ episode_length = 500+ kp, kd = 35.0, 0.5+ action_scale = 0.3+ z_des = 0.55+ desired_forward = np.array([0.0, 0.0, -1.0])+ pose_joints = np.arange(6, 12)+ scales = dict(height=1.0, orientation=1.0, contact=-0.1, dof_pos_limits=-0.5, pose=-0.1)+ noise_scales = dict(joint_pos=0.01, joint_vel=1.5, gyro=0.2, gravity=0.05, linvel=0.1)+ unwanted = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # Footstand inherits this front-leg list (handstand.py)++ def __init__(self, seed=0):+ super().__init__(seed)+ c = (self.lo + self.hi) / 2; r = self.hi - self.lo+ self.soft_lo, self.soft_hi = c - 0.5 * r * 0.9, c + 0.5 * r * 0.9+ self.unwanted_s = [self._sens[f"{g}_floor_found"][0] for g in self.unwanted]+ self.feet_s = [self._sens[f"{f}_floor_found"][0] for f in ("FR", "FL", "RR", "RL")]++ def reset(self):+ q = self.home.copy(); q[0:2] += self.rng.uniform(-0.5, 0.5, 2)+ yaw = self.rng.uniform(-3.14, 3.14); q[3:7] = [np.cos(yaw / 2), 0, 0, np.sin(yaw / 2)]+ mujoco.mj_resetData(self.m, self.d)+ self.d.qpos[:] = q; self.d.qvel[:6] = self.rng.uniform(-0.5, 0.5, 6); self.d.ctrl[:] = q[7:]+ mujoco.mj_forward(self.m, self.d)+ self.last_act = np.zeros(12)+ return self.obs()++ def gravity(self):+ return self.imu_xmat().T @ np.array([0, 0, -1.0])++ def obs(self):+ ns = self.noise_scales+ lin, gyro, grav = self.sensor("local_linvel"), self.sensor("gyro"), self.gravity()+ q, qd = self.d.qpos[7:].copy(), self.d.qvel[6:].copy()+ state = np.concatenate([self.noise(lin, ns["linvel"]), self.noise(gyro, ns["gyro"]), self.noise(grav, ns["gravity"]),+ self.noise(q, ns["joint_pos"]) - self.default_pose, self.noise(qd, ns["joint_vel"]),+ self.last_act])+ priv = np.concatenate([state, gyro, self.sensor("accelerometer"), lin, self.sensor("global_angvel"), q, qd,+ self.d.actuator_force, [self.d.site_xpos[self.imu][2]]])+ return state, priv++ def step(self, a):+ self.sim(self.d.ctrl + a * self.action_scale) # targets accumulate in ctrl space (handstand.py:203)+ sd = self.d.sensordata+ bad_contact = any(sd[i] > 0 for i in self.unwanted_s)+ done = self.d.site_xmat[self.imu].reshape(3, 3)[2, 2] < -0.25 or bad_contact+ fwd = self.imu_xmat() @ np.array([1.0, 0, 0]); h = self.d.site_xpos[self.imu][2]; q = self.d.qpos[7:]+ r = dict(+ height=np.exp(-(self.z_des - min(h, self.z_des))),+ orientation=(0.5 * fwd @ self.desired_forward + 0.5) ** 2,+ contact=float(any(sd[i] > 0 for i in self.feet_s)),+ dof_pos_limits=np.sum(-np.clip(q - self.soft_lo, None, 0) + np.clip(q - self.soft_hi, 0, None)),+ pose=np.sum((q[self.pose_joints] - self.default_pose[self.pose_joints]) ** 2),+ )+ reward = float(np.clip(sum(self.scales[k] * v for k, v in r.items()) * self.ctrl_dt, 0, 1e4))+ self.last_act = a.copy()+ return (*self.obs(), reward, bool(done))+++class Go1Footstand(Go1Handstand):+ name = "Go1Footstand"+ z_des = 0.53+ desired_forward = np.array([0.0, 0.0, 1.0])+ pose_joints = np.arange(0, 6)+++class Go1FootstandStrict(Go1Footstand):+ """Go1Footstand plus the termination Playground's Footstand sets up but never reads (handstand.py: _post_init+ assigns the hind-leg geoms to _unwanted_contact_geom_ids, the termination reads the inherited front-leg sensors):+ a hind leg's hip, thigh or calf touching the floor ends the episode too. Without it the policy sits on a hind hip."""++ name = "Go1FootstandStrict"+ scene = "Go1Footstand"+ hind = ["rl_calf1", "rl_calf2", "rr_calf1", "rr_calf2", "rl_thigh1", "rl_thigh2", "rl_thigh3", "rr_thigh1",+ "rr_thigh2", "rr_thigh3", "rl_hip", "rr_hip"]++ def __init__(self, seed=0):+ super().__init__(seed)+ self.floor = self.m.geom("floor").id+ self.hind_ids = {self.m.geom(g).id for g in self.hind}++ def step(self, a):+ state, priv, reward, done = super().step(a)+ return state, priv, reward, done or self.hind_contact()++ def hind_contact(self) -> bool:+ d = self.d+ for i in range(d.ncon):+ g1, g2 = d.contact[i].geom1, d.contact[i].geom2+ if (g1 == self.floor and g2 in self.hind_ids) or (g2 == self.floor and g1 in self.hind_ids):+ return True+ return False+++class Go1FootstandStrict2(Go1FootstandStrict):+ """Go1FootstandStrict trained from scratch with a start curriculum (training only): half of the episodes start in+ Playground's `footstand` keyframe (small joint and base-velocity noise), so balancing is learnt before rearing up;+ the other half start as Playground's reset does."""++ name = "Go1FootstandStrict2"++ def reset(self):+ if self.rng.random() < 0.5:+ return super().reset()+ kf = self.m.keyframe("footstand")+ mujoco.mj_resetData(self.m, self.d)+ self.d.qpos[:] = kf.qpos+ self.d.qpos[7:] += self.rng.uniform(-0.05, 0.05, 12)+ self.d.qvel[:6] = self.rng.uniform(-0.2, 0.2, 6)+ self.d.ctrl[:] = self.d.qpos[7:]+ mujoco.mj_forward(self.m, self.d)+ self.last_act = np.zeros(12)+ return self.obs()+++# --------------------------------------------------------------------------------------------------------- Spot getup+class SpotGetup(Env):+ """spot/getup.py: recover from a drop from 1 m in a random orientation (p = 0.6) or the home pose."""++ name = "SpotGetup"+ episode_length = 300+ kp, kd = 400.0, 20.0+ action_scale = 0.6+ scales = dict(orientation=1.0, torso_height=1.0, posture=1.0, stand_still=1.0)+ noise_scales = dict(joint_pos=0.01, gyro=0.2, gravity=0.05)+ up = np.array([0.0, 0.0, 1.0])++ def __init__(self, seed=0):+ super().__init__(seed)+ self.z_des = self.home[2]++ def reset(self):+ if self.rng.random() < 0.6:+ q = np.zeros(self.m.nq); q[2] = 1.0+ quat = self.rng.normal(size=4); q[3:7] = quat / (np.linalg.norm(quat) + 1e-6)+ q[7:] = self.rng.uniform(self.ctrl_lo, self.ctrl_hi)+ else:+ q = self.home.copy()+ mujoco.mj_resetData(self.m, self.d)+ self.d.qpos[:] = q+ mujoco.mj_forward(self.m, self.d)+ self.sim(q[7:], n=round(0.5 / self.m.opt.timestep)); self.d.time = 0.0+ self.last_act = np.zeros(12)+ return self.obs()++ def obs(self):+ ns = self.noise_scales+ gyro, up = self.sensor("gyro"), self.sensor("upvector")+ q = self.d.qpos[7:].copy()+ state = np.concatenate([self.noise(gyro, ns["gyro"]), self.noise(up, ns["gravity"]),+ self.noise(q, ns["joint_pos"]) - self.default_pose, self.last_act])+ priv = np.concatenate([state, gyro, up, q, self.d.qvel.copy(), [self.d.qpos[2]], self.d.actuator_force])+ return state, priv++ def step(self, a):+ self.sim(np.clip(self.d.qpos[7:] + a * self.action_scale, self.ctrl_lo, self.ctrl_hi))+ q = self.d.qpos[7:]; up = self.sensor("upvector"); z = self.d.qpos[2]+ done = bool(np.any(q < self.ctrl_lo) or np.any(q > self.ctrl_hi))+ upright = np.sum((self.up - up) ** 2) < 0.01+ h_err = np.clip((self.z_des - z) / self.z_des, 0, 1)+ r = dict(orientation=np.exp(-2.0 * np.sum((self.up - up) ** 2)), torso_height=1.0 - h_err,+ posture=upright * np.exp(-0.5 * np.sum((q - self.default_pose) ** 2)),+ stand_still=upright * (h_err < 0.005) * np.exp(-0.5 * np.sum(a ** 2)))+ reward = float(np.clip(sum(self.scales[k] * v for k, v in r.items()) * self.ctrl_dt, 0, 1e4))+ self.last_act = a.copy()+ return (*self.obs(), reward, done)+++# ------------------------------------------------------------------------------------------------ Spot joystick+class SpotFlatTerrainJoystick(Env):+ """spot/joystick.py (task flat_terrain): track (vx, vy, wz) commands from the home pose; perturbations off (its+ default config); a command redrawn every 201 control steps (zero with p = 0.1); termination: upvector z < 0.85."""++ name = "SpotFlatTerrainJoystick"+ episode_length = 1000+ kp, kd = 300.0, 1.0+ action_scale = 0.3+ cmd_lo = np.array([-1.0, -0.8, -1.0])+ cmd_hi = np.array([1.0, 0.8, 1.0])+ scales = dict(tracking_lin_vel=1.5, tracking_ang_vel=0.8, lin_vel_z=-2.0, ang_vel_xy=-0.05, orientation=-5.0,+ termination=-1.0, posture=1.0, torques=-0.0002, action_rate=-0.01, energy=-0.001, feet_slip=-0.1,+ feet_clearance=-2.0, feet_height=-0.1, feet_air_time=0.1)+ sigma, max_foot_height = 0.25, 0.12+ feet = ("FL", "FR", "HL", "HR")++ def __init__(self, seed=0):+ super().__init__(seed)+ self.foot_site = np.array([self.m.site(f).id for f in self.feet])+ self.contact_s = [self._sens[f"{f}_floor_found"][0] for f in self.feet]++ def sample_command(self):+ if self.rng.random() < 0.1:+ return np.zeros(3)+ return self.rng.uniform(self.cmd_lo, self.cmd_hi)++ def reset(self):+ mujoco.mj_resetData(self.m, self.d)+ self.d.qpos[:] = self.home+ mujoco.mj_forward(self.m, self.d)+ self.cmd = self.sample_command()+ self.step_i = 0+ self.last_act = np.zeros(12); self.last_last_act = np.zeros(12)+ self.motor_targets = np.zeros(12)+ self.err_hist = np.zeros(36)+ self.air = np.zeros(4); self.last_contact = np.zeros(4, bool); self.swing_peak = np.zeros(4)+ return self.obs()++ def feet_pos(self):+ return np.concatenate([self.sensor(f"{f}_pos") for f in self.feet])++ def obs(self):+ gyro, up = self.sensor("gyro"), self.sensor("upvector")+ q = self.d.qpos[7:].copy()+ nq = self.noise(q, 0.05)+ fp = self.feet_pos().reshape(4, 3)+ if self.obs_noise:+ for ax, sc in enumerate((0.01, 0.005, 0.02)):+ fp[:, ax] += (2 * self.rng.random(4) - 1) * sc+ self.err_hist = np.roll(self.err_hist, 12)+ self.err_hist[:12] = nq - self.motor_targets+ state = np.concatenate([self.noise(gyro, 0.1), self.noise(up, 0.03), nq - self.default_pose, self.err_hist,+ fp.ravel(), self.last_act, self.cmd])+ feet_v = np.concatenate([self.sensor(f"{f}_global_linvel") for f in self.feet])+ priv = np.concatenate([state, gyro, self.sensor("accelerometer"), up, self.sensor("local_linvel"),+ self.sensor("global_angvel"), q - self.default_pose, self.feet_pos(), self.d.qvel[6:],+ self.d.actuator_force, self.last_contact.astype(float), feet_v, self.air, np.zeros(3)])+ return state, priv++ def step(self, a):+ self.motor_targets = np.clip(self.default_pose + a * self.action_scale, self.ctrl_lo, self.ctrl_hi)+ self.sim(self.motor_targets)+ sd = self.d.sensordata+ contact = np.array([sd[i] > 0 for i in self.contact_s])+ contact_filt = contact | self.last_contact+ first = (self.air > 0) * contact_filt+ self.air += self.ctrl_dt+ pz = self.d.site_xpos[self.foot_site][:, 2]+ self.swing_peak = np.maximum(self.swing_peak, pz)+ up = self.sensor("upvector")+ done = bool(up[2] < 0.85)+ lin, gyro = self.sensor("local_linvel"), self.sensor("gyro")+ glin, gang = self.sensor("global_linvel"), self.sensor("global_angvel")+ feet_v = np.array([self.sensor(f"{f}_global_linvel") for f in self.feet])+ cmd_norm = np.linalg.norm(self.cmd)+ tau = self.d.actuator_force+ vxy = feet_v[:, :2]+ r = dict(+ tracking_lin_vel=np.exp(-np.sum((self.cmd[:2] - lin[:2]) ** 2) / self.sigma),+ tracking_ang_vel=np.exp(-((self.cmd[2] - gyro[2]) ** 2) / self.sigma),+ lin_vel_z=glin[2] ** 2,+ ang_vel_xy=np.sum(gang[:2] ** 2),+ orientation=np.sum(up[:2] ** 2),+ termination=float(done),+ posture=np.exp((-10.0 if cmd_norm < 0.01 else 0.0) * np.sum((self.d.qpos[7:] - self.default_pose) ** 2)),+ torques=np.sqrt(np.sum(tau ** 2)) + np.sum(np.abs(tau)),+ action_rate=np.sum((a - self.last_act) ** 2) + np.sum((a - 2 * self.last_act + self.last_last_act) ** 2),+ energy=np.sum(np.abs(self.d.qvel[6:]) * np.abs(tau)),+ feet_slip=np.sum(np.sum(vxy ** 2, axis=1) * contact),+ feet_clearance=np.sum(np.abs(pz - self.max_foot_height) * np.sqrt(np.linalg.norm(vxy, axis=1))),+ feet_height=np.sum((self.swing_peak / self.max_foot_height - 1.0) ** 2 * first) * (cmd_norm >= 0.01),+ feet_air_time=np.sum((self.air - 0.1) * first) * (cmd_norm >= 0.01),+ )+ reward = float(np.clip(sum(self.scales[k] * v for k, v in r.items()) * self.ctrl_dt, 0, 1e4))+ self.last_last_act = self.last_act; self.last_act = a.copy()+ self.step_i += 1+ if self.step_i > 200:+ self.cmd = self.sample_command(); self.step_i = 0+ self.air *= ~contact; self.last_contact = contact; self.swing_peak *= ~contact+ return (*self.obs(), reward, done)+++# ------------------------------------------------------------------------------------------------ Barkour joystick+class BarkourJoystick(Env):+ """barkour/joystick.py: track (vx, vy, wz) under random pushes. Its model keeps the XML's 2 ms timestep while the+ env takes round(ctrl_dt / sim_dt) = 5 substeps, so one control step is 10 ms of simulated time (as upstream).+ Command at reset and redrawn after step 500; a push every kick_wait_steps (50-149) steps lasting 1-9 steps;+ termination: upvector z < 0, a joint outside [lowers, uppers], torso z < 0.18. Observation: 15 frames of 31."""++ name = "BarkourJoystick"+ imu_site = "imu_frame"+ episode_length = 1000+ action_scale = 0.3+ lowers = np.array([-0.7, -1.0, 0.05] * 4)+ uppers = np.array([0.52, 2.1, 2.1] * 4)+ scales = dict(tracking_lin_vel=1.5, tracking_ang_vel=0.8, lin_vel_z=-2.0, ang_vel_xy=-0.05, orientation=-5.0,+ torques=-0.0002, action_rate=-0.1, stand_still=-0.5, termination=-1.0, feet_air_time=0.2)+ sigma = 0.25++ def edit_model(self, m):+ m.dof_damping[6:] = 0.5239+ m.actuator_gainprm[:, 0] = 35.0+ m.actuator_biasprm[:, 1] = -35.0++ def __init__(self, seed=0):+ super().__init__(seed)+ self.n_sub = 5+ self.torso = self.m.body("torso").id+ self.torso_mass = self.m.body_subtreemass[self.torso]+ self.contact_s = [self._sens[f"{g}_floor_found"][0] for g in BARKOUR_FEET]++ def sample_command(self):+ return self.rng.uniform([-0.6, -0.8, -0.7], [1.5, 0.8, 0.7])++ def reset(self):+ mujoco.mj_resetData(self.m, self.d)+ self.d.qpos[:] = self.home+ mujoco.mj_forward(self.m, self.d)+ self.cmd = self.sample_command()+ self.kick_wait = int(self.rng.integers(50, 150)); self.kick_dur = int(self.rng.integers(1, 10))+ self.vel_kick = self.rng.uniform(0.1, 1.0); self.kick_dir = np.zeros(3); self.last_kick = -np.inf+ self.step_i = 0+ self.last_act = np.zeros(12); self.air = np.zeros(4); self.last_contact = np.zeros(4, bool)+ self.hist = np.zeros(15 * 31)+ return self.obs()++ def obs(self):+ o = np.concatenate([self.sensor("gyro")[2:3] * 0.25, self.sensor("upvector"), self.cmd * np.array([2.0, 2.0, 0.25]),+ self.d.qpos[7:] - self.default_pose, self.last_act])+ o = np.clip(o, -100, 100)+ if self.obs_noise:+ o = o + 0.05 * self.rng.uniform(-1, 1, o.shape)+ self.hist = np.roll(self.hist, o.size); self.hist[:o.size] = o+ priv = np.concatenate([self.hist[:31], self.sensor("local_linvel"), self.sensor("global_angvel"), self.d.qvel[6:],+ [self.d.xpos[self.torso][2]], self.cmd, self.d.xfrc_applied[self.torso, :3] / 100.0])+ return self.hist.copy(), priv++ def push(self):+ start = self.step_i % self.kick_wait == 0 and self.step_i != 0+ if start:+ ang = self.rng.uniform(0, 2 * np.pi); self.kick_dir = np.array([np.cos(ang), np.sin(ang), 0.0])+ self.last_kick = self.step_i+ dur = max(self.step_i - self.last_kick, 0)+ self.d.xfrc_applied[:] = 0+ if dur < self.kick_dur:+ u = 0.5 * np.sin(np.pi * dur / self.kick_dur)+ self.d.xfrc_applied[self.torso, :3] = u * self.torso_mass * self.vel_kick / (self.kick_dur * self.ctrl_dt) * self.kick_dir++ def step(self, a):+ self.push()+ self.sim(np.clip(self.default_pose + a * self.action_scale, self.lowers, self.uppers))+ q = self.d.qpos[7:]+ contact = np.array([self.d.sensordata[i] > 0 for i in self.contact_s])+ first = (self.air > 0) * (contact | self.last_contact)+ self.air += self.ctrl_dt+ up = self.sensor("upvector")+ done = bool(up[2] < 0 or np.any(q < self.lowers) or np.any(q > self.uppers) or self.d.xpos[self.torso][2] < 0.18)+ lin, gyro = self.sensor("local_linvel"), self.sensor("gyro")+ unit = self.cmd[:2] / (np.linalg.norm(self.cmd[:2]) + 1e-12)+ r = dict(+ tracking_lin_vel=np.exp(-np.sum((self.cmd[:2] - lin[:2]) ** 2) / self.sigma),+ tracking_ang_vel=np.exp(-((self.cmd[2] - gyro[2]) ** 2) / self.sigma),+ lin_vel_z=self.sensor("global_linvel")[2] ** 2,+ ang_vel_xy=np.sum(self.sensor("global_angvel")[:2] ** 2),+ orientation=np.sum(up[:2] ** 2),+ torques=np.sqrt(np.sum(self.d.qfrc_actuator ** 2)) + np.sum(np.abs(self.d.qfrc_actuator)),+ action_rate=np.sum((a - self.last_act) ** 2),+ stand_still=np.sum(np.abs(q - self.default_pose)) * (unit[1] < 0.1),+ termination=float(done and self.step_i < 500),+ feet_air_time=np.sum((self.air - 0.1) * first) * (np.linalg.norm(self.cmd[:2]) > 0.05),+ )+ reward = float(np.clip(sum(self.scales[k] * v for k, v in r.items()) * self.ctrl_dt, 0, 1e4))+ self.last_act = a.copy()+ self.step_i += 1+ if self.step_i > 500:+ self.cmd = self.sample_command(); self.step_i = 0+ self.air *= ~contact; self.last_contact = contact+ return (*self.obs(), reward, done)+++# ----------------------------------------------------------------------------------------- Spot gait tracking+GAIT_PHASES = np.array([[0, np.pi, np.pi, 0], [0, 0.5 * np.pi, np.pi, 1.5 * np.pi], [0, np.pi, 0, np.pi],+ [0, 0, np.pi, np.pi], [0, 0, 0, 0]]) # trot, walk, pace, bound, pronk; feet FL, FR, HL, HR+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (phi + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0, swing_height, 2 * x), bez(swing_height, 0, 2 * x - 1))+++class SpotJoystickGaitTracking(SpotFlatTerrainJoystick):+ """spot/joystick_gait_tracking.py: joystick commands plus a gait (type, frequency 0.5-4 Hz, foot height 0.08-0.4 m)+ fixed per episode; reward = (sum of positive terms) * exp(0.2 * sum of negative terms) * dt, not clipped."""++ name = "SpotJoystickGaitTracking"+ kp, kd = 400.0, 10.0+ action_scale = 0.6+ cmd_lo = np.array([-1.0, -0.5, -1.0])+ cmd_hi = np.array([1.0, 0.5, 1.0])+ pos_scales = dict(feet_phase=2.0, tracking_lin_vel=0.5, tracking_ang_vel=0.5)+ neg_scales = dict(ang_vel_xy=-0.5, lin_vel_z=-0.5, hip_splay=-0.5)++ def reset(self):+ self.gait_freq = self.rng.uniform(0.5, 4.0)+ self.phase_dt = 2 * np.pi * self.ctrl_dt * self.gait_freq+ self.gait = int(self.rng.integers(0, 5))+ self.phase = GAIT_PHASES[self.gait].copy()+ self.foot_height = self.rng.uniform(0.08, 0.4)+ return super().reset()++ def obs(self):+ gyro, up = self.sensor("gyro"), self.sensor("upvector")+ q = self.d.qpos[7:].copy()+ nq = self.noise(q, 0.05)+ self.err_hist = np.roll(self.err_hist, 12)+ self.err_hist[:12] = nq - self.motor_targets+ contact = np.array([self.d.sensordata[i] > 0 for i in self.contact_s], dtype=float)+ state = np.concatenate([self.noise(gyro, 0.1), self.noise(up, 0.03), nq, self.err_hist, contact,+ np.cos(self.phase), np.sin(self.phase), [self.gait_freq, self.gait, self.foot_height]])+ priv = np.concatenate([state, self.sensor("local_linvel"), self.sensor("global_angvel"), self.d.qvel[6:],+ self.d.site_xpos[self.foot_site][:, 2], self.cmd])+ return state, priv++ def step(self, a):+ self.motor_targets = np.clip(self.default_pose + a * self.action_scale, self.ctrl_lo, self.ctrl_hi)+ self.sim(self.motor_targets)+ contact = np.array([self.d.sensordata[i] > 0 for i in self.contact_s])+ up = self.sensor("upvector")+ done = bool(up[2] < 0.85)+ lin, gyro = self.sensor("local_linvel"), self.sensor("gyro")+ fz = self.d.site_xpos[self.foot_site][:, 2]+ pos = dict(feet_phase=np.exp(-np.sum((fz - gait_rz(self.phase, self.foot_height)) ** 2) / 0.1),+ tracking_lin_vel=np.exp(-np.sum((self.cmd[:2] - lin[:2]) ** 2) / self.sigma),+ tracking_ang_vel=np.exp(-((self.cmd[2] - gyro[2]) ** 2) / self.sigma))+ neg = dict(ang_vel_xy=np.sum(self.sensor("global_angvel")[:2] ** 2),+ lin_vel_z=self.sensor("global_linvel")[2] ** 2 * (self.gait > 2),+ hip_splay=np.sum((self.d.qpos[7:][[0, 3, 6, 9]] - self.default_pose[[0, 3, 6, 9]]) ** 2))+ reward = float(sum(self.pos_scales[k] * v for k, v in pos.items())+ * np.exp(0.2 * sum(self.neg_scales[k] * v for k, v in neg.items())) * self.ctrl_dt)+ self.last_last_act = self.last_act; self.last_act = a.copy()+ self.step_i += 1+ self.phase = np.fmod(self.phase + self.phase_dt + np.pi, 2 * np.pi) - np.pi+ if self.step_i > 200:+ self.cmd = self.sample_command(); self.step_i = 0+ self.last_contact = contact+ return (*self.obs(), reward, done)++++class Go1FootstandStrict3(Go1FootstandStrict2):+ """Go1FootstandStrict2 fine-tuned with a steeper height reward (training only): exp(-(z_des - min(h, z_des)) / 0.1)+ at scale 3 instead of Playground's exp(-(z_des - min(h, z_des))) at scale 1, which leaves a squat on the hind feet+ (IMU at 0.2 m, trunk 30 deg from vertical) at 72% of the standing reward."""++ name = "Go1FootstandStrict3"++ def step(self, a):+ state, priv, reward, done = super().step(a)+ h = self.d.site_xpos[self.imu][2]+ old = np.exp(-(self.z_des - min(h, self.z_des)))+ new = 3.0 * np.exp(-(self.z_des - min(h, self.z_des)) / 0.1)+ return state, priv, max(0.0, reward + (new - old) * self.ctrl_dt), done+++class SpotJoystickGaitTrackingCmd(SpotJoystickGaitTracking):+ """SpotJoystickGaitTracking with the command in the policy's observation (72 = Playground's 69 + vx, vy, wz).+ Playground's observation leaves the command out, so a policy trained on it cannot track the joystick, which its+ reward asks for; this is how the reference for that task is trained."""++ name = "SpotJoystickGaitTrackingCmd"+ scene = "SpotJoystickGaitTracking"++ def obs(self):+ state, priv = super().obs()+ return np.concatenate([state, self.cmd]), priv+++ENVS = {c.name: c for c in (Go1Getup, Go1Handstand, Go1Footstand, Go1FootstandStrict, Go1FootstandStrict2,+ Go1FootstandStrict3, SpotGetup,+ SpotFlatTerrainJoystick, BarkourJoystick, SpotJoystickGaitTracking,+ SpotJoystickGaitTrackingCmd)}diff --git a/scripts/mujoco-playground/train/run_capped.sh b/scripts/mujoco-playground/train/run_capped.shnew file mode 100755index 0000000000..b5c005d46b--- /dev/null+++ b/scripts/mujoco-playground/train/run_capped.sh@@ -0,0 +1,6 @@+#!/bin/bash+# Run one training under a hard memory cap (systemd user scope): at the cap the kernel stops this run, not other+# users' jobs. PYTHON: an interpreter with mujoco==3.3.7, torch, rsl-rl-lib, tensordict.+HERE=$(cd "$(dirname "$0")" && pwd)+exec systemd-run --user --scope -q -p MemoryMax=${RCB_MEM_MAX:-48G} -p MemorySwapMax=0 \+ ${PYTHON:-python} -u "$HERE/train.py" "$@"diff --git a/scripts/mujoco-playground/train/train.py b/scripts/mujoco-playground/train/train.pynew file mode 100644index 0000000000..0d41272aaa--- /dev/null+++ b/scripts/mujoco-playground/train/train.py@@ -0,0 +1,50 @@+"""Train one env with rsl_rl PPO on CPU (Playground's rsl_rl hyperparameters).++ python train.py Go1Getup --iters 1000 --envs 2048 --workers 16 --out runs/go1_getup+Writes runs/<out>/model_<it>.pt (rsl_rl checkpoints) and policy.pt (TorchScript, deterministic actor)."""+import argparse, os, sys, time+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import torch+from rsl_rl.runners import OnPolicyRunner+from vecenv import CpuVecEnv++ap = argparse.ArgumentParser()+ap.add_argument("env"); ap.add_argument("--iters", type=int, default=1000); ap.add_argument("--envs", type=int, default=2048)+ap.add_argument("--workers", type=int, default=16); ap.add_argument("--out", required=True); ap.add_argument("--seed", type=int, default=1)+ap.add_argument("--lr", type=float, default=3e-4); ap.add_argument("--entropy", type=float, default=0.001)+ap.add_argument("--steps", type=int, default=24); ap.add_argument("--resume", default="")+ap.add_argument("--threads", type=int, default=8)+a = ap.parse_args()+torch.set_num_threads(a.threads)++cfg = {+ "seed": a.seed, "num_steps_per_env": a.steps, "save_interval": 50, "check_for_nan": True,+ "obs_groups": {"actor": ["state"], "critic": ["privileged_state"]},+ "logger": "tensorboard", "experiment_name": a.env, "run_name": "",+ "algorithm": {"class_name": "PPO", "value_loss_coef": 1.0, "use_clipped_value_loss": True, "clip_param": 0.2,+ "entropy_coef": a.entropy, "num_learning_epochs": 5, "num_mini_batches": 4, "learning_rate": a.lr,+ "schedule": "fixed", "gamma": 0.99, "lam": 0.95, "desired_kl": 0.01, "max_grad_norm": 1.0},+ "actor": {"class_name": "MLPModel", "hidden_dims": [512, 256, 128], "activation": "elu", "obs_normalization": True,+ "distribution_cfg": {"class_name": "GaussianDistribution", "init_std": 1.0}},+ "critic": {"class_name": "MLPModel", "hidden_dims": [512, 256, 128], "activation": "elu", "obs_normalization": True},+}+env = CpuVecEnv(a.env, num_envs=a.envs, workers=a.workers, seed=a.seed)+os.makedirs(a.out, exist_ok=True)+runner = OnPolicyRunner(env, cfg, a.out, device="cpu")+resume = a.resume or (open(a.out.rstrip("/") + ".resume").read().strip() if os.path.exists(a.out.rstrip("/") + ".resume") else "")+if resume: # --resume, or <out>.resume holding a checkpoint path (how a queued job fine-tunes)+ runner.load(resume)+ print(f"resumed from {resume}", flush=True)+t0 = time.time()+chunk = 50+done_it = 0+while done_it < a.iters:+ n = min(chunk, a.iters - done_it)+ runner.learn(num_learning_iterations=n)+ done_it += n+ import numpy as np+ r = np.mean(env.done_rets) if env.done_rets else float("nan"); L = np.mean(env.done_lens) if env.done_lens else float("nan")+ print(f"[{a.env}] it {done_it}/{a.iters} ep_return {r:.3f} ep_len {L:.0f} elapsed {time.time() - t0:.0f}s", flush=True)+ runner.save(os.path.join(a.out, f"model_{done_it}.pt"))+ runner.export_policy_to_jit(a.out, "policy.pt")+env.close()diff --git a/scripts/mujoco-playground/train/vecenv.py b/scripts/mujoco-playground/train/vecenv.pynew file mode 100644index 0000000000..b6395513f0--- /dev/null+++ b/scripts/mujoco-playground/train/vecenv.py@@ -0,0 +1,103 @@+"""Multiprocess vector env over qenv.Env for rsl_rl (VecEnv interface), CPU only.++W worker processes, E envs each; actions, observations, rewards and done flags go through shared memory, one pipe+message per step per worker. Episodes auto-reset; reaching episode_length is a time-out (truncation)."""+from __future__ import annotations++import multiprocessing as mp+from multiprocessing import shared_memory++import numpy as np+import torch+from tensordict import TensorDict++import qenv+++def _arr(shm, shape, dtype=np.float32):+ return np.ndarray(shape, dtype=dtype, buffer=shm.buf)+++def _worker(name, seed, lo, hi, shm_names, shapes, conn, env_kwargs):+ import os+ os.environ["OMP_NUM_THREADS"] = "1"+ envs = [qenv.ENVS[name](seed=seed + i, **env_kwargs) for i in range(lo, hi)]+ shms = {k: shared_memory.SharedMemory(name=v) for k, v in shm_names.items()}+ A = _arr(shms["act"], shapes["act"]); O = _arr(shms["obs"], shapes["obs"]); P = _arr(shms["priv"], shapes["priv"])+ R = _arr(shms["rew"], shapes["rew"]); D = _arr(shms["done"], shapes["done"]); T = _arr(shms["trunc"], shapes["trunc"])+ t = np.zeros(hi - lo, int)+ while True:+ cmd = conn.recv()+ if cmd == "reset":+ for j, e in enumerate(envs):+ o, p = e.reset(); O[lo + j], P[lo + j] = o, p; t[j] = 0+ elif cmd == "step":+ for j, e in enumerate(envs):+ o, p, r, done = e.step(A[lo + j].astype(np.float64))+ t[j] += 1+ trunc = (not done) and t[j] >= e.episode_length+ if not np.all(np.isfinite(o)) or not np.isfinite(r):+ done, r = True, 0.0+ R[lo + j] = r; D[lo + j] = float(done or trunc); T[lo + j] = float(trunc)+ if done or trunc:+ o, p = e.reset(); t[j] = 0+ O[lo + j], P[lo + j] = o, p+ elif cmd == "close":+ break+ conn.send("ok")+++class CpuVecEnv:+ def __init__(self, name: str, num_envs: int = 2048, workers: int = 16, seed: int = 0, env_kwargs=None):+ env_kwargs = env_kwargs or {}+ probe = qenv.ENVS[name](seed=0, **env_kwargs)+ self.num_envs, self.num_actions = num_envs, probe.m.nu+ self.max_episode_length = probe.episode_length+ self.device = "cpu"; self.cfg = {"env": name}+ o, p = probe.reset()+ shapes = {"act": (num_envs, self.num_actions), "obs": (num_envs, len(o)), "priv": (num_envs, len(p)),+ "rew": (num_envs,), "done": (num_envs,), "trunc": (num_envs,)}+ self._shm = {k: shared_memory.SharedMemory(create=True, size=int(np.prod(s)) * 4) for k, s in shapes.items()}+ self.A, self.O, self.P = (_arr(self._shm[k], shapes[k]) for k in ("act", "obs", "priv"))+ self.R, self.D, self.T = (_arr(self._shm[k], shapes[k]) for k in ("rew", "done", "trunc"))+ ctx = mp.get_context("fork")+ bounds = np.linspace(0, num_envs, workers + 1).astype(int)+ self.conns, self.procs = [], []+ for w in range(workers):+ a, b = ctx.Pipe()+ pr = ctx.Process(target=_worker, args=(name, seed * 100003, bounds[w], bounds[w + 1],+ {k: v.name for k, v in self._shm.items()}, shapes, b, env_kwargs),+ daemon=True)+ pr.start(); self.conns.append(a); self.procs.append(pr)+ self._broadcast("reset")+ self.ep_ret = np.zeros(num_envs); self.ep_len = np.zeros(num_envs); self.done_rets = []; self.done_lens = []++ def _broadcast(self, cmd):+ for c in self.conns: c.send(cmd)+ for c in self.conns: c.recv()++ def _obs(self):+ return TensorDict({"state": torch.from_numpy(self.O.copy()), "privileged_state": torch.from_numpy(self.P.copy())},+ batch_size=[self.num_envs])++ def get_observations(self):+ return self._obs()++ def step(self, actions: torch.Tensor):+ self.A[:] = torch.clip(actions, -1.0, 1.0).detach().cpu().numpy()+ self._broadcast("step")+ rew, done = self.R.copy(), self.D.copy()+ self.ep_ret += rew; self.ep_len += 1+ for i in np.nonzero(done)[0]:+ self.done_rets.append(self.ep_ret[i]); self.done_lens.append(self.ep_len[i]); self.ep_ret[i] = 0; self.ep_len[i] = 0+ self.done_rets = self.done_rets[-200:]; self.done_lens = self.done_lens[-200:]+ info = {"time_outs": torch.from_numpy(self.T.copy()), "log": {}}+ return self._obs(), torch.from_numpy(rew), torch.from_numpy(done), info++ def close(self):+ try:+ self._broadcast("close")+ except Exception:+ pass+ for s in self._shm.values():+ s.close(); s.unlink()diff --git a/tasks/dataset.toml b/tasks/dataset.tomlindex cb73cd5a7f..45d0314f31 100644--- a/tasks/dataset.toml+++ b/tasks/dataset.toml@@ -5045,3 +5045,75 @@ digest = "sha256:8e2b62005e21072cebd6c5e323d5ef97ea1f1da2713d8d3bc600031b414e48ename = "robot-coding-bench/myosuite-table-tennis-i00-standard"digest = "sha256:ab662facb27913488097bd11797981c6e1ac2eb0e340e159203ab1615feeeed1"+[[tasks]]+name = "robot-coding-bench/mujoco_playground_barkour_joystick-privileged"+digest = "sha256:828092965de333184aa998552c5752c3a4d894f73ff59af6f37d2107db0a6aba"++[[tasks]]+name = "robot-coding-bench/mujoco_playground_barkour_joystick-standard"+digest = "sha256:4ba0713bbcf0a57f4b386efb50d090dac819259fb827f65673a05143c9d06a83"++[[tasks]]+name = "robot-coding-bench/mujoco_playground_go1_footstand-privileged"+digest = "sha256:1ff2b00eea9e3788d9fd070e6ac86555361aee330d23f1cc42d922ab7c24f907"++[[tasks]]+name = "robot-coding-bench/mujoco_playground_go1_footstand-standard"+digest = "sha256:dc80e6ea38c4b3a419189feb9f43059f2471e1102ddf5db0dda53f4da948193b"++[[tasks]]+name = "robot-coding-bench/mujoco_playground_go1_getup-privileged"+digest = "sha256:ebbf79ff460f1be40a2ba4acb1bc7731a12c95958fe456d4ddb75ae9290c092c"++[[tasks]]+name = "robot-coding-bench/mujoco_playground_go1_getup-standard"+digest = "sha256:3b70296e47332ee434388567134a1cfab1d42be6617f2a0ba6182f8f16f7ce2f"++[[tasks]]+name = "robot-coding-bench/mujoco_playground_go1_handstand-privileged"+digest = "sha256:8b6399e4d9c18bcd9beaccc3269f271973353d0007f9c641b462097ecd698de7"++[[tasks]]+name = "robot-coding-bench/mujoco_playground_go1_handstand-standard"+digest = "sha256:bc70428f5cc113412ca7bb15e91ad9e1c0a2a6f6a751cf351a4e771f99717bd9"++[[tasks]]+name = "robot-coding-bench/mujoco_playground_go1_joystick_flat_terrain-privileged"+digest = "sha256:c101802a5e25b18933cec18c49afbb75375df2c0812b551755fcf66a4e206805"++[[tasks]]+name = "robot-coding-bench/mujoco_playground_go1_joystick_flat_terrain-standard"+digest = "sha256:5b6eee2f84286b7962379dede58e2fc7e7decd7b4c1e7cf22a03b84ed955e40e"++[[tasks]]+name = "robot-coding-bench/mujoco_playground_go1_joystick_rough_terrain-privileged"+digest = "sha256:1000f254d7a90f2464b489f21c76d4f2ca55676fa3941ea8fb0bcae46497c1f9"++[[tasks]]+name = "robot-coding-bench/mujoco_playground_go1_joystick_rough_terrain-standard"+digest = "sha256:0686d22af447da197451350280217fd8ed41aaac7c8a1733652258737e2531cc"++[[tasks]]+name = "robot-coding-bench/mujoco_playground_spot_flat_terrain_joystick-privileged"+digest = "sha256:420caa6a8d0ab249f457ad44af7347ed657fb2fb9ad005572c3b7b50202471f0"++[[tasks]]+name = "robot-coding-bench/mujoco_playground_spot_flat_terrain_joystick-standard"+digest = "sha256:1c0355c4563b73e2a8227fd39991684c4b63dac12259b7a16cbc742213335c7a"++[[tasks]]+name = "robot-coding-bench/mujoco_playground_spot_getup-privileged"+digest = "sha256:afb116c391de7e5c8e1bec743bf5731354d261322e1b12c8ff9add4a59046a79"++[[tasks]]+name = "robot-coding-bench/mujoco_playground_spot_getup-standard"+digest = "sha256:095b80a1dee58000996537b45db903ff4c082ecb7c81a99d149356eb2e8e02c5"++[[tasks]]+name = "robot-coding-bench/mujoco_playground_spot_joystick_gait_tracking-privileged"+digest = "sha256:a39156e282927ad7dbfa821c80111293caeb551ffc356a4b400822a5f26d0c88"++[[tasks]]+name = "robot-coding-bench/mujoco_playground_spot_joystick_gait_tracking-standard"+digest = "sha256:d1fc73ff53db47e6bb72e31f3c9b91e8e5956d79caf65e1c83777d2427b7f49e"+diff --git a/tasks/mujoco_playground_barkour_joystick-privileged/README.md b/tasks/mujoco_playground_barkour_joystick-privileged/README.mdnew file mode 100644index 0000000000..5b849cae1b--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-privileged/README.md@@ -0,0 +1,42 @@+# mujoco_playground_barkour_joystick-privileged++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | privileged |+| Twin | `mujoco_playground_barkour_joystick-standard` |+| Simulator / robot | `mujoco` / `google-barkour-vb` |+| Family / instance | `mujoco_playground/BarkourJoystick` / seed 2 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `BarkourJoystick` (Google Barkour vB), rebuilt in plain MuJoCo from Playground's scene files: Make Google's Barkour quadruped follow the joystick command schedule for the whole 10 s episode, through random pushes, without falling over.+For 10 s the robot gets a joystick command schedule (2 segments: planar velocity and yaw rate in its own frame) and must track it without falling over. Its torso is pushed 12 times. The deliverable is one replayable trajectory of joint position targets+(`/app/output/trajectory.npz`, `(T, 12)`, T = 1000 (the whole schedule)).++## Difficulty+Velocity tracking for 10 s: the agent has to make a 12-joint quadruped walk (a gait, not one motion) and steer it through the schedule's changes of speed, direction and turning rate, and an open-loop trajectory of 1000 steps only works if it is computed against the simulator. Random pushes on the torso come at fixed but unannounced times; the gait has to absorb them without a joint leaving its box.++## Reference solution+A policy trained here on Playground's BarkourJoystick reward, pushes included (PPO on the CPU, `scripts/mujoco-playground/train/`, not in the image), its targets recorded (`scripts/mujoco-playground/oracle.py`): worst segment errors 0.033 m/s and 0.028 rad/s. Replayed by `solution/solve.sh` (`solution/oracle.npy`, 1000 rows); the rows are float32-exact, so the+standard twin's client executes the same targets. Re-verified by `scripts/mujoco-playground/select_instances.py`: two+fresh-process replays succeed and end in the same state.++## Verification+`tests/grade.py` in a separate sandbox without network: two replays, each in a fresh process, from the verifier's own+copy of the instance (`tests/instance.json`; the start state is checked against its hash on every load); pass iff both+succeed and end in the same state (`deterministic`). Oracle: success, worst segment errors 0.033 m/s and 0.028 rad/s. `nop`: no trajectory, reward 0.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `menagerie/google_barkour_vb/scene_mjx.xml`; MuJoCo Menagerie @ 1b86ece (`google_barkour_vb`); simulated in MuJoCo 3.3.7 on the CPU |+| Instance | Playground's `reset` with `jax.random.PRNGKey(2)` and Playground's command process over the 1000 steps (and its pushes); chosen by `scripts/mujoco-playground/select_instances.py` (seed 2; skipped 0: pushes null or weak (peak under 20% of the torso's weight; a 1-step kick is zero in Playground's half-sine); 1: pushes null or weak (peak under 20% of the torso's weight; a 1-step kick is zero in Playground's half-sine)) |+| Actions | 12 joint position targets per control step (0.01 s of simulated time); kp = 35 N m/rad, joint damping 0.5239 N m s/rad, plus the actuators' own damping of 0.5 N m s/rad |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py` from `scripts/mujoco-playground/instances/BarkourJoystick.json`+(`make_instances.py`, `select_instances.py`) and `scripts/mujoco-playground/oracles/BarkourJoystick.npy` (`oracle.py`).diff --git a/tasks/mujoco_playground_barkour_joystick-privileged/environment/Dockerfile b/tasks/mujoco_playground_barkour_joystick-privileged/environment/Dockerfilenew file mode 100644index 0000000000..7bdd7d2938--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-privileged/environment/Dockerfile@@ -0,0 +1,8 @@+# MuJoCo Playground quadruped task (privileged): plain MuJoCo with Playground's and Menagerie's assets+# (images/mujoco/prepare_assets.sh), the task's tooling and its frozen instance.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY instance.json /app/instance.json+COPY rcb_quadruped.py /opt/tools/rcb_quadruped.py+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_barkour_joystick-privileged/environment/instance.json b/tasks/mujoco_playground_barkour_joystick-privileged/environment/instance.jsonnew file mode 100644index 0000000000..4aba72fed1--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-privileged/environment/instance.json@@ -0,0 +1,192 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "BarkourJoystick",+ "seed": 2,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 0.2800000011920929,+ 1.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.5,+ 1.0,+ 0.0,+ 0.5,+ 1.0,+ 0.0,+ 0.5,+ 1.0,+ 0.0,+ 0.5,+ 1.0+ ],+ "qvel0": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 0.4594014286994934,+ "vy": 0.22121715545654297,+ "wz": 0.016074633225798607+ },+ {+ "start_step": 501,+ "vx": 0.0903209000825882,+ "vy": -0.3885873854160309,+ "wz": 0.6428412795066833+ }+ ],+ "kicks": [+ {+ "start_step": 80,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.8203420823732267,+ -0.5718731221936891+ ]+ },+ {+ "start_step": 160,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.788163164239454,+ -0.6154663488250608+ ]+ },+ {+ "start_step": 240,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.9131765428086646,+ -0.4075642301085992+ ]+ },+ {+ "start_step": 320,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.3721731613746436,+ 0.9281633142677013+ ]+ },+ {+ "start_step": 400,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.9775782732872876,+ -0.2105723619011887+ ]+ },+ {+ "start_step": 480,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.8350665582365031,+ 0.5501489283049099+ ]+ },+ {+ "start_step": 581,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.7430595752025673,+ 0.6692252742535807+ ]+ },+ {+ "start_step": 661,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.8082263256570713,+ 0.5888719780350138+ ]+ },+ {+ "start_step": 741,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.22144795284761612,+ -0.9751721920664063+ ]+ },+ {+ "start_step": 821,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.9990854215709072,+ -0.042758863461072875+ ]+ },+ {+ "start_step": 901,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.821963866092448,+ -0.5695396411474414+ ]+ },+ {+ "start_step": 981,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.4999078076804545,+ -0.8660786245024881+ ]+ }+ ],+ "text": "Make Google's Barkour quadruped follow the joystick command schedule for the whole 10 s episode, through random pushes, without falling over.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": 0.0,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.22,+ "reference_rows": 1000,+ "torso_mass_kg": 14.496,+ "reference_worst_lin_err": 0.0329,+ "reference_worst_yaw_err": 0.0276+ },+ "state_sha": "90c7b858534f",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s), when its pushes (Barkour) are null or\n weak (peak under 20% of the torso's weight), or when the reference trajectory (oracle.py) fails the task's\n success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 3+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_barkour_joystick-privileged/environment/rcb_quadruped.py b/tasks/mujoco_playground_barkour_joystick-privileged/environment/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-privileged/environment/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_barkour_joystick-privileged/instruction.md b/tasks/mujoco_playground_barkour_joystick-privileged/instruction.mdnew file mode 100644index 0000000000..bd23517d15--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-privileged/instruction.md@@ -0,0 +1,62 @@+# MuJoCo Playground · BarkourJoystick — frozen episode++**Task:** Make Google's Barkour quadruped follow the joystick command schedule for the whole 10 s episode, through random pushes, without falling over.++You control the Google Barkour vB quadruped in one episode of MuJoCo Playground's `BarkourJoystick` environment, rebuilt in plain+MuJoCo 3.3.7 from Playground's own scene files (Apache-2.0, commit 4057c14) and the robot from MuJoCo Menagerie. The+episode is frozen: it starts the same way after every reset (Playground's `reset` with seed 2), and you may reset+as often as you like. Your deliverable is **one open-loop trajectory**, not a general policy.++## The episode+The robot starts standing still at Playground's `home` pose (this environment's reset does not move it). The ground is flat. One control step is 10 ms of simulated time: Playground's Barkour environment keeps Menagerie's 2 ms timestep and takes 5 substeps.+For 10 s (1000 control steps) it is given this command schedule, drawn by Playground's command process (a new draw after 501 control steps). A command is a velocity in the robot's own frame: vx forward, vy to the left (the trunk's planar velocity), and the yaw rate:++| from (s) | vx (m/s) | vy (m/s) | yaw rate (rad/s) |+|---:|---:|---:|---:|+| 0.00 | +0.459 | +0.221 | +0.016 |+| 5.01 | +0.090 | -0.389 | +0.643 |++The torso is pushed 12 times (Playground's kicks): each push lasts 5 control steps, a half-sine of horizontal force up to 35 N in a random direction; `instance.json` (`kicks`) lists when and where, and `s.push_force(t)` gives the force of control step t.++`s.commands` holds the schedule per control step; `s.state()["command"]` is the current one.++## Success+The episode lasts exactly 1000 control steps: the trajectory must have T = 1000 rows. Success iff+1. the robot never meets Playground's termination rule for this environment: the trunk's up axis pointing below the horizon, a joint outside its box (abduction [-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m; and+2. in every command segment, over its control steps after the first 25 (0.25 s): the mean planar velocity error |v_xy - cmd_xy| is at most 0.2 m/s, with v the IMU's velocimeter (`local_linvel`, trunk frame), and the mean yaw-rate error |w_z - cmd_wz| at most 0.3 rad/s, with w the IMU's gyro.++`s.check()` reports `fell_at`, each segment's errors and `success`.++## Deliverable+`/app/output/trajectory.npz` with `actions`: float64 (T, 12), one row per control step (0.01 s): absolute targets of+the 12 joint position actuators, in `s.joint_names` order (front-left, hind-left, front-right, hind-right legs, each abduction, hip, knee), in radians; T = 1000 (the whole schedule). Values+outside the actuator ranges (`s.lower`, `s.upper`) are clipped. `s.save_trajectory(rows)` writes it. Also leave the+script that produced it at `/app/output/gen.py`. Save a working trajectory as soon as you have one and overwrite it as+you improve it: whatever is in `/app/output/` when your 3600 s are up is graded. The tooling logs your sessions and+resets (cost accounting, not graded).++## Tooling (installed; `python` from any directory)+```python+from rcb_quadruped import Session+s = Session("/app/instance.json") # the frozen episode at t = 0 (checked against the instance's state hash)+s.joint_names; s.lower; s.upper # the actuator order and ranges (rad)+s.home # Playground's standing pose (its `home` keyframe), in that order+s.step(row) # one control step: 12 joint targets, 5 physics steps of 0.002 s; returns s.check()+s.check() # the task's check on the steps so far (see Success)+s.state() # qpos, qvel, IMU (local_linvel, gyro, gravity, accelerometer, pose), feet, contacts, command+s.sensor(name); s.gravity() # one MuJoCo sensor; gravity's direction in the IMU frame+s.model, s.data # the live MuJoCo model and data (read them; changing them is not part of the replay)+s.render(cam); s.cameras # uint8 (240, 320, 3) from cameras that follow the robot: `track` (follows the robot) and `realsense/rgb` (on its head)+s.reset() # back to t = 0+s.replay(rows) # reset, run the rows, return the check and the final state's hash+s.render_video(rows, "/app/output/try.mp4")+s.save_trajectory(rows, "/app/output/trajectory.npz")+```+The grader runs exactly this CLI in two fresh processes, so run it to check yourself:+`python /opt/tools/rcb_quadruped.py replay --instance /app/instance.json --traj /app/output/trajectory.npz`++## Conventions+- Joint position actuators (PD): kp = 35 N m/rad, joint damping 0.5239 N m s/rad, plus the actuators' own damping of 0.5 N m s/rad, as Playground's environment sets them; the physics step is 0.002 s,+ the control step 0.01 s (5 physics steps); a row holds until the next one.+- World frame z up, metres; quaternions **wxyz**. The IMU frame is the trunk's: x forward, y left, z up.+- Physics is MuJoCo on the CPU: the same rows from the same start give the same result in every fresh process.diff --git a/tasks/mujoco_playground_barkour_joystick-privileged/solution/oracle.npy b/tasks/mujoco_playground_barkour_joystick-privileged/solution/oracle.npynew file mode 100644index 0000000000..56910d0997Binary files /dev/null and b/tasks/mujoco_playground_barkour_joystick-privileged/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_barkour_joystick-privileged/solution/oracle_replay.py b/tasks/mujoco_playground_barkour_joystick-privileged/solution/oracle_replay.pynew file mode 100644index 0000000000..46987df1d0--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-privileged/solution/oracle_replay.py@@ -0,0 +1,15 @@+"""Oracle (privileged): replay the reference rows in the tooling, check them, and save them as the deliverable."""+import json+import os+import sys++import numpy as np++sys.path.insert(0, "/opt/tools")+from rcb_quadruped import Session # noqa: E402++rows = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy"))+s = Session("/app/instance.json")+r = s.replay(rows)+s.save_trajectory(rows, "/app/output/trajectory.npz", meta={"source": "reference trajectory (solution/oracle.npy)"})+print(json.dumps({k: v for k, v in r.items() if k != "segments"}))diff --git a/tasks/mujoco_playground_barkour_joystick-privileged/solution/solve.sh b/tasks/mujoco_playground_barkour_joystick-privileged/solution/solve.shnew file mode 100755index 0000000000..430ffb6017--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-privileged/solution/solve.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Oracle (privileged): write the reference trajectory frozen at generation time (solution/oracle.npy; how it was made:+# scripts/mujoco-playground/oracle.py) as the deliverable.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_barkour_joystick-privileged/task.toml b/tasks/mujoco_playground_barkour_joystick-privileged/task.tomlnew file mode 100644index 0000000000..987b8add49--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-privileged/task.toml@@ -0,0 +1,43 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = ["/app/output/", "/logs/agent/rcb/"]++[task]+name = "robot-coding-bench/mujoco_playground_barkour_joystick-privileged"+description = "MuJoCo Playground BarkourJoystick in plain MuJoCo (Google Barkour vB, joint position control every 0.01 s): Make Google's Barkour quadruped follow the joystick command schedule for the whole 10 s episode, through random pushes, without falling over. Produce one replayable trajectory of joint position targets on a frozen instance (Playground's reset with seed 2); graded by velocity tracking over the whole 10 s schedule without a fall (two fresh-process replays)."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "google-barkour-vb", "quadruped", "locomotion", "joystick", "code-as-policy", "trajectory", "privileged"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "google-barkour-vb"+family = "mujoco_playground/BarkourJoystick"+mode = "privileged"+oracle = "full"+instance_seed = 2 # the PRNGKey of Playground's reset (and, for the joystick tasks, its command process)+expert_time_estimate_hours = 3.0++[verifier]+timeout_sec = 1200.0+environment_mode = "separate"+network_mode = "no-network"++[verifier.environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192++[agent]+timeout_sec = 3600.0+# MuJoCo Playground's trained policies are public upstream, so the agent reaches the model APIs and nothing else+# (scripts/set_agent_egress.py HOSTS).+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_barkour_joystick-privileged/tests/Dockerfile b/tasks/mujoco_playground_barkour_joystick-privileged/tests/Dockerfilenew file mode 100644index 0000000000..f49c79154d--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-privileged/tests/Dockerfile@@ -0,0 +1,7 @@+# Separate verifier sandbox (PROTOCOL §4): the same image with the verifier's own copies of the tooling and the frozen+# instance. Nothing the agent did in its container reaches this one: Harbor uploads only the declared artifacts.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY grade.py instance.json rcb_quadruped.py test.sh /tests/+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier+ENV PYTHONPATH=/tests+WORKDIR /testsdiff --git a/tasks/mujoco_playground_barkour_joystick-privileged/tests/grade.py b/tasks/mujoco_playground_barkour_joystick-privileged/tests/grade.pynew file mode 100644index 0000000000..e5668de85f--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-privileged/tests/grade.py@@ -0,0 +1,126 @@+"""Verifier (privileged): replay /app/output/trajectory.npz from the frozen instance and write Harbor's rewards.++ python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz++Two replays, each in its own fresh process (`rcb_quadruped.py replay`: the frozen start, one control step per row, the+task's success check on the whole trajectory). success = both replays succeed and end in the same state. Writes+/logs/verifier/reward.txt (1/0) and reward.json (numbers only); then a third replay renders replay.mp4, after the+verdict is on disk (it never changes it).+"""+import argparse+import json+import os+import subprocess+import sys+import tempfile+import traceback++import numpy as np++LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")+TOOL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_quadruped.py")+REPLAY_TIMEOUT_S = 300 # a 1000-step replay takes a few seconds; the video replay renders 4 views every 2nd step+++def write(ok: bool, out: dict) -> None:+ os.makedirs(LOG_DIR, exist_ok=True)+ open(os.path.join(LOG_DIR, "reward.txt"), "w").write("1\n" if ok else "0\n")+ json.dump(out, open(os.path.join(LOG_DIR, "reward.json"), "w"))+ print(json.dumps(out), flush=True)+++def agent_cost() -> dict:+ """Self-reported cost from the tooling's log in the agent's container (accounting, not evidence)."""+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_replays": 0, "agent_cost_self_reported": 1}+ for path in ("/logs/agent/rcb/rcb_session_log.jsonl", "/app/output/rcb_session_log.jsonl"):+ if not os.path.exists(path):+ continue+ try:+ with open(path) as f:+ for i, line in enumerate(f):+ if i > 200_000 or len(line) > 10_000:+ break+ try:+ e = json.loads(line)+ ev = e.get("ev") if isinstance(e, dict) else None+ if ev == "session_start":+ cost["agent_sessions"] += 1+ elif ev == "reset":+ cost["agent_resets"] += 1+ elif ev == "replay":+ cost["agent_replays"] += 1+ elif ev == "session_end":+ cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)+ except Exception: # noqa: BLE001 -- one bad line must not sink the verdict+ continue+ except OSError:+ pass+ break+ return cost+++def replay(instance: str, traj: str, video: str | None) -> dict:+ """One replay in a fresh process; its result (`--out`), or {"error": ...}."""+ with tempfile.NamedTemporaryFile(suffix=".json") as out:+ cmd = [sys.executable, TOOL, "replay", "--instance", instance, "--traj", traj, "--out", out.name]+ try:+ p = subprocess.run(cmd + (["--video", video] if video else []), stdout=subprocess.DEVNULL, stderr=sys.stderr,+ timeout=REPLAY_TIMEOUT_S, env={**os.environ, "RCB_SESSION_LOG": "", "RCB_AGENT_TRACE_DIR": ""})+ except subprocess.TimeoutExpired:+ return {"error": f"replay took over {REPLAY_TIMEOUT_S} s"}+ try:+ return json.load(open(out.name))+ except ValueError:+ return {"error": f"replay process rc={p.returncode}"}+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--instance", required=True)+ ap.add_argument("--traj", default="/app/output/trajectory.npz")+ a = ap.parse_args()+ cost = agent_cost()+ if not os.path.isfile(a.traj):+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost})+ return 0+ try:+ horizon = int(json.load(open(a.instance))["horizon"])+ d = np.load(a.traj, allow_pickle=False)+ acts = np.asarray(d["actions"], dtype=np.float64) if "actions" in d.files else np.zeros((0, 0))+ if acts.ndim != 2 or acts.shape[1] != 12 or len(acts) > horizon or not np.all(np.isfinite(acts)):+ write(False, {"success": 0, "bad_trajectory": 1, "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0,+ "grader_error": 0, **cost})+ return 0+ runs = [replay(a.instance, a.traj, None), replay(a.instance, a.traj, None)]+ if any("error" in r and not r.get("bad_trajectory") for r in runs):+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ if not all(r.get("instance_ok") for r in runs): # the image no longer builds the frozen start: not the agent's 0+ write(False, {"success": 0, "grader_error": 1, "instance_mismatch": 1, **cost})+ return 0+ all_success = all(bool(r.get("success")) for r in runs)+ deterministic = runs[0].get("state_sha") == runs[1].get("state_sha")+ ok = all_success and deterministic+ r = runs[0]+ num = lambda k: float(r.get(k) if r.get(k) is not None else -1) # noqa: E731+ out = {"success": int(ok), "replay_success": int(all_success), "deterministic": int(deterministic),+ "n_actions": int(len(acts)), "horizon": horizon, "fell": int(r.get("fell_at") is not None),+ "fell_at_step": num("fell_at"), "worst_lin_err": num("worst_lin_err"), "worst_yaw_err": num("worst_yaw_err"),+ "end_tilt_deg": num("tilt_deg"), "end_imu_height": num("imu_height"), "end_pose_angle_deg": num("pose_angle_deg"),+ "grader_error": 0,+ "video_rendered": 0, **cost}+ write(ok, out) # the verdict, before any video+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ try: # the video, for humans: it never changes the verdict+ if replay(a.instance, a.traj, os.path.join(LOG_DIR, "replay.mp4")).get("video"):+ write(ok, {**out, "video_rendered": 1})+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/mujoco_playground_barkour_joystick-privileged/tests/instance.json b/tasks/mujoco_playground_barkour_joystick-privileged/tests/instance.jsonnew file mode 100644index 0000000000..4aba72fed1--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-privileged/tests/instance.json@@ -0,0 +1,192 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "BarkourJoystick",+ "seed": 2,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 0.2800000011920929,+ 1.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.5,+ 1.0,+ 0.0,+ 0.5,+ 1.0,+ 0.0,+ 0.5,+ 1.0,+ 0.0,+ 0.5,+ 1.0+ ],+ "qvel0": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 0.4594014286994934,+ "vy": 0.22121715545654297,+ "wz": 0.016074633225798607+ },+ {+ "start_step": 501,+ "vx": 0.0903209000825882,+ "vy": -0.3885873854160309,+ "wz": 0.6428412795066833+ }+ ],+ "kicks": [+ {+ "start_step": 80,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.8203420823732267,+ -0.5718731221936891+ ]+ },+ {+ "start_step": 160,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.788163164239454,+ -0.6154663488250608+ ]+ },+ {+ "start_step": 240,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.9131765428086646,+ -0.4075642301085992+ ]+ },+ {+ "start_step": 320,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.3721731613746436,+ 0.9281633142677013+ ]+ },+ {+ "start_step": 400,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.9775782732872876,+ -0.2105723619011887+ ]+ },+ {+ "start_step": 480,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.8350665582365031,+ 0.5501489283049099+ ]+ },+ {+ "start_step": 581,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.7430595752025673,+ 0.6692252742535807+ ]+ },+ {+ "start_step": 661,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.8082263256570713,+ 0.5888719780350138+ ]+ },+ {+ "start_step": 741,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.22144795284761612,+ -0.9751721920664063+ ]+ },+ {+ "start_step": 821,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.9990854215709072,+ -0.042758863461072875+ ]+ },+ {+ "start_step": 901,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.821963866092448,+ -0.5695396411474414+ ]+ },+ {+ "start_step": 981,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.4999078076804545,+ -0.8660786245024881+ ]+ }+ ],+ "text": "Make Google's Barkour quadruped follow the joystick command schedule for the whole 10 s episode, through random pushes, without falling over.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": 0.0,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.22,+ "reference_rows": 1000,+ "torso_mass_kg": 14.496,+ "reference_worst_lin_err": 0.0329,+ "reference_worst_yaw_err": 0.0276+ },+ "state_sha": "90c7b858534f",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s), when its pushes (Barkour) are null or\n weak (peak under 20% of the torso's weight), or when the reference trajectory (oracle.py) fails the task's\n success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 3+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_barkour_joystick-privileged/tests/rcb_quadruped.py b/tasks/mujoco_playground_barkour_joystick-privileged/tests/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-privileged/tests/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_barkour_joystick-privileged/tests/test.sh b/tasks/mujoco_playground_barkour_joystick-privileged/tests/test.shnew file mode 100755index 0000000000..1c3d2f767b--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-privileged/tests/test.sh@@ -0,0 +1,9 @@+#!/bin/bash+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in two fresh processes (the+# verdict), then a third that renders replay.mp4.+# Writes /logs/verifier/reward.txt (1/0) and reward.json (numeric fields, docs/PROTOCOL.md §2.6).+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/*+mkdir -p /logs/verifier+python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz 2> /logs/verifier/grade.logdiff --git a/tasks/mujoco_playground_barkour_joystick-standard/README.md b/tasks/mujoco_playground_barkour_joystick-standard/README.mdnew file mode 100644index 0000000000..5199231e05--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/README.md@@ -0,0 +1,44 @@+# mujoco_playground_barkour_joystick-standard++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | standard (`eai-standard/2.2`) |+| Twin | `mujoco_playground_barkour_joystick-privileged` |+| Simulator / robot | `mujoco` / `google-barkour-vb` |+| Family / instance | `mujoco_playground/BarkourJoystick` / seed 2 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `BarkourJoystick` (Google Barkour vB) on the same frozen instance as `mujoco_playground_barkour_joystick-privileged`: Make Google's Barkour quadruped follow the joystick command schedule for the whole 10 s episode, through random pushes, without falling over.+For 10 s the robot gets a joystick command schedule (2 segments: planar velocity and yaw rate in its own frame) and must track it without falling over. Its torso is pushed 12 times. Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with only+the robot's own sensors and four cameras that follow it.++## Difficulty+Same instance and success check as `mujoco_playground_barkour_joystick-privileged`. In standard mode the agent loses resets, the simulator and+the world state: it sees camera images and proprioception (joints, IMU, foot contacts), acts in joint position chunks,+and gets one episode, so it has to close the loop on the robot's own sensors and recover from its own mistakes without+starting over.++## Reference solution+`solution/oracle_replay.py` streams the privileged reference's rows (`solution/oracle.npy`, 1000 rows, float32-exact)+through the client in `hold` chunks; it uses no privileged information at run time. The service's recorded trajectory+is then exactly the privileged reference, and the episode ends after the 1000 steps of the schedule, with success.++## Verification+The sim service judges the episode live and records every executed control step; the collect hook+(`environment/sim/finalize.sh`) ends the service, replays the recorded trajectory in two fresh processes and writes+`final.json`; `tests/grade.py` (separate sandbox, no network) passes iff the live check succeeded, both replays succeed,+and they end in the same state. Oracle: success, worst segment errors 0.033 m/s and 0.028 rad/s.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `menagerie/google_barkour_vb/scene_mjx.xml`; MuJoCo Menagerie @ 1b86ece (`google_barkour_vb`); MuJoCo 3.3.7 on the CPU |+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); cameras `track` (follows the robot) and `realsense/rgb` (on its head) (320 x 240), the feet's kinematics in the trunk frame |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py`, as its privileged twin.diff --git a/tasks/mujoco_playground_barkour_joystick-standard/environment/Dockerfile b/tasks/mujoco_playground_barkour_joystick-standard/environment/Dockerfilenew file mode 100644index 0000000000..ed5eee3703--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/environment/Dockerfile@@ -0,0 +1,9 @@+# Standard mode: the agent container has NO simulator and no Playground code, only Python and the client, on the shared+# pinned client base with the shared pins (scripts/eai_standard/client.env, client-requirements.txt).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY client-requirements.txt /tmp/client-requirements.txt+RUN pip install --no-cache-dir -r /tmp/client-requirements.txt+COPY rcb_client.py rcb1.py /opt/tools/+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_barkour_joystick-standard/environment/client-requirements.txt b/tasks/mujoco_playground_barkour_joystick-standard/environment/client-requirements.txtnew file mode 100644index 0000000000..8aa73a968f--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/environment/client-requirements.txt@@ -0,0 +1,11 @@+# Exact pins for what the standard agent container installs (and a verifier, if it installs anything): the closure of+# `pip install requests numpy pillow scipy`, the unpinned line of every standard task at 9eb18edf, resolved on+# 2026-10-01 in CLIENT_IMAGE (client.env: Python 3.12.14, pip 25.0.1). A change here is a shared-files PR.+certifi==2026.7.22+charset-normalizer==3.5.2+idna==3.20+numpy==2.5.3+pillow==12.3.0+requests==2.34.2+scipy==1.18.1+urllib3==2.8.0diff --git a/tasks/mujoco_playground_barkour_joystick-standard/environment/docker-compose.yaml b/tasks/mujoco_playground_barkour_joystick-standard/environment/docker-compose.yamlnew file mode 100644index 0000000000..8ec63c582e--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/environment/docker-compose.yaml@@ -0,0 +1,23 @@+# Standard mode: the simulator runs in the `sim` sidecar (the agent cannot open it); the agent only reaches port 8000.+# No `expose`/`ports` on sim: under Harbor's egress control it shares main's network namespace (localhost:8000).+# CPU only: MuJoCo physics and rendering (EGL when a GPU is there, else OSMesa); no GPU reservation.+# Crash recovery (docs/STANDARD_MODE_2_2.md §13): run.sh exits non-zero when the service crashes, compose restarts the+# container (same container, same /data) and the service replays its journal into the same episode, never a reset.+services:+ main:+ depends_on: [sim]+ sim:+ image: ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+ volumes:+ - ./sim:/srv:ro+ working_dir: /tmp+ command: sh /srv/run.sh+ restart: on-failure:6 # N >= 3 (PROTOCOL §4.1); a resume continues the episode+ environment:+ RCB_INSTANCE: /srv/instance.json+ RCB_TOOL: /srv/rcb_quadruped.py+ RCB_DATA: /data+ RCB_WALL_CLOCK_S: "3600"+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in about a second+ PYTHONPATH: /srv+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction logdiff --git a/tasks/mujoco_playground_barkour_joystick-standard/environment/rcb1.py b/tasks/mujoco_playground_barkour_joystick-standard/environment/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/environment/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_barkour_joystick-standard/environment/rcb_client.py b/tasks/mujoco_playground_barkour_joystick-standard/environment/rcb_client.pynew file mode 100644index 0000000000..aa25b0e050--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/environment/rcb_client.py@@ -0,0 +1,211 @@+"""eai-standard/2.2 client (formerly rcb-limited/2.x) — the only thing a standard-mode agent gets (installed at+/opt/tools/rcb_client.py).++ from rcb_client import Robot+ r = Robot() # finds the service (sim:8000, then localhost:8000), waits for warm-up+ spec = r.spec() # actions, cameras (+ intrinsics, mounting), robot_spec, world, budget, kinematics+ obs = r.get_obs() # current frames: obs.last[cam] -> uint8 (H,W,3); obs.meta["proprio"]+ obs = r.get_obs(depth=True) # + obs.last_depth[cam] -> float32 (H,W) z-depth in metres, 0 = no reading+ res = r.submit("joint_position", A, dt=0.1) # A: (T, dim) rows dt apart; returns the execution video+ res = r.submit("ee_pose", P) # (T, dim) end-effector targets (see spec()["action_types"])+ res.video[cam] -> mp4 bytes res.frames[cam] -> uint8 (N,H,W,3) if video="frames"/"both" res.last[cam]+ res.proprio -> float32 (N, D), one row per frame (names: spec()["proprio_layout"]; res.group("tcp_pose"))+ res.frame_step -> int64 (N,) control step of each frame res.frame_time_s -> float64 (N,) simulated time+ res.extrinsic_cv[cam] -> float64 (N,3,4) world->camera per frame (res.meta["cameras"]: intrinsics + the last frame's pose)+ res = r.submit(..., depth="frames") # + res.depth[cam] -> float32 (N,H,W) metres, one per frame (1 mm steps)+ r.fk(q) # {"ok", "poses": {frame: [x,y,z, quaternion]}}: forward kinematics, no physics+ r.ik({frame: pose}, seed=q) # {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}: inverse kinematics+ res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, frames/<cam>/NNN.jpg, proprio.npy, depth, frame_meta.npz+ obs = r.get_obs(seconds=3, video="both") # hold the last command, let physics run 3 s, return the video+ r.status() # calls, control steps, done, reason, elapsed time++Nothing is put into your context automatically: what you look at, and where you store it, is your code's decision.++If a call fails with a connection error or a 5xx, the service may have crashed; it restarts and resumes the SAME episode+(never a reset) in the state after the last call it completed, which you may not have received. r.wait_ready() waits+until it answers again (resuming replays the episode so far: long episodes can take minutes); then check r.status()+before you continue (spec()["on_service_error"]).+"""+from __future__ import annotations+import json, os, pathlib, sys, time, zlib+import numpy as np+import requests+import rcb1++PROTOCOL = "eai-standard/2.2" # also talks to 2.0 / 2.1 services (they ignore depth and send no frame metadata)+ACCEPTED = ("eai-standard/2.", "rcb-limited/2.") # every 2.x service, under the protocol's current and former name+++class EpisodeOver(RuntimeError):+ pass+++def _decode_depth_frames(p: dict) -> np.ndarray:+ a = np.frombuffer(zlib.decompress(p["data"]), dtype="<u2").reshape(p["shape"])+ return a.astype(np.float32) / 1000.0+++class Result:+ """Decoded RCB1 response: meta (dict), video (cam -> mp4 bytes), frames (cam -> uint8 (N,H,W,3)), last (cam -> uint8+ (H,W,3)), last_depth (cam -> float32 (H,W) m), depth (cam -> float32 (N,H,W) m, one per frame), proprio (float32 (N,D)),+ frame_step (int64 (N,)), frame_time_s (float64 (N,)), extrinsic_cv (cam -> float64 (N,3,4)). save(dir) writes it out;+ show(cam, k) returns one frame; group(name) the proprio columns of one spec()["proprio_groups"] group. stopped: None,+ or why the service stopped the call early ("max_call_wall_s": it ran longer than spec()["max_call_wall_s"]); then+ meta["executed_rows"] < the rows sent, and meta["proprio"]["now"] is where the robot is."""+ def __init__(self, meta: dict, parts: dict, spec: dict | None = None):+ self.meta = meta; self.raw = parts; self._spec = spec or {}; self.stopped = meta.get("stopped")+ self.video, self.frames, self.last, self.last_depth, self.depth, self.extrinsic_cv = {}, {}, {}, {}, {}, {}+ self.proprio = None; self.frame_step = None; self.frame_time_s = None+ for name, p in parts.items():+ kind, data = p["kind"], p["data"]+ if name.startswith("video/") and kind == "mp4": self.video[name[6:]] = data+ elif name.startswith("frames/") and kind == "array": self.frames[name[7:]] = data+ elif name.startswith("last/") and kind == "array": self.last[name[5:]] = data+ elif name.startswith("last_depth/") and kind == "array": self.last_depth[name[11:]] = np.asarray(data, dtype=np.float32)+ elif name.startswith("depth_frames/") and p.get("codec") == "zlib": self.depth[name[13:]] = _decode_depth_frames(p)+ elif name.startswith("depth/") and kind == "array": self.depth[name[6:]] = np.asarray(data, dtype=np.float32) # 2.1 form+ elif name.startswith("extrinsic_cv/") and kind == "array": self.extrinsic_cv[name[13:]] = data+ elif name == "proprio": self.proprio = data+ elif name == "frame_step": self.frame_step = data+ elif name == "frame_time_s": self.frame_time_s = data++ @property+ def done(self) -> bool: return bool(self.meta.get("done"))++ def show(self, camera: str, k: int = -1) -> np.ndarray:+ if camera in self.frames: return self.frames[camera][k]+ return self.last[camera]++ def group(self, name: str, now: bool = False) -> np.ndarray:+ """Columns of proprio group `name` (spec()["proprio_groups"]): (N, n) over the frames, or (n,) of meta["proprio"]["now"]."""+ first, n = self._spec["proprio_groups"][name][:2]+ if now: return np.asarray(self.meta["proprio"]["now"], dtype=np.float64)[first:first + n]+ return self.proprio[:, first:first + n]++ def save(self, out_dir: str) -> str:+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ (out / "meta.json").write_text(json.dumps(self.meta, indent=1))+ for cam, b in self.video.items(): (out / f"{cam}.mp4").write_bytes(b)+ try:+ from PIL import Image+ for cam, img in self.last.items():+ (out / "last").mkdir(exist_ok=True); Image.fromarray(np.ascontiguousarray(img)).save(out / "last" / f"{cam}.jpg", quality=90)+ for cam, arr in self.frames.items():+ d = out / "frames" / cam; d.mkdir(parents=True, exist_ok=True)+ for i, f in enumerate(arr): Image.fromarray(np.ascontiguousarray(f)).save(d / f"{i:03d}.jpg", quality=85)+ except ImportError:+ for cam, img in self.last.items(): np.save(out / f"last_{cam}.npy", img)+ for cam, arr in self.frames.items(): np.save(out / f"frames_{cam}.npy", arr)+ for cam, arr in self.last_depth.items(): np.save(out / f"last_depth_{cam}.npy", arr)+ for cam, arr in self.depth.items(): np.savez_compressed(out / f"depth_{cam}.npz", depth_mm=np.rint(arr * 1000).astype(np.uint16))+ if self.proprio is not None: np.save(out / "proprio.npy", self.proprio)+ if self.frame_step is not None:+ np.savez(out / "frame_meta.npz", frame_step=self.frame_step, frame_time_s=self.frame_time_s,+ **{f"extrinsic_cv/{c}": e for c, e in self.extrinsic_cv.items()})+ return str(out)+++class Robot:+ def __init__(self, base: str | None = None, timeout: float = 600.0):+ cands = [base or os.environ.get("SIM_URL"), "http://sim:8000", "http://localhost:8000"]+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ for b in [c for c in cands if c]:+ try:+ r = requests.get(b + "/spec", timeout=(5, 30))+ if r.status_code == 503: last = "warming up"; break+ r.raise_for_status(); self.base = b; self._spec = r.json()+ if not str(self._spec.get("protocol", "")).startswith(ACCEPTED):+ raise RuntimeError(f"not a 2.x service: protocol {self._spec.get('protocol')!r}")+ return+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(2)+ raise RuntimeError(f"sim service unavailable: {last}")++ def spec(self) -> dict:+ return self._spec++ def _post(self, path: str, meta: dict, parts: list, timeout: float) -> Result:+ body = rcb1.encode(meta, parts)+ r = requests.post(self.base + path, data=body, headers={"Content-Type": "application/x-rcb1"}, timeout=(5, timeout))+ if r.status_code == 409:+ raise EpisodeOver(r.json().get("reason") if r.headers.get("Content-Type", "").startswith("application/json") else "episode finished")+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ m, p = rcb1.decode(r.content); return Result(m, p, self._spec)++ def _common(self, cameras, video_fps, depth, include_depth) -> dict:+ cams = list(cameras) if cameras is not None else self._spec.get("default_cameras")+ if depth is None or depth is False: depth = "frames" if include_depth else "none"+ elif depth is True: depth = "last"+ m = {"cameras": cams, "video_fps": None if video_fps is None else int(video_fps), "depth": depth}+ return {k: v for k, v in m.items() if v is not None}++ def submit(self, action_type: str, actions, dt: float | None = None, interpolate: str = "linear", cameras=None,+ video_fps: int | None = None, video: str = "mp4", depth=None, include_depth: bool = False, note: str = "") -> Result:+ """Execute a chunk of low-level actions (T, dim); see spec()['action_types'] for dims, layouts, limits and semantics.+ dt defaults to one control period, cameras to spec()['default_cameras']; depth: None | True (= "last") | "frames"."""+ a = np.asarray(actions, dtype=np.float32)+ if a.ndim == 1: a = a[None, :]+ if dt is None and self._spec.get("control_hz"): dt = 1.0 / float(self._spec["control_hz"])+ meta = {"type": action_type, "interpolate": interpolate, "video": video, "note": note,+ **({} if dt is None else {"dt": float(dt)}), **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/submit", meta, [rcb1.array_part("actions", a)], timeout=1800)+ if res.stopped:+ print(f"[rcb_client] the service stopped this call early ({res.stopped}): {res.meta.get('executed_rows')} of {len(a)} rows "+ "executed; meta['proprio']['now'] is where the robot is", file=sys.stderr)+ return res++ def get_obs(self, cameras=None, seconds: float = 0.0, video_fps: int | None = None, depth=None, include_depth: bool = False,+ video: str = "frames") -> Result:+ """Current frames (seconds=0, free) or hold the last command and watch for `seconds` (returns the video).+ depth: None | True (= "last": the last frame's depth) | "frames" (one depth map per frame)."""+ meta = {"seconds": float(seconds), "video": video, **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/observe", meta, [], timeout=600)+ if res.stopped:+ print(f"[rcb_client] the service stopped this watch early ({res.stopped}) after {res.meta.get('control_steps_watch')} control "+ "steps", file=sys.stderr)+ return res++ def status(self) -> dict:+ r = requests.get(self.base + "/status", timeout=(5, 60)); r.raise_for_status(); return r.json()++ def wait_ready(self, timeout: float = 3600.0) -> dict:+ """After a connection error: wait until the service answers GET /status again (it resumes the same episode after a+ crash), then return the status. Raises RuntimeError after `timeout` seconds."""+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ try:+ return self.status()+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(5)+ raise RuntimeError(f"sim service did not come back within {timeout:.0f} s: {last}")++ def kinematics(self, body: dict) -> dict:+ """POST /kinematics (stateless: never moves the robot, never advances time). Raises ValueError on a bad request."""+ r = requests.post(self.base + "/kinematics", json=body, timeout=(5, 120))+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ return r.json()++ def fk(self, q, links=None, base_pose=None) -> dict:+ """Forward kinematics: q in spec()['kinematics']['joint_names'] order -> {"ok", "frame", "poses": {link: [x,y,z, quat]}}+ (quaternion order spec()['world']['quaternion_order']; a mobile robot answers in its base frame unless base_pose is given)."""+ body = {"op": "fk", "q": [float(v) for v in np.asarray(q).reshape(-1)]}+ if links is not None: body["links"] = list(links)+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)++ def ik(self, targets: dict, seed=None, base_pose=None, **opts) -> dict:+ """Inverse kinematics: {frame: [x,y,z, quat]} (frames from spec()['kinematics']['ik_targets']) and an optional seed q ->+ {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}. opts: tol_pos_m, tol_rot_rad, max_iters."""+ body = {"op": "ik", "targets": {k: [float(v) for v in p] for k, p in targets.items()}, **opts}+ if seed is not None: body["seed"] = [float(v) for v in np.asarray(seed).reshape(-1)]+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)diff --git a/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/finalize.sh b/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/finalize.shnew file mode 100755index 0000000000..02048ddc74--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/finalize.sh@@ -0,0 +1,80 @@+#!/bin/sh+# [[verifier.collect]] hook, run inside the `sim` sidecar once Harbor has stopped the agent's container.+# 1. `rcb_limited.py end` (docs/STANDARD_MODE_2_2.md §13.3): SIGUSR1 to the service, which ends the episode if the+# agent had not (reason "timeout"), writes trajectory.npz + episode.json (live verdict, final-state hash) and exits.+# It exits 2 when final.json already holds the verdict (the service gave up after crashes): that verdict stays.+# 2. replay the trajectory from the frozen instance in TWO fresh processes (`rcb_quadruped.py replay`, the privileged+# verifier's replay): determinism = fresh process == fresh process; live_matches_replay = live == replay.+# 3. merge everything into final.json, the only thing the verifier sandbox grades;+# 4. a third replay renders replay.mp4, after the verdict is on disk (it never changes it).+set -u+DATA="${RCB_DATA:-/data}"; TOOL="${RCB_TOOL:?}"; INSTANCE="${RCB_INSTANCE:?}"+python /srv/rcb_limited.py end "$DATA" --timeout "${RCB_COLLECT_END_TIMEOUT_S:-900}"; rc=$?+if [ "$rc" = 2 ]; then+ echo "[finalize] final.json already holds the verdict; no replay"; exit 0+fi+if [ "$rc" != 0 ]; then+ echo "[finalize] the service did not end and dump the episode in time (rc $rc): an infrastructure failure"+ python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data"); p = os.path.join(d, "final.json")+try:+ out = json.load(open(p))+except Exception:+ out = {}+out.update({"finalized": True, "success": False, "replay_success": False, "deterministic": False, "infra_error": 1,+ "error": "collect hook: the sim service did not end and dump the episode in time"})+json.dump(out, open(p, "w"))+print(json.dumps(out))+PY+ exit 0+fi+replay() { # <n> [--video FILE]: one replay in a fresh process, its result in $DATA/replay<n>.json+ n=$1; shift+ RCB_SESSION_LOG= python "$TOOL" replay --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --out "$DATA/replay$n.json" \+ "$@" > /dev/null 2> "$DATA/replay$n.log"+ echo "[finalize] replay $n exit $?"+}+echo "[finalize] episode dumped; replaying twice in fresh processes"+rm -f "$DATA/replay1.json" "$DATA/replay2.json" "$DATA/replay3.json"+replay 1+replay 2+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+def result(name):+ try:+ v = json.load(open(os.path.join(d, name)))+ except (OSError, ValueError):+ return {}+ return v if isinstance(v, dict) else {}+out = {"replay_success": False, "deterministic": False, "video": False}+try:+ out.update(json.load(open(os.path.join(d, "episode.json"))))+except Exception as exc:+ out["error"] = f"no episode.json: {exc!r}"+a, b = result("replay1.json"), result("replay2.json")+out["replay_success"] = bool(a.get("success")) and bool(b.get("success"))+out["replay_sha"], out["replay_sha2"] = a.get("state_sha"), b.get("state_sha")+out["deterministic"] = bool(a.get("state_sha")) and a.get("state_sha") == b.get("state_sha")+out["live_matches_replay"] = bool(a.get("state_sha")) and a.get("state_sha") == out.get("live_sha")+if not (a.get("state_sha") and b.get("state_sha")): # a replay process died (it crashed or timed out): not the agent's 0+ out.update({"replay_failed": 1, "infra_error": 1,+ "error": "a replay process gave no result (replay1.log / replay2.log)"})+elif not (a.get("instance_ok") and b.get("instance_ok")): # the image no longer builds the frozen start: not the agent's 0+ out.update({"instance_mismatch": 1, "infra_error": 1, "error": "a replay did not start in the instance's t = 0 state"})+out["finalized"] = True+json.dump(out, open(os.path.join(d, "final.json"), "w"))+print(json.dumps(out))+PY+replay 3 --video "$DATA/replay.mp4"+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+try:+ shown = json.load(open(os.path.join(d, "replay3.json"))).get("video")+except (OSError, ValueError):+ shown = False+if shown:+ p = os.path.join(d, "final.json"); out = json.load(open(p)); out["video"] = True; json.dump(out, open(p, "w"))+PYdiff --git a/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/instance.json b/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/instance.jsonnew file mode 100644index 0000000000..4aba72fed1--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/instance.json@@ -0,0 +1,192 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "BarkourJoystick",+ "seed": 2,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 0.2800000011920929,+ 1.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.5,+ 1.0,+ 0.0,+ 0.5,+ 1.0,+ 0.0,+ 0.5,+ 1.0,+ 0.0,+ 0.5,+ 1.0+ ],+ "qvel0": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 0.4594014286994934,+ "vy": 0.22121715545654297,+ "wz": 0.016074633225798607+ },+ {+ "start_step": 501,+ "vx": 0.0903209000825882,+ "vy": -0.3885873854160309,+ "wz": 0.6428412795066833+ }+ ],+ "kicks": [+ {+ "start_step": 80,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.8203420823732267,+ -0.5718731221936891+ ]+ },+ {+ "start_step": 160,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.788163164239454,+ -0.6154663488250608+ ]+ },+ {+ "start_step": 240,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.9131765428086646,+ -0.4075642301085992+ ]+ },+ {+ "start_step": 320,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.3721731613746436,+ 0.9281633142677013+ ]+ },+ {+ "start_step": 400,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.9775782732872876,+ -0.2105723619011887+ ]+ },+ {+ "start_step": 480,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.8350665582365031,+ 0.5501489283049099+ ]+ },+ {+ "start_step": 581,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.7430595752025673,+ 0.6692252742535807+ ]+ },+ {+ "start_step": 661,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.8082263256570713,+ 0.5888719780350138+ ]+ },+ {+ "start_step": 741,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ 0.22144795284761612,+ -0.9751721920664063+ ]+ },+ {+ "start_step": 821,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.9990854215709072,+ -0.042758863461072875+ ]+ },+ {+ "start_step": 901,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.821963866092448,+ -0.5695396411474414+ ]+ },+ {+ "start_step": 981,+ "duration_steps": 5,+ "velocity_mps": 0.4883994162082672,+ "direction_xy": [+ -0.4999078076804545,+ -0.8660786245024881+ ]+ }+ ],+ "text": "Make Google's Barkour quadruped follow the joystick command schedule for the whole 10 s episode, through random pushes, without falling over.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": 0.0,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.22,+ "reference_rows": 1000,+ "torso_mass_kg": 14.496,+ "reference_worst_lin_err": 0.0329,+ "reference_worst_yaw_err": 0.0276+ },+ "state_sha": "90c7b858534f",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s), when its pushes (Barkour) are null or\n weak (peak under 20% of the torso's weight), or when the reference trajectory (oracle.py) fails the task's\n success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 3+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/rcb1.py b/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/rcb_limited.py b/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/rcb_limited.pynew file mode 100644index 0000000000..1ce1171787--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/rcb_limited.py@@ -0,0 +1,930 @@+"""eai-standard/2.2 (formerly rcb-limited/2.2): the HTTP layer, the protocol helpers and the crash recovery that every+2.2 sim service shares (docs/STANDARD_MODE_2_2.md; the 2.1 base is docs/LIMITED_MODE_PROTOCOL.md).++The source is scripts/eai_standard/rcb_limited.py; the generators copy it unchanged into every standard task's+environment/sim/ (ci_checks/check-tooling-identity.sh). A service keeps its simulator to itself (scene, action+execution, cameras, kinematic model) and hands this module plain callables:++ import rcb_limited as L+ EP = L.Episode(DATA, dim=N, resume="exact") # before the scene is built; "approx" for a nondeterministic simulator+ EP.startup() # start count, back-off after failed starts, startup watchdog+ S = <build the scene>; EP.scene_built() # the watchdog stands down+ def ctrl_step(a, rec): # every executed control step+ S.step(a); stop = EP.journal(a); rec.tick(); return E["done"] or stop+ rec = L.Recorder(cams, every, grab, proprio_row, extrinsics, clock, depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+ rec.tick(force=True) # first frame (before the chunk / watch)+ ...; rec.tick(); ... # after every control step: a frame every `every` steps+ rec.tick(force=True, last=True) # last frame (+ its depth)+ parts = rec.parts(video, fps) # RCB1 parts: video/ frames/ last/ extrinsic_cv/ last_depth/ depth_frames/ depth/ proprio frame_*+ S.record_start()+ EP.begin(state=E, step=S.step, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, start_event={...}, on_end=end_fn)+ L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics,+ status=status, on_submit_error=lambda exc: finish("error"), log=EP.log,+ episode=EP, state_sha=S.state_sha, proprio=proprio_row))++ grab(cams, want_depth) -> ({cam: uint8 (H,W,3)}, {cam: float32 (H,W) z-depth in metres, 0 = no reading})+ extrinsics(cams) -> {cam: (3,4) world -> camera, OpenCV axes (x right, y down, z forward)}+ proprio_row() -> float32 (len(spec["proprio_layout"]),)+ clock() -> int, control steps since the episode start (the frame's step index)+ do_kinematics(req) -> dict; `req` is parse_kinematics(body, spec["kinematics"]); it must never step physics++None of the callables may step physics. check_spec(SPEC) runs in serve(): a service whose /spec misses a 2.2 field, or+carries a field the protocol forbids (segmentation, object identities or sizes, physical parameters), does not start.+Crash recovery (class Episode; PROTOCOL §4.7): every executed control step is journaled, every completed call+checkpointed (rows, state hash, the robot's proprio row); after a crash compose restarts the container and the service+replays the journal and continues the SAME episode, never a reset. `python rcb_limited.py end <data dir>` is the shared+first half of a collect hook."""+from __future__ import annotations+import faulthandler, json, math, os, re, select, signal, socket, sys, tempfile, threading, time, traceback, zlib+from http.server import BaseHTTPRequestHandler, HTTPServer+from typing import Any, Callable++import numpy as np++import rcb1++PROTOCOL = "eai-standard/2.2"+COMPAT = ["rcb-limited/2.0", "rcb-limited/2.1", "eai-standard/2.1"] # requests written for these are served unchanged+MAX_BODY = 64 * 1024 * 1024+MAX_RESP = 256 * 1024 * 1024+DEPTH_MODES = ("none", "last", "frames")+DEPTH_MAX_M = 65.535 # uint16 millimetres; a farther surface reads 0 (no reading)+DEPTH_NOISE = os.environ.get("RCB_DEPTH_NOISE", "off").strip().lower() # off | realsense (as rcb-limited/2.1)+_RNG = np.random.default_rng(int(os.environ.get("RCB_DEPTH_NOISE_SEED", "0")))+PROPRIO_GROUPS_REQUIRED = ("joint_pos", "joint_vel", "gripper_opening", "tcp_pose", "joint_effort")+PART_PREFIXES = ("video/", "frames/", "last/", "last_depth/", "depth_frames/", "depth/", "extrinsic_cv/")+PART_NAMES = ("proprio", "frame_step", "frame_time_s")+++# ---------------------------------------------------------------- depth+def depth_mode(meta: dict) -> str:+ """The request's depth mode: "none" | "last" | "frames" (2.2 field `depth`), or "legacy" for a 2.0/2.1 request that+ sets `include_depth: true` and no `depth` (answered as 2.1 did: `depth/<cam>` float16 (N,H,W) metres)."""+ d = meta.get("depth")+ if d is None or d is False:+ return "legacy" if meta.get("include_depth") is True else "none"+ if d is True:+ return "last"+ if isinstance(d, str) and d in DEPTH_MODES:+ return d+ raise ValueError(f"depth must be one of {'|'.join(DEPTH_MODES)} (got {d!r})")+++def clean_depth(z) -> np.ndarray:+ """float32 z-depth in metres: non-finite, negative and beyond-range pixels read 0 (no reading); the optional+ RCB_DEPTH_NOISE=realsense model (sigma = 2 mm + 2.5 mm * z^2, 1 % dropouts) is applied here, after rendering, so it+ never touches physics."""+ z = np.asarray(z, dtype=np.float32).copy()+ if z.ndim == 3 and z.shape[-1] == 1:+ z = z[..., 0]+ bad = ~np.isfinite(z) | (z <= 0) | (z > DEPTH_MAX_M)+ z[bad] = 0.0+ if DEPTH_NOISE == "realsense":+ valid = z > 0+ z = z + _RNG.normal(0.0, 1.0, z.shape).astype(np.float32) * (0.002 + 0.0025 * z * z)+ z[_RNG.random(z.shape) < 0.01] = 0.0+ z[~valid] = 0.0+ z[(z < 0) | (z > DEPTH_MAX_M)] = 0.0+ return z.astype(np.float32)+++def depth_frames_part(name: str, stack: np.ndarray) -> tuple[str, str, bytes, dict]:+ """(N,H,W) metres -> an RCB1 "bytes" part: zlib of C-order uint16 millimetres (0 = no reading). Clients that do not+ know it keep the raw bytes and ignore it; rcb_client decodes it back to float32 metres."""+ mm = np.rint(np.asarray(stack, dtype=np.float64) * 1000.0)+ mm[(mm < 0) | (mm > 65535)] = 0+ a = np.ascontiguousarray(mm.astype("<u2"))+ return (name, "bytes", zlib.compress(a.tobytes(), 1), {"codec": "zlib", "dtype": "uint16", "shape": list(a.shape), "unit": "mm"})+++def encode_mp4(frames: np.ndarray, fps: int) -> bytes:+ """H.264 mp4 (yuv420p, faststart) of uint8 (N,H,W,3) frames: the same encoding every 2.0 service used."""+ import imageio.v2 as imageio+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tf:+ path = tf.name+ try:+ with imageio.get_writer(path, format="FFMPEG", mode="I", fps=fps, codec="libx264", macro_block_size=1,+ output_params=["-movflags", "+faststart", "-pix_fmt", "yuv420p"]) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ return open(path, "rb").read()+ finally:+ try:+ os.unlink(path)+ except OSError:+ pass+++# ---------------------------------------------------------------- recording what the cameras see during one call+class Recorder:+ """Frames of the requested cameras every `every` clock ticks, plus forced first/last frames; for every frame the+ proprio row, the clock (step index), each camera's extrinsics and, if asked, its depth. All arrays share one frame+ axis N: frames/<cam>, the mp4's frames, proprio, frame_step, frame_time_s, extrinsic_cv/<cam>, depth_frames/<cam>."""++ def __init__(self, cameras, every: int, grab: Callable, proprio_row: Callable, extrinsics: Callable, clock: Callable,+ depth: str = "none", clock_hz: float = 1.0):+ if depth not in DEPTH_MODES + ("legacy",):+ raise ValueError(f"bad depth mode {depth!r}")+ self.cams = list(cameras); self.every = max(1, int(every)); self.mode = depth; self.hz = float(clock_hz)+ self._grab, self._prop, self._ext, self._clock = grab, proprio_row, extrinsics, clock+ self.frames: dict = {c: [] for c in self.cams}; self.depth: dict = {c: [] for c in self.cams}+ self.ext: dict = {c: [] for c in self.cams}; self.last_depth: dict = {}+ self.prop: list = []; self.steps: list = []; self.n = 0; self.missing = 0++ def tick(self, force: bool = False, last: bool = False) -> None:+ if force or last or self.n % self.every == 0:+ self._capture(last)+ self.n += 1++ def _capture(self, last: bool) -> None:+ want = self.mode in ("frames", "legacy") or (last and self.mode == "last")+ rgb, dep = self._grab(self.cams, want)+ ext = self._ext(self.cams)+ for c in self.cams:+ img = rgb.get(c)+ if img is not None:+ img = np.ascontiguousarray(np.asarray(img)[..., :3].astype(np.uint8))+ else: # a camera that failed to render: a black frame (sized in parts()) keeps one frame axis+ self.missing += 1+ self.frames[c].append(img)+ e = ext.get(c)+ self.ext[c].append(np.full((3, 4), np.nan) if e is None else np.asarray(e, dtype=np.float64).reshape(3, 4))+ if want:+ d = dep.get(c)+ if d is None:+ d = np.zeros(img.shape[:2] if img is not None else (1, 1), np.float32)+ else:+ d = clean_depth(d)+ if img is not None and d.shape != img.shape[:2]:+ raise RuntimeError(f"depth of {c} is {d.shape}, its RGB {img.shape[:2]}: they must be pixel-aligned")+ if self.mode in ("frames", "legacy"):+ self.depth[c].append(d)+ if last or self.mode == "frames":+ self.last_depth[c] = d+ self.prop.append(np.asarray(self._prop(), dtype=np.float32).reshape(-1))+ self.steps.append(int(self._clock()))++ def parts(self, video: str, fps: int) -> list:+ if self.mode == "last" and not self.last_depth and self.prop: # no last=True tick: the state has not moved since+ _, dep = self._grab(self.cams, True)+ self.last_depth = {c: clean_depth(dep[c]) for c in self.cams if c in dep}+ out = []+ for c in self.cams:+ good = [f for f in self.frames[c] if f is not None]+ hw = good[-1].shape[:2] if good else (1, 1)+ if len(good) < len(self.frames[c]):+ self.frames[c] = [f if f is not None else np.zeros(hw + (3,), np.uint8) for f in self.frames[c]]+ self.depth[c] = [d if d.shape == hw else np.zeros(hw, np.float32) for d in self.depth[c]]+ if c in self.last_depth and self.last_depth[c].shape != hw:+ self.last_depth[c] = np.zeros(hw, np.float32)+ fr = np.stack(self.frames[c]) if self.frames[c] else np.zeros((0, 1, 1, 3), np.uint8)+ if video in ("mp4", "both") and len(fr):+ out.append((f"video/{c}", "mp4", encode_mp4(fr, fps), {"fps": fps, "n": int(len(fr))}))+ if video in ("frames", "both"):+ out.append(rcb1.array_part(f"frames/{c}", fr))+ if len(fr):+ out.append(rcb1.array_part(f"last/{c}", fr[-1]))+ out.append(rcb1.array_part(f"extrinsic_cv/{c}", np.stack(self.ext[c]) if self.ext[c] else np.zeros((0, 3, 4))))+ if self.mode in ("last", "frames") and c in self.last_depth:+ out.append(rcb1.array_part(f"last_depth/{c}", self.last_depth[c]))+ if self.mode == "frames" and self.depth[c]:+ out.append(depth_frames_part(f"depth_frames/{c}", np.stack(self.depth[c])))+ if self.mode == "legacy" and self.depth[c]:+ out.append(rcb1.array_part(f"depth/{c}", np.stack(self.depth[c]).astype(np.float16)))+ out.append(rcb1.array_part("proprio", np.stack(self.prop) if self.prop else np.zeros((0, 0), np.float32)))+ st = np.asarray(self.steps, dtype=np.int64)+ out.append(rcb1.array_part("frame_step", st))+ out.append(rcb1.array_part("frame_time_s", st.astype(np.float64) / self.hz))+ return out+++def encode_response(meta: dict, parts: list, max_bytes: int = MAX_RESP) -> bytes:+ """The RCB1 body; over `max_bytes` the per-frame depth goes first, then the raw frames (mp4, last frames, last+ depth, proprio and the per-frame arrays always stay), and meta["degraded"] says what was dropped."""+ body = rcb1.encode(meta, parts)+ dropped = []+ for prefixes in (("depth_frames/", "depth/"), ("frames/",)):+ if len(body) <= max_bytes:+ break+ keep = [p for p in parts if not p[0].startswith(prefixes)]+ if len(keep) < len(parts):+ parts = keep; dropped += [x.rstrip("/") for x in prefixes]+ body = rcb1.encode({**meta, "degraded": f"response over {max_bytes} bytes: {', '.join(dropped)} dropped"}, parts)+ return body+++# ---------------------------------------------------------------- kinematics+def _vec(x, n: int, what: str) -> list:+ a = np.asarray(x, dtype=np.float64).reshape(-1) if x is not None else None+ if a is None or a.size != n or not np.all(np.isfinite(a)):+ raise ValueError(f"{what} must be {n} finite numbers")+ return a.tolist()+++def _pose(x, what: str) -> list:+ p = _vec(x, 7, what)+ nq = math.sqrt(sum(v * v for v in p[3:]))+ if nq < 1e-6:+ raise ValueError(f"{what}: quaternion has zero norm")+ return p[:3] + [v / nq for v in p[3:]]+++def parse_kinematics(body: dict, kin: dict) -> dict:+ """Validate a /kinematics request against spec["kinematics"] (ValueError -> 400). Returns+ {"op": "fk", "q", "links", "base_pose"} or {"op": "ik", "targets": {frame: pose7}, "seed", "base_pose", "tol_pos_m",+ "tol_rot_rad", "max_iters"}; poses are x y z + a unit quaternion in the spec's order; q follows kin["joint_names"]."""+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object")+ op = body.get("op"); n = len(kin["joint_names"])+ base = None+ if body.get("base_pose") is not None:+ if kin.get("frame") != "base":+ raise ValueError("base_pose is only accepted by a mobile robot (spec kinematics.frame == 'base')")+ base = _pose(body["base_pose"], "base_pose")+ if op == "fk":+ links = body.get("links") or list(kin["links"])+ if not isinstance(links, list) or any(l not in kin["links"] for l in links):+ raise ValueError(f"links must be a list of names from spec kinematics.links: {kin['links']}")+ return {"op": "fk", "q": _vec(body.get("q"), n, "q"), "links": links, "base_pose": base}+ if op == "ik":+ tg = body.get("targets")+ if not isinstance(tg, dict) or not tg or any(k not in kin["ik_targets"] for k in tg):+ raise ValueError(f"targets must map frames from spec kinematics.ik_targets {kin['ik_targets']} to poses")+ ik = kin.get("ik", {})+ seed = None if body.get("seed") is None else _vec(body["seed"], n, "seed")+ tol_p = float(body.get("tol_pos_m", ik.get("tol_pos_m", 0.005)))+ tol_r = float(body.get("tol_rot_rad", ik.get("tol_rot_rad", 0.05)))+ it = int(body.get("max_iters", ik.get("max_iters", 200)))+ if not (1e-5 <= tol_p <= 0.5 and 1e-4 <= tol_r <= 3.2 and 1 <= it <= 5000):+ raise ValueError("tol_pos_m in [1e-5, 0.5], tol_rot_rad in [1e-4, 3.2], max_iters in [1, 5000]")+ return {"op": "ik", "targets": {k: _pose(v, f"targets[{k}]") for k, v in tg.items()}, "seed": seed, "base_pose": base,+ "tol_pos_m": tol_p, "tol_rot_rad": tol_r, "max_iters": it}+ raise ValueError("op must be 'fk' or 'ik'")+++def fk_response(poses: dict, frame: str) -> dict:+ return {"ok": True, "op": "fk", "frame": frame, "poses": {k: [float(v) for v in np.asarray(p, dtype=np.float64).reshape(7)] for k, p in poses.items()}}+++def ik_response(q, ok: bool, errors: dict, frame: str, note: str | None = None) -> dict:+ """errors: {frame: (position error m, rotation error rad)} of the returned q (None / non-finite -> null: no solution)."""+ fin = lambda v: float(v) if v is not None and math.isfinite(float(v)) else None # noqa: E731+ out = {"ok": bool(ok), "op": "ik", "frame": frame, "q": None if q is None else [float(v) for v in np.asarray(q).reshape(-1)],+ "error": {k: {"pos_m": fin(e[0]), "rot_rad": fin(e[1])} for k, e in errors.items()}}+ if note:+ out["note"] = note+ return out+++def quat_angle(q1, q2) -> float:+ """Rotation angle (rad) between two unit quaternions of the same order."""+ d = abs(float(np.dot(np.asarray(q1, dtype=np.float64), np.asarray(q2, dtype=np.float64))))+ return 2.0 * math.acos(min(1.0, d))+++# ---------------------------------------------------------------- /spec self-check+FORBIDDEN_KEY = re.compile(r"mask|segment|semantic(?!s$)|instance_?id|bbox|bounding|categor|object|\bobj_|label|mass|friction|"+ r"restitution|inertia|density|damping|stiffness", re.I)+GAIN_PATHS = ("robot_spec.controller",) # joint drive gains (stiffness, damping) are the robot's own, and allowed there+POSITION_KEY = re.compile(r"(?:^|_)(?:pos|position|positions|pose|poses|origin|location|coords?|coordinates|world|translation)(?:_|$)|"+ r"(?:^|_)cent(?:er|re)s?(?:_|$)|(?:^|_)xyz?$|(?:^|_)(?:top|surface|floor|table|plane|height|elevation)?_?z$", re.I)+WORLD_TEXT = re.compile(r"\bworld\s+[xyz]\s*=", re.I)+COORDS = re.compile(r"\(\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*(?:,\s*-?\d+(?:\.\d+)?\s*)?\)")+++def world_text(s: str) -> bool:+ """A text that gives a world coordinate: a pixel-to-world formula, or a coordinate tuple with a decimal point that is+ not the robot's own pose ("robot base at (0, 0, 1.08)" stays)."""+ return bool(WORLD_TEXT.search(s)) or any("." in m.group(0) and not re.search(r"base|robot|origin", s[max(0, m.start() - 40):m.start()], re.I)+ for m in COORDS.finditer(s))+CONVENTIONS = {"static.floor_z": 0.0} # BEHAVIOR: the floor is the plane z = 0 (the world frame's definition)+++def static_positions(obj: Any, path: str = "static") -> list[str]:+ """Paths in /spec static that say WHERE something is (keys naming positions, heights, centres; texts with world+ coordinates). Names, inventories, sizes and colours may stay in static; positions never (docs § Never provided)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}"+ if POSITION_KEY.search(str(k)) and CONVENTIONS.get(p, object()) != v:+ out.append(p)+ else:+ out += static_positions(v, p)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += static_positions(v, f"{path}[{i}]")+ elif isinstance(obj, str) and world_text(obj):+ out.append(path)+ return out+++SPEC_REQUIRED = ("protocol", "protocol_compat", "simulator", "robot", "task_text", "control_hz", "cameras", "default_cameras",+ "action_types", "proprio_layout", "proprio_groups", "static", "world", "budget", "robot_spec", "kinematics", "depth")+++def forbidden_keys(obj: Any, path: str = "", skip: tuple = ()) -> list[str]:+ """Key paths that name something the protocol never provides (key paths in `skip` are not searched)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}" if path else str(k)+ if p in skip:+ continue+ if FORBIDDEN_KEY.search(str(k)) and not (re.search(r"damping|stiffness", str(k), re.I) and p.startswith(GAIN_PATHS)):+ out.append(p)+ out += forbidden_keys(v, p, skip)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += forbidden_keys(v, f"{path}[{i}]", skip)+ return out+++def check_spec(spec: dict) -> None:+ """Raise if /spec is not a complete 2.2 spec or names anything forbidden (run at startup, before binding :8000)."""+ miss = [k for k in SPEC_REQUIRED if k not in spec]+ if miss:+ raise RuntimeError(f"/spec misses {miss}")+ if spec["protocol"] != PROTOCOL:+ raise RuntimeError(f"/spec protocol {spec['protocol']!r} != {PROTOCOL}")+ bad = forbidden_keys(spec, skip=())+ if bad:+ raise RuntimeError(f"/spec names forbidden fields: {bad}")+ pos = static_positions(spec["static"])+ if pos:+ raise RuntimeError(f"/spec static says where things are (never provided): {pos}")+ lay = spec["proprio_layout"]+ if len(set(lay)) != len(lay):+ raise RuntimeError("proprio_layout names are not unique")+ for g in PROPRIO_GROUPS_REQUIRED:+ if g not in spec["proprio_groups"]:+ raise RuntimeError(f"proprio_groups misses {g}")+ for g, (first, n, _meaning) in spec["proprio_groups"].items():+ if not (0 <= first and first + n <= len(lay)):+ raise RuntimeError(f"proprio group {g} [{first}, +{n}) outside the {len(lay)} columns")+ kin = spec["kinematics"]+ for k in ("endpoint", "joint_names", "frame", "quaternion_order", "links", "tcp_frames", "ee_frames", "ik_targets"):+ if k not in kin:+ raise RuntimeError(f"kinematics misses {k}")+ if any(j not in lay for j in kin["joint_names"]):+ raise RuntimeError("kinematics.joint_names must be proprio_layout columns (the measured joint positions)")+ if any(f not in kin["links"] for f in list(kin["tcp_frames"]) + list(kin["ee_frames"]) + list(kin["ik_targets"])):+ raise RuntimeError("kinematics tcp_frames / ee_frames / ik_targets must be listed in kinematics.links")+ if spec["proprio_groups"]["tcp_pose"][1] != 7 * len(kin["tcp_frames"]):+ raise RuntimeError("proprio group tcp_pose must hold 7 columns per kinematics.tcp_frames entry")+ for c, cam in spec["cameras"].items():+ for k in ("rgb", "depth", "mounted", "resolution", "intrinsic_cv", "mount"):+ if k not in cam:+ raise RuntimeError(f"cameras.{c} misses {k}")+ if cam["mount"].get("type") not in ("static", "link"):+ raise RuntimeError(f"cameras.{c}.mount.type must be static|link")+ if any(c not in spec["cameras"] for c in spec["default_cameras"]):+ raise RuntimeError("default_cameras must be cameras")+++# ---------------------------------------------------------------- crash recovery (PROTOCOL §4.7; docs/STANDARD_MODE_2_2.md)+MAX_RESUMES = int(os.environ.get("RCB_MAX_RESUMES", "2"))+STARTUP_TIMEOUT_S = float(os.environ.get("RCB_STARTUP_TIMEOUT_S", "900")) # a task with a slower scene build sets more+MAX_CALL_WALL_S = float(os.environ.get("RCB_MAX_CALL_WALL_S", "900")) # < the client's 1800 s /submit read timeout+RESUME_MAX_DEV_M = float(os.environ.get("RCB_RESUME_MAX_DEV_M", "0.05")) # approx resumes: the gross-divergence guard+ON_SERVICE_ERROR = ("a connection error means the service crashed: it restarts and resumes the SAME episode (never a reset) "+ "in the state after the last call it completed, which you may not have received. Wait until GET /status "+ "answers again (rcb_client: Robot.wait_ready(); resuming replays the episode so far, which can take "+ "minutes in a long episode, and the wall clock keeps running), then check calls and control_steps "+ "before you continue. A 500 means the simulator failed: the episode is over (reason \"error\"). A call "+ "that runs longer than max_call_wall_s seconds stops at the next control step and returns what it "+ "executed (meta.stopped, executed_rows).")+++def _jsonable(v: Any) -> Any:+ if isinstance(v, np.ndarray):+ return v.tolist()+ if isinstance(v, (np.floating, np.integer, np.bool_)):+ return v.item()+ if isinstance(v, (list, tuple)):+ return [_jsonable(x) for x in v]+ if isinstance(v, dict):+ return {str(k): _jsonable(x) for k, x in v.items()}+ return v+++def _peer_closed(sock) -> bool:+ """True when the client of an HTTP request has closed its connection (it gave up on the call): the socket reads as+ end-of-file. A client never sends anything while it waits for the response, so readable means closed."""+ try:+ r, _, _ = select.select([sock], [], [], 0)+ return bool(r) and sock.recv(1, socket.MSG_PEEK) == b""+ except (OSError, ValueError):+ return True+++def _read_json(path: str) -> dict:+ try:+ with open(path) as f:+ d = json.load(f)+ return d if isinstance(d, dict) else {}+ except (OSError, ValueError):+ return {}+++def _write_json(path: str, obj: dict) -> None:+ tmp = f"{path}.{os.getpid()}.tmp"+ with open(tmp, "w") as f:+ json.dump(obj, f)+ os.replace(tmp, path)+++def final_verdict(data: str) -> dict | None:+ """final.json if it already holds a verdict that nothing may overwrite: the grading result (finalized, with+ `deterministic`) or the end of an episode the service gave up after crashes (`gave_up`)."""+ fin = _read_json(os.path.join(data, "final.json"))+ if fin.get("finalized") and (fin.get("gave_up") or fin.get("deterministic") is not None):+ return fin+ return None+++class Episode:+ """Crash-safe episode bookkeeping, the same rules as the RoboTwin and MuJoCo services (PROTOCOL §4.7):++ - startup(): before the scene is built. One line in startups.jsonl; a back-off of min(120, 20 (n - 1)) s when the+ earlier starts never began an episode (they crashed while building, e.g. GPU memory taken by other trials); the+ startup watchdog (faulthandler, a C thread: it fires even when a native scene build holds the GIL) dumps every+ thread's traceback and exits 1 after RCB_STARTUP_TIMEOUT_S, so compose restarts the build. Until begin() a SIGUSR1+ (the collect hook's "the agent phase is over") is only remembered.+ - journal(row): every executed control step (the exact row given to the simulator's step) goes to journal.f64.+ - checkpoint(): after every completed call (the HTTP layer calls it): the journal is flushed, then the call's+ checkpoint is logged in episode.jsonl (rows, control steps, state hash, the robot's proprio row, `persist` keys).+ - begin(): a fresh episode, or after a crash (run.sh exits non-zero, compose restarts the container, `restart:+ on-failure:N`) the SAME episode resumed: the journal is replayed up to the last checkpoint, the journal truncated+ there (the call that was in flight is lost as a whole: its caller got an error, not a result), the state hash+ compared, the service's counters restored; the wall clock keeps running from the first start.+ - Resume check, by the simulator's determinism class: `exact` (bit-exact in a fresh process): the hash must match,+ else the episode ends `resume_failed` (infra_error). `approx` (a simulator declared nondeterministic): a+ mismatch is recorded (resume_state_mismatch, and the robot's deviation from its checkpointed proprio: joint_pos and+ tcp_pose) and the episode continues, unless a TCP is more than RCB_RESUME_MAX_DEV_M from where it was+ (resume_failed, infra_error). The verdict never comes from the live state but from fresh replays of the complete+ recorded trajectory, so continuing cannot raise a score.+ - More than RCB_MAX_RESUMES crashes end the episode: `sim_crashed_on_call` if every crash happened while a call was+ being served (the agent's failure), else `sim_crashed` (infra_error = 1). A verdict already on disk is never+ overwritten; the service then idles with its PID file for the collect hook.+ - Per call, two bounds keep one call from holding the single-threaded service: a call that runs longer than+ max_call_wall_s, or whose client has hung up, stops at the next control step and returns what it executed+ (journal() returns True; meta.stopped says why). Neither bounds the episode: the wall clock is its only budget."""++ def __init__(self, data: str, dim: int, resume: str = "exact", persist: tuple = ()):+ if resume not in ("exact", "approx"):+ raise ValueError("resume must be 'exact' or 'approx'")+ self.data, self.dim, self.resume_class, self.persist = data, int(dim), resume, tuple(persist)+ os.makedirs(data, exist_ok=True)+ p = lambda n: os.path.join(data, n) # noqa: E731+ self.f_events, self.f_journal, self.f_final, self.f_pid, self.f_startups = (+ p("episode.jsonl"), p("journal.f64"), p("final.json"), p("server.pid"), p("startups.jsonl"))+ self.rows = 0 # control steps executed in this episode (journaled)+ self.max_call_wall_s = MAX_CALL_WALL_S+ self.n_startups = 0; self.resumes = 0; self.mismatches = 0; self.max_tcp_dev = 0.0; self.max_joint_dev = 0.0+ self._jf = None; self._call: dict | None = None; self._ids = 0; self._ck: tuple | None = None+ self._on_end: Callable | None = None; self._end_pending = False++ # ---- startup+ def startup(self) -> None:+ signal.signal(signal.SIGUSR1, self._usr1)+ try:+ os.remove(self.f_pid) # a PID file from before a crash would send the collect hook to a dead process+ except OSError:+ pass+ with open(self.f_startups, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid()}) + "\n")+ with open(self.f_startups) as f:+ self.n_startups = sum(1 for line in f if line.strip())+ if self.n_startups > 1 and not any(e.get("ev") == "start" for e in self.events()):+ time.sleep(min(120.0, 20.0 * (self.n_startups - 1)))+ faulthandler.dump_traceback_later(STARTUP_TIMEOUT_S, exit=True)++ def scene_built(self) -> None:+ faulthandler.cancel_dump_traceback_later() # the scene exists: a resume replay may take long, it is not a hang++ def _usr1(self, *_):+ if self._on_end is None:+ self._end_pending = True+ else:+ threading.Thread(target=self._on_end, daemon=True).start()++ # ---- the record+ def log(self, ev: dict) -> None:+ with open(self.f_events, "a") as f:+ f.write(json.dumps(_jsonable({"ts": time.time(), **ev})) + "\n")++ def events(self) -> list:+ out = []+ try:+ with open(self.f_events) as f:+ for line in f:+ try:+ out.append(json.loads(line))+ except ValueError: # a line cut by a crash+ pass+ except OSError:+ pass+ return [e for e in out if isinstance(e, dict)]++ def journal(self, row) -> bool:+ """One executed control step. True: the call in progress must stop at this step boundary (meta.stopped)."""+ a = np.asarray(row, dtype=np.float64).reshape(-1)+ if a.size != self.dim:+ raise ValueError(f"journal rows have {self.dim} entries, got {a.size}")+ if self._jf is None:+ self._jf = open(self.f_journal, "ab")+ self._jf.write(a.tobytes()); self.rows += 1+ c = self._call+ if c is None:+ return False+ if c["stopped"] is None:+ now = time.monotonic()+ if now - c["t0"] > self.max_call_wall_s:+ c["stopped"] = "max_call_wall_s"+ elif c["sock"] is not None and now - c["polled"] >= 0.2:+ c["polled"] = now+ if _peer_closed(c["sock"]):+ c["stopped"] = "client_disconnected"+ return c["stopped"] is not None++ @property+ def stopping(self) -> bool:+ """The call in progress must stop (adapters whose loops test E["done"] test this too)."""+ return bool(self._call and self._call["stopped"])++ @property+ def stop_reason(self) -> str | None:+ return self._call["stopped"] if self._call else None++ def call_begin(self, path: str, sock=None) -> int:+ self._ids += 1+ if path != "/kinematics":+ self._call = {"id": self._ids, "t0": time.monotonic(), "sock": sock, "polled": 0.0, "stopped": None}+ self.log({"ev": "call_begin", "id": self._ids, "path": path})+ return self._ids++ def call_end(self, cid: int, path: str, **extra) -> None:+ self.log({"ev": "call_end", "id": cid, "path": path, **extra})+ if path != "/kinematics":+ self._call = None++ def checkpoint(self, state: dict, state_sha: Callable | None, proprio: Callable | None) -> None:+ if self._jf is not None:+ self._jf.flush() # the rows reach the file before the checkpoint that counts them+ if self._ck is not None and self._ck[0] == self.rows:+ sha, pr = self._ck[1], self._ck[2] # no physics since the last checkpoint+ else:+ try:+ sha = state_sha() if state_sha else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); sha = None+ pr = self._proprio_row(proprio)+ self._ck = (self.rows, sha, pr)+ self.log({"ev": "checkpoint", "call": int(state.get("calls") or 0), "step": int(state.get("step") or 0),+ "control_steps": self.rows, "success": bool(state.get("success")), "done": bool(state.get("done")),+ "reason": state.get("reason"), "state_sha": sha, "proprio": pr,+ **({"persist": {k: state.get(k) for k in self.persist}} if self.persist else {})})++ @staticmethod+ def _proprio_row(proprio: Callable | None) -> list | None:+ try:+ return [round(float(v), 6) for v in np.asarray(proprio(), dtype=np.float64).reshape(-1)] if proprio else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); return None++ def final_fields(self) -> dict:+ """Crash-recovery fields for final.json / episode.json (all numeric, for reward.json)."""+ return {"sim_startups": self.n_startups, "resumes": self.resumes, "resume_state_mismatch": int(self.mismatches > 0),+ "resume_max_tcp_dev_m": round(self.max_tcp_dev, 6), "resume_max_joint_dev": round(self.max_joint_dev, 6)}++ # ---- start or resume+ def begin(self, *, state: dict, step: Callable, state_sha: Callable, proprio: Callable, spec: dict,+ start_event: dict | None = None, on_end: Callable | None = None) -> bool:+ """Start the episode, or resume it after a crash. `step(row)` executes one journaled row on the simulator (the+ recorder on, no rendering needed); `on_end` is what the collect hook's SIGUSR1 runs (in a thread). Returns True+ if the episode was resumed."""+ try: # a line cut by the crash must not swallow the next record+ with open(self.f_events, "rb+") as f:+ f.seek(0, os.SEEK_END)+ if f.tell():+ f.seek(-1, os.SEEK_END)+ if f.read(1) != b"\n":+ f.write(b"\n")+ except OSError:+ pass+ ev = self.events()+ starts = [e for e in ev if e.get("ev") == "start"]+ if not starts:+ try:+ os.remove(self.f_journal)+ except OSError:+ pass+ sha = state_sha()+ self._ck = (0, sha, self._proprio_row(proprio))+ self.log({**(start_event or {}), "ev": "start", "state_sha": sha, "protocol": PROTOCOL, "resume": self.resume_class,+ "journal_dim": self.dim})+ state["t0"] = time.time()+ self._arm(on_end)+ return False+ tries = [e for e in ev if e.get("ev") == "resuming"] # earlier resumes (a crash during one counts too)+ resumed = [e for e in ev if e.get("ev") == "resumed"]+ self.resumes = len(tries) # the record so far, also for a give-up below (final_fields)+ self.mismatches = sum(1 for e in resumed if e.get("exact") is False)+ self.max_tcp_dev = max([float(e.get("tcp_dev_m") or 0) for e in resumed] + [0.0])+ self.max_joint_dev = max([float(e.get("joint_dev") or 0) for e in resumed] + [0.0])+ if final_verdict(self.data):+ self.give_up("restarted after finalize", infra=False)+ k = max(i for i, e in enumerate(ev) if e.get("ev") in ("start", "resuming", "resumed"))+ tail = ev[k + 1:]+ in_call = bool({e.get("id") for e in tail if e.get("ev") == "call_begin"} - {e.get("id") for e in tail if e.get("ev") == "call_end"})+ if len(tries) >= MAX_RESUMES:+ agent = sum(1 for e in tries if e.get("crashed_in_call")) + int(in_call) == len(tries) + 1+ self.give_up("sim_crashed_on_call" if agent else "sim_crashed", infra=not agent)+ self.log({"ev": "resuming", "attempt": len(tries) + 1, "crashed_in_call": in_call,+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self.resumes = len(tries) + 1 # this attempt counts, whether or not it succeeds+ cps = [e for e in ev if e.get("ev") == "checkpoint"]+ last = cps[-1] if cps else {"call": 0, "step": 0, "control_steps": 0, "success": False, "state_sha": starts[0].get("state_sha")}+ n = int(last.get("control_steps") or 0)+ try:+ R = np.fromfile(self.f_journal, dtype=np.float64)+ except (OSError, ValueError):+ R = np.zeros(0)+ if R.size < n * self.dim:+ self.give_up("resume_failed: journal shorter than the log", infra=True)+ R = R[: n * self.dim].reshape(n, self.dim)+ t = time.time()+ for row in R:+ step(row)+ replay_s = time.time() - t+ R.tofile(self.f_journal) # drop the rows of the call that was in flight+ self.rows = n+ sha = state_sha(); want = last.get("state_sha")+ exact = None if want is None else sha == want+ dev = self._deviation(last.get("proprio"), proprio, spec)+ if exact is False: # recorded first: a give-up below reports it too+ self.mismatches += 1+ self.max_tcp_dev = max(self.max_tcp_dev, dev.get("tcp_m") or 0.0)+ self.max_joint_dev = max(self.max_joint_dev, dev.get("joint") or 0.0)+ if self.resume_class == "exact":+ self.give_up("resume_failed: replayed state differs from the logged one", infra=True)+ if dev.get("tcp_m") is not None and dev["tcp_m"] > RESUME_MAX_DEV_M:+ self.give_up(f"resume_failed: a replayed TCP is {dev['tcp_m']:.3f} m from its checkpoint (> {RESUME_MAX_DEV_M} m)", infra=True)+ state["calls"] = int(last.get("call") or 0); state["step"] = int(last.get("step") or 0)+ if "success" in state:+ state["success"] = bool(last.get("success"))+ for key, v in (last.get("persist") or {}).items():+ state[key] = v+ state["t0"] = float(starts[0]["ts"])+ ended = [e for e in ev if e.get("ev") == "end" and int(e.get("control_steps") or 0) <= n] # not the lost call's+ if ended:+ state["done"] = True; state["reason"] = ended[-1].get("reason"); state["t_end"] = float(ended[-1]["ts"])+ state["episode_control_steps"] = int(ended[-1].get("control_steps") or n)+ self._ck = (n, sha, self._proprio_row(proprio)) # the replayed state's row (it may differ under approx)+ self.log({"ev": "resumed", "attempt": self.resumes, "control_steps": n, "calls": state["calls"], "state_sha": sha,+ "logged_sha": want, "exact": exact, "class": self.resume_class, "tcp_dev_m": dev.get("tcp_m"),+ "joint_dev": dev.get("joint"), "crashed_in_call": in_call, "replay_s": round(replay_s, 1),+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self._arm(on_end)+ return True++ @staticmethod+ def _deviation(ref, proprio: Callable, spec: dict) -> dict:+ """The replayed robot against its checkpointed proprio row: max |joint_pos| difference (rad or m) and the largest+ TCP position error (m) over the tcp_pose frames (7 columns each: x y z + quaternion)."""+ if ref is None:+ return {}+ try:+ now = np.asarray(proprio(), dtype=np.float64).reshape(-1); ref = np.asarray(ref, dtype=np.float64).reshape(-1)+ except Exception: # noqa: BLE001+ return {}+ if now.shape != ref.shape:+ return {}+ g, out = spec.get("proprio_groups") or {}, {}+ if "joint_pos" in g:+ f, n = int(g["joint_pos"][0]), int(g["joint_pos"][1])+ out["joint"] = float(np.max(np.abs(now[f:f + n] - ref[f:f + n]))) if n else 0.0+ if "tcp_pose" in g:+ f, n = int(g["tcp_pose"][0]), int(g["tcp_pose"][1]); m = n // 7+ d = (now[f:f + 7 * m] - ref[f:f + 7 * m]).reshape(m, 7)[:, :3]+ out["tcp_m"] = float(np.max(np.linalg.norm(d, axis=1))) if m else 0.0+ return out++ def _arm(self, on_end: Callable | None) -> None:+ self._on_end = on_end+ signal.signal(signal.SIGUSR1, self._usr1)+ if on_end is not None and self._end_pending:+ self._end_pending = False+ threading.Thread(target=on_end, daemon=True).start()++ def give_up(self, reason: str, infra: bool) -> None:+ """End the trial's episode without a new one (never a reset): log it, write the verdict unless one is on disk,+ leave the PID file for the collect hook, and idle until the container is removed."""+ faulthandler.cancel_dump_traceback_later()+ self.log({"ev": "restart_refused", "reason": reason})+ if not final_verdict(self.data):+ fin = _read_json(self.f_final)+ fin.update({"success": False, "done": True, "reason": reason, "finalized": True, "gave_up": True, "protocol": PROTOCOL,+ **self.final_fields(), **({"infra_error": 1} if infra else {})})+ _write_json(self.f_final, fin)+ with open(self.f_pid, "w") as f:+ f.write(str(os.getpid()))+ signal.signal(signal.SIGUSR1, lambda *_: None)+ print(f"[{PROTOCOL}] restart refused: {reason}", flush=True)+ while True:+ time.sleep(3600)+++# ---------------------------------------------------------------- the HTTP layer+class Service:+ """What a sim service hands to serve(): spec (dict), lock, state (the service's E dict: done, reason, exiting, error),+ submit(meta, actions) and observe(meta) -> (meta_out, rcb1 parts), kinematics(req) -> dict, status() -> dict,+ on_submit_error(exc) (a simulator error in /submit or /observe: it ends the episode, reason "error"), log(event dict),+ and for crash recovery the Episode with the simulator's state_sha() and proprio row()."""++ def __init__(self, *, spec: dict, lock, state: dict, submit: Callable, observe: Callable, kinematics: Callable,+ status: Callable, on_submit_error: Callable, log: Callable, max_resp: int = MAX_RESP,+ episode: Episode | None = None, state_sha: Callable | None = None, proprio: Callable | None = None):+ self.spec, self.lock, self.state, self.submit, self.observe = spec, lock, state, submit, observe+ self.kinematics, self.status, self.on_submit_error, self.log, self.max_resp = kinematics, status, on_submit_error, log, max_resp+ self.episode, self.state_sha, self.proprio = episode, state_sha, proprio+ self.kin_calls = 0+++def make_handler(svc: Service):+ class H(BaseHTTPRequestHandler):+ def _send(self, code: int, ctype: str, body: bytes) -> None:+ try:+ self.send_response(code); self.send_header("Content-Type", ctype); self.send_header("Content-Length", str(len(body)))+ self.end_headers(); self.wfile.write(body)+ except (BrokenPipeError, ConnectionResetError): # the client hung up (its call was abandoned)+ pass++ def _json(self, code: int, obj: dict) -> None:+ self._send(code, "application/json", json.dumps(obj).encode())++ def _rcb1(self, meta: dict, parts: list) -> None:+ self._send(200, "application/x-rcb1", encode_response(meta, parts, svc.max_resp))++ def log_message(self, *a):+ pass++ def _body(self):+ try:+ n = int(self.headers.get("Content-Length", 0))+ except ValueError:+ raise ValueError("bad Content-Length")+ if n > MAX_BODY:+ raise ValueError("request too large")+ raw = self.rfile.read(n) if n else b""+ if raw[:4] == rcb1.MAGIC:+ return rcb1.decode(raw)+ body = json.loads(raw or b"{}")+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object or an RCB1 frame")+ return body, {}++ def do_GET(self):+ if self.path == "/spec":+ return self._json(200, svc.spec)+ if self.path == "/status":+ st = svc.status()+ return self._json(200, {**st, "resumes": svc.episode.resumes} if svc.episode else st)+ return self._json(404, {"error": "no such endpoint"})++ def do_POST(self):+ if self.path not in ("/submit", "/observe", "/kinematics"):+ return self._json(404, {"error": "no such endpoint"})+ try:+ meta, parts = self._body()+ except Exception as exc: # noqa: BLE001+ return self._json(413 if "too large" in str(exc) else 400, {"error": str(exc)[:200]})+ E, ep = svc.state, svc.episode+ if self.path == "/kinematics": # stateless: never steps physics, never waits for the episode lock+ cid = ep.call_begin(self.path) if ep else 0+ try:+ req = parse_kinematics(meta, svc.spec["kinematics"])+ out = svc.kinematics(req); svc.kin_calls += 1+ except ValueError as exc:+ return self._json(400, {"error": str(exc)[:300]})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); return self._json(500, {"error": "kinematics error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ ep.call_end(cid, self.path)+ return self._json(200, out)+ with svc.lock:+ if E.get("exiting") or (self.path == "/submit" and E.get("done")):+ return self._json(409, {"error": "episode finished", "reason": E.get("reason")})+ cid = ep.call_begin(self.path, self.connection) if ep else 0+ rows0 = ep.rows if ep else 0+ out = blobs = err = None; stopped = None+ try:+ if self.path == "/submit":+ A = np.asarray(parts["actions"]["data"] if "actions" in parts else meta.get("actions", []), dtype=np.float64)+ out, blobs = svc.submit(meta, A)+ else:+ out, blobs = svc.observe(meta)+ except ValueError as exc:+ err = (400, {"error": str(exc)})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); E["error"] = repr(exc); svc.log({"ev": "error", "path": self.path, "error": repr(exc)})+ try:+ svc.on_submit_error(exc) # PROTOCOL §4.6: a simulator error ends the episode (reason "error")+ except Exception: # noqa: BLE001+ traceback.print_exc()+ err = (500, {"error": "simulator error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ stopped = ep.stop_reason+ if err is None or ep.rows != rows0:+ try:+ ep.checkpoint(E, svc.state_sha, svc.proprio)+ except Exception: # noqa: BLE001+ traceback.print_exc()+ ep.call_end(cid, self.path, **({"stopped": stopped} if stopped else {}))+ if err is not None:+ return self._json(*err)+ return self._rcb1({**out, "stopped": stopped}, blobs)+ return H+++def serve(svc: Service, port: int = 8000) -> None:+ """Check the spec, then serve forever (one request at a time, as every 2.x service)."""+ svc.spec.setdefault("on_service_error", ON_SERVICE_ERROR)+ if svc.episode is not None:+ svc.spec.setdefault("max_call_wall_s", svc.episode.max_call_wall_s)+ check_spec(svc.spec)+ HTTPServer(("0.0.0.0", port), make_handler(svc)).serve_forever()+++# ---------------------------------------------------------------- the collect hook's first half+def _alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ try: # a zombie (exited, not yet reaped) counts as gone+ with open(f"/proc/{pid}/stat") as f:+ return f.read().rsplit(")", 1)[-1].split()[0] != "Z"+ except OSError:+ return True+++def end_episode(data: str, timeout: float = 21600.0, wait_key: str | None = None, resend_s: float = 30.0) -> int:+ """Tell the service that the agent phase is over and wait until it has ended the episode. The service may be+ resuming after a crash (no PID file until it is ready again), so there is no fixed start-up wait, and a signal goes+ only to the process that wrote the newest line of startups.jsonl (its SIGUSR1 handler is installed by then).+ Returns 2: final.json already holds the verdict (the service gave up after crashes, or graded in-process; with+ `wait_key`, also waits for that final.json key, e.g. video_done): keep it, run no replays.+ Returns 0: the service dumped the episode (episode.json) and exited: the hook replays it next.+ Returns 1: timed out."""+ t0, sent = time.time(), 0.0+ f_pid, f_dump, f_starts = (os.path.join(data, n) for n in ("server.pid", "episode.json", "startups.jsonl"))+ while time.time() - t0 < timeout:+ fin = final_verdict(data)+ if fin is not None:+ if not wait_key or fin.get(wait_key) or fin.get("gave_up"):+ return 2+ time.sleep(2); continue+ try:+ with open(f_pid) as f:+ pid = int(f.read().strip())+ except (OSError, ValueError):+ pid = None+ try:+ with open(f_starts) as f:+ cur = json.loads([x for x in f if x.strip()][-1]).get("pid")+ except (OSError, ValueError, IndexError):+ cur = None # a service without Episode.startup(): signal what the PID file names+ if pid is not None and (cur is None or pid == cur):+ if not _alive(pid):+ if os.path.exists(f_dump):+ return 0+ elif time.time() - sent >= resend_s:+ try:+ os.kill(pid, signal.SIGUSR1); sent = time.time()+ except OSError:+ pass+ time.sleep(2)+ return 1+++if __name__ == "__main__":+ a = sys.argv[1:]+ if len(a) >= 2 and a[0] == "end":+ wk = a[a.index("--wait-key") + 1] if "--wait-key" in a else None+ to = float(a[a.index("--timeout") + 1]) if "--timeout" in a else 21600.0+ rc = end_episode(a[1], timeout=to, wait_key=wk)+ print({0: "[collect] episode dumped by the service", 1: "[collect] timed out waiting for the service",+ 2: "[collect] final.json already holds the verdict"}[rc], flush=True)+ sys.exit(rc)+ if len(a) == 2 and a[0] == "final-verdict":+ fin = final_verdict(a[1])+ print(json.dumps(fin) if fin else "no final verdict")+ sys.exit(0 if fin else 1)+ print("usage: rcb_limited.py end <data dir> [--wait-key KEY] [--timeout S] | final-verdict <data dir>")+ sys.exit(2)diff --git a/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/rcb_quadruped.py b/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/run.sh b/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/run.shnew file mode 100755index 0000000000..49d4d045d4--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/run.sh@@ -0,0 +1,22 @@+#!/bin/sh+# eai-standard/2.2 sidecar entrypoint: PID 1 of the `sim` container, shared by every 2.2 service+# (scripts/eai_standard/run.sh, copied unchanged into each standard task's environment/sim/).+# - The service crashed (a non-zero exit: an exception, a signal, the startup watchdog): exit with its code, so compose+# restarts the container (`restart: on-failure:6`) and the service resumes the same episode from its journal+# (rcb_limited.Episode). The container keeps its /data (or /out) across the restart.+# - The service exited cleanly (0: it dumped its episode on the collect hook's SIGUSR1 and released the simulator): keep+# the container up for the collect hook's fresh-process replays. If the service were PID 1 itself, that exit would+# stop the container and kill the hook with it (Harbor reports exit 137).+# - Everything the service prints also goes to $RCB_DATA/server.log (an artifact: Harbor keeps no sidecar output, and a+# simulator that dies while it loads leaves no other trace).+DATA="${RCB_DATA:-/data}"+mkdir -p "$DATA"+rm -f "$DATA/.service_rc"+{ python -u "${RCB_SERVER:-/srv/server.py}" 2>&1; echo "$?" > "$DATA/.service_rc"; } | tee -a "$DATA/server.log"+rc="$(cat "$DATA/.service_rc" 2>/dev/null)"; rc="${rc:-1}"+if [ "$rc" != 0 ]; then+ echo "[sim] service exited ($rc): leaving, so compose restarts the container (the service resumes the episode if one began)" | tee -a "$DATA/server.log"+ exit "$rc"+fi+echo "[sim] service exited (0); holding the container open for the collect hook" | tee -a "$DATA/server.log"+while true; do sleep 3600; donediff --git a/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/server.py b/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/server.pynew file mode 100644index 0000000000..b0c774b183--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/environment/sim/server.py@@ -0,0 +1,478 @@+"""eai-standard/2.2 sim service for MuJoCo Playground's quadruped tasks (docs/STANDARD_MODE_2_2.md): the adapter of the+shared layer rcb_limited.py; the simulator is rcb_quadruped.Session (plain MuJoCo on the CPU).+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to+/data/episode.jsonl.++The episode is the frozen instance's: one control step = 1/50 s. A joystick episode ends after the whole command schedule+(the horizon), when the robot meets Playground's termination rule (it falls over: a failure), when the agent submits+`done`, or when its time is over; success = the task's check on the steps executed. A getup episode ends the moment the+check holds (success), after the horizon, on `done` or on timeout.++Crash recovery (rcb_limited.Episode, resume class `exact`: MuJoCo on the CPU repeats bit for bit in a fresh process):+every executed row is journaled; after a crash the service rebuilds the episode and replays the journal. When the+episode ends the service writes /data/trajectory.npz + /data/episode.json; the collect hook (finalize.sh) makes it exit+and replays the trajectory in two fresh processes."""++import math+import os+import sys+import threading+import time+import traceback++import numpy as np++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import rcb_limited as L # noqa: E402++DATA = os.environ.get("RCB_DATA", "/data")+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.json"))+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "3600"))+MAX_CHUNK_S = float(os.environ.get("RCB_MAX_CHUNK_S", "10"))+MAX_WATCH_S = float(os.environ.get("RCB_MAX_WATCH_S", "30"))+CAM_W, CAM_H = 320, 240+LOCK = threading.Lock()+PID_FILE = os.path.join(DATA, "server.pid")+E = {"ready": False, "step": 0, "calls": 0, "done": False, "reason": None, "success": False, "t0": time.time(), "error": None}++os.environ["RCB_SESSION_LOG"] = ""+os.environ["RCB_AGENT_TRACE_DIR"] = ""+import rcb_quadruped as Q # noqa: E402 (first: it picks the rendering backend before mujoco loads)+import mujoco # noqa: E402++EP = L.Episode(DATA, dim=Q.N, resume="exact")+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()+S = Q.Session(INSTANCE)+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz+DT = S.control_dt # one control step of simulated time (Barkour: 10 ms, as Playground steps it)+CTRL_HZ = 1.0 / DT+SUBSTEPS = S.substeps+M = S.model+CAMS = list(S.cameras)+FEET = S.robot["feet"]+LIMITS = np.stack([S.lower, S.upper], axis=1)+GROUPS = [+ ("joint_pos", S.joint_names, "measured joint positions (rad), in the action's order"),+ ("joint_vel", [f"{j}_vel" for j in S.joint_names], "measured joint velocities (rad/s)"),+ ("joint_effort", [f"{j}_effort" for j in S.joint_names], "actuator torques of those joints (N m)"),+ ("gripper_opening", [], "none (no gripper)"),+ ("tcp_pose", [], "none (no gripper)"),+ ("imu_gyro", ["gyro_x", "gyro_y", "gyro_z"], "angular velocity of the trunk, IMU frame (rad/s)"),+ ("imu_accelerometer", ["acc_x", "acc_y", "acc_z"], "specific force at the IMU, IMU frame (m/s^2; +9.81 up at rest)"),+ ("imu_gravity", ["gravity_x", "gravity_y", "gravity_z"], "unit vector of gravity's direction in the IMU frame "+ "([0, 0, -1] when the trunk is level)"),+ ("imu_linvel", ["linvel_x", "linvel_y", "linvel_z"], "linear velocity of the trunk at the IMU, IMU frame (m/s; the "+ "IMU's velocimeter, what a state estimator gives)"),+ ("foot_contact", [f"{f}_contact" for f in FEET], "1 when the foot touches the ground, else 0"),+]+PROPRIO_LAYOUT = [n for _, names, _ in GROUPS for n in names]+PROPRIO_GROUPS, _i = {}, 0+for _g, _names, _meaning in GROUPS:+ PROPRIO_GROUPS[_g] = [_i, len(_names), _meaning]+ _i += len(_names)+++# ------------------------------------------------------------------------------------------------- cameras+def _intrinsic(cam: str) -> list:+ fovy = math.radians(float(M.cam_fovy[M.camera(cam).id]))+ f = 0.5 * CAM_H / math.tan(fovy / 2)+ return [[f, 0.0, CAM_W / 2], [0.0, f, CAM_H / 2], [0.0, 0.0, 1.0]]+++def camera_info(cam: str) -> dict:+ """World -> camera (OpenCV axes) and camera -> world (OpenGL axes) at the current state."""+ i = M.camera(cam).id+ R_gl = S.data.cam_xmat[i].reshape(3, 3) # camera axes (OpenGL: x right, y up, z back) in the world+ p = S.data.cam_xpos[i].copy()+ R_cv = R_gl @ np.diag([1.0, -1.0, -1.0])+ ext = np.zeros((3, 4))+ ext[:, :3] = R_cv.T+ ext[:, 3] = -R_cv.T @ p+ c2w = np.eye(4)+ c2w[:3, :3] = R_gl+ c2w[:3, 3] = p+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": ext.tolist(), "cam2world_gl": c2w.tolist(),+ "image_size": [CAM_W, CAM_H]}+++# ------------------------------------------------------------------------------------------------- kinematics+KD = mujoco.MjData(M) # kinematics only: the trunk at the origin, level; never stepped+_FOOT = {f: M.site(f).id for f in FEET}+_LEG_DOF = {f: [6 + 3 * k + j for j in range(3)] for k, f in enumerate(FEET)} # actuator order = leg order = FEET+++def _fk_kd(q) -> None:+ KD.qpos[:] = 0.0+ KD.qpos[3] = 1.0+ KD.qpos[7:] = q+ mujoco.mj_kinematics(M, KD)+++def _foot_pose(f: str) -> list:+ quat = np.zeros(4)+ mujoco.mju_mat2Quat(quat, KD.site_xmat[_FOOT[f]])+ return [*KD.site_xpos[_FOOT[f]].tolist(), *quat.tolist()]+++def do_kinematics(req: dict) -> dict:+ """Feet in the trunk frame (the trunk body's origin and axes; x forward, y left, z up). IK solves positions only, one+ leg (3 joints) per foot target, damped least squares within the joint ranges; a foot's orientation is ignored."""+ if req["op"] == "fk":+ _fk_kd(np.asarray(req["q"]))+ return L.fk_response({f: _foot_pose(f) for f in req["links"]}, "trunk")+ q = np.array(req["seed"] if req["seed"] is not None else S.data.qpos[7:], dtype=np.float64)+ errors = {}+ jac = np.zeros((3, M.nv))+ for f, pose in req["targets"].items():+ tgt = np.asarray(pose[:3])+ idx = _LEG_DOF[f]+ for _ in range(req["max_iters"]):+ _fk_kd(q)+ err = tgt - KD.site_xpos[_FOOT[f]]+ if np.linalg.norm(err) < req["tol_pos_m"]:+ break+ mujoco.mj_jacSite(M, KD, jac, None, _FOOT[f])+ J = jac[:, idx]+ dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(3), err)+ q[[i - 6 for i in idx]] = np.clip(q[[i - 6 for i in idx]] + dq, S.lower[[i - 6 for i in idx]],+ S.upper[[i - 6 for i in idx]])+ _fk_kd(q)+ errors[f] = (float(np.linalg.norm(tgt - KD.site_xpos[_FOOT[f]])), 0.0)+ ok = all(e[0] <= req["tol_pos_m"] for e in errors.values())+ return L.ik_response(q, ok, errors, "trunk", note="feet: position only (a foot is a sphere; its orientation is ignored)")+++# ------------------------------------------------------------------------------------------------- spec+def schedule_text() -> list:+ if S.commands is None:+ return []+ return [{"from_s": round(int(c["start_step"]) * DT, 2), "vx_mps": round(c["vx"], 4), "vy_mps": round(c["vy"], 4),+ "wz_radps": round(c["wz"], 4)} for c in S.inst["commands"]]+++TASK_EPISODE = {+ "joystick": f"one episode, no reset: it ends after {S.horizon} control steps (the {S.horizon * DT:g} s command "+ f"schedule), when the robot meets its termination rule ({S.spec.get('term_text')}: a failure), when you "+ "submit `done`, or when your time is over",+ "getup": f"one episode, no reset: it ends the moment the robot has stood upright for {Q.HOLD_STEPS} control steps in a "+ f"row (success), after {S.horizon} control steps, when you submit `done`, or when your time is over",+ "stand_on_two": f"one episode, no reset: it ends the moment the pose has been held for {Q.POSE_HOLD_STEPS} control steps "+ "in a row (success), when the robot meets the termination rule (a failure: its trunk's up axis below "+ f"-0.25, or {'a leg' if S.spec.get('hind_leg_contact') else 'a front leg'}'s thigh, calf or hip on the "+ f"floor), after {S.horizon} control steps, when you "+ "submit `done`, or when your time is over",+}[S.kind]+_ctl = {"type": "joint position actuators (PD)", "kp_nm_per_rad": float(M.actuator_gainprm[0, 0]),+ "kd_nms_per_rad": float(M.dof_damping[6] - M.actuator_biasprm[0, 2])}+SPEC = {+ "protocol": L.PROTOCOL,+ "protocol_compat": list(L.COMPAT),+ "simulator": "MuJoCo 3.3.7 (MuJoCo Playground's scene, plain MuJoCo on the CPU)",+ "robot": S.robot["name"],+ "task_text": S.inst["text"],+ "control_hz": CTRL_HZ,+ "physics_substeps": SUBSTEPS,+ "max_chunk_s": MAX_CHUNK_S,+ "max_watch_s": MAX_WATCH_S,+ "cameras": {c: {"rgb": True, "depth": True, "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),+ **({"mounted": "follows the robot", "mount": {"type": "link", "link": S.robot["root"], "note":+ "follows the robot's centre of mass at a fixed offset; it does not turn with the robot"}}+ if int(M.cam_mode[M.camera(c).id]) != 0 else+ {"mounted": "on the robot's head", "mount": {"type": "link", "link": M.body(M.cam_bodyid[M.camera(c).id]).name+ or S.robot["root"], "note": "fixed to the robot: moves and turns with it"}})}+ for c in CAMS},+ "default_cameras": ["track"],+ "action_types": {+ "joint_position": {+ "dim": Q.N,+ "layout": S.joint_names,+ "limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "units": "rad",+ "semantics": "absolute targets of the 12 joint position actuators, one per control step (1/50 s); rows `dt` "+ "apart (a multiple of the control period, at most 0.5 s), `hold` or `linear` between rows; values "+ "outside the limits are clipped and reported",+ },+ "done": {"dim": 0, "layout": [], "semantics": 'ends the episode now, in the current state (no physics); r.submit("done", [])'},+ "not_yet": ["joint_velocity", "joint_torque", "joint_delta"],+ },+ "proprio_layout": PROPRIO_LAYOUT,+ "proprio_groups": PROPRIO_GROUPS,+ "static": {},+ "world": {"frame": "z up; the robot starts where the episode puts it (no world coordinates are given)", "up": "+z",+ "units": {"length": "m", "angle": "rad", "time": "s"}, "quaternion_order": "wxyz",+ "camera_axes": "intrinsic_cv / extrinsic_cv: OpenCV camera axes (x right, y down, z forward); cam2world_gl: OpenGL axes"},+ "budget": {"reset": 0, "steps": None, "wall_clock_s": WALL_CLOCK_S},+ "max_control_steps": S.horizon,+ "episode": TASK_EPISODE,+ "command_schedule": schedule_text(),+ **({"gait": {k: S.gait[k] for k in ("name", "frequency_hz", "foot_height_m", "phase0", "phase_dt")} | {+ "feet": FEET, "rule": "foot i's target height at control step t is get_rz(wrap(phase0[i] + t * phase_dt)) with "+ "Playground's gait.get_rz (a cubic Bezier from 0 up to foot_height_m over the first half of the phase, then "+ "down); phases in rad, wrapped to [-pi, pi)"}} if S.gait else {}),+ "robot_spec": {"name": S.robot["name"], "joints": S.joint_names, "joint_limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "joint_order": S.robot["joint_text"], "home_pose": dict(zip(S.joint_names, S.home.tolist())),+ "feet": FEET, "controller": _ctl},+ "kinematics": {"endpoint": "/kinematics", "joint_names": S.joint_names, "frame": "trunk", "quaternion_order": "wxyz",+ "links": FEET, "tcp_frames": [], "ee_frames": FEET, "ik_targets": FEET,+ "ik": {"tol_pos_m": 0.002, "tol_rot_rad": 3.2, "max_iters": 100},+ "note": "poses of the feet in the trunk frame (x forward, y left, z up, metres) for joint positions q; "+ "ik: one leg per foot, positions only"},+ "depth": {"modes": list(L.DEPTH_MODES), "default": "none", "kind": "z-depth", "unit": "m", "invalid": 0,+ "max_m": L.DEPTH_MAX_M, "frames_encoding": "uint16 mm, zlib", "noise": L.DEPTH_NOISE},+}+L.check_spec(SPEC) # a spec that misses a 2.2 field or names a forbidden one never starts the episode+EP.scene_built()++_RENDER = {}+++def _renderer():+ if "r" not in _RENDER:+ _RENDER["r"] = mujoco.Renderer(M, CAM_H, CAM_W)+ return _RENDER["r"]+++def ctrl_steps() -> int:+ return S.steps+++def proprio_row() -> np.ndarray:+ d = S.data+ return np.concatenate([d.qpos[7:], d.qvel[6:], d.actuator_force, S.sensor("gyro"), S.sensor("accelerometer"), S.gravity(),+ S.sensor("local_linvel"), S.foot_contacts()]).astype(np.float32)+++def grab(cams, want_depth: bool):+ r = _renderer()+ rgb, dep = {}, {}+ for c in cams:+ r.update_scene(S.data, camera=c)+ rgb[c] = r.render().copy()+ if want_depth:+ r.enable_depth_rendering()+ r.update_scene(S.data, camera=c)+ dep[c] = r.render().astype(np.float32).copy()+ r.disable_depth_rendering()+ return rgb, dep+++def extrinsics(cams) -> dict:+ return {c: np.asarray(camera_info(c)["extrinsic_cv"], dtype=np.float64) for c in cams}+++def write_final() -> None:+ if L.final_verdict(DATA): # finalize.sh's verdict, or a give-up after crashes: never overwritten+ return+ L._write_json(os.path.join(DATA, "final.json"), {**summary(), "finalized": False, "live_sha": E.get("live_sha")})+++def summary() -> dict:+ n = int(E.get("episode_control_steps") or ctrl_steps())+ chk = E.get("check") or {}+ return {"success": bool(E["success"]), "steps": E["step"], "calls": E["calls"], "control_steps": n,+ "physics_steps": n * SUBSTEPS, "elapsed_s": round((E.get("t_end") or time.time()) - E["t0"], 1),+ "reason": E["reason"], "done": E["done"], "env": S.env, "protocol": L.PROTOCOL, "n_actions": len(ROWS),+ "fell_at": chk.get("fell_at"), "worst_lin_err": chk.get("worst_lin_err"), "worst_yaw_err": chk.get("worst_yaw_err"),+ "tilt_deg": chk.get("tilt_deg"), "imu_height": chk.get("imu_height"), "pose_angle_deg": chk.get("pose_angle_deg"),+ **EP.final_fields()}+++def finish(reason: str) -> None:+ """The episode is over: the task's check on the steps executed, then the record for the collect hook."""+ if E["done"]:+ return+ E["done"] = True+ E["reason"] = reason+ E["t_end"] = time.time()+ E["episode_control_steps"] = ctrl_steps()+ try:+ chk = S.check()+ E["check"] = {k: v for k, v in chk.items() if k != "segments"}+ E["success"] = bool(chk["success"])+ except Exception: # noqa: BLE001+ traceback.print_exc()+ EP.log({"ev": "end", "reason": reason, "step": E["step"], "control_steps": ctrl_steps(), "success": bool(E["success"])})+ dump()+++def dump() -> None:+ if E.get("dumped"):+ return+ E["dumped"] = True+ E["live_sha"] = S.state_sha()+ np.savez(os.path.join(DATA, "trajectory.npz"), actions=np.asarray(ROWS, dtype=np.float64).reshape(-1, Q.N),+ env=S.env, action_layout=",".join(S.joint_names))+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})+ write_final()+++def after_step() -> None:+ if S.kind in ("joystick", "stand_on_two") and S.fell_at is not None:+ finish("fell")+ elif S.kind in ("getup", "stand_on_two") and S.check()["success"]:+ finish("success")+ elif S.done:+ finish("horizon")+++def ctrl_step(a, rec) -> bool:+ """One executed control step, journaled. True when the call must stop here."""+ S.step(a)+ ROWS.append(np.asarray(a, dtype=np.float64))+ stop = EP.journal(a)+ rec.tick()+ after_step()+ return E["done"] or stop+++def recorder(cams, fps: int, meta: dict) -> L.Recorder:+ return L.Recorder(cams, max(1, int(round(CTRL_HZ / max(1, fps)))), grab, proprio_row, extrinsics, ctrl_steps,+ depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+++def video_fps(meta: dict) -> int:+ fps = meta.get("video_fps")+ if fps is None:+ return 10+ if isinstance(fps, bool) or not isinstance(fps, (int, float)) or not (1 <= fps <= 50):+ raise ValueError("video_fps must be in [1, 50]")+ return int(fps)+++def cameras_of(meta: dict) -> list:+ cams = meta.get("cameras") or ["track"]+ bad = [c for c in cams if c not in CAMS]+ if bad:+ raise ValueError(f"unknown cameras {bad}; cameras: {CAMS}")+ return list(cams)+++def meta_common(cams) -> dict:+ n = ctrl_steps()+ out = {"step": E["step"], "calls": E["calls"], "control_steps": n, "physics_steps": n * SUBSTEPS,+ "sim_time_s": round(n * DT, 3), "time_s": round(time.time() - E["t0"], 2),+ "time_left_s": max(0.0, round(WALL_CLOCK_S - (time.time() - E["t0"]), 1)),+ "proprio": {"layout": PROPRIO_LAYOUT, "now": proprio_row().tolist()}, "done": E["done"], "reason": E["reason"],+ "cameras": {c: camera_info(c) for c in cams}}+ if S.kind == "joystick":+ out["command_now"] = dict(zip(("vx_mps", "vy_mps", "wz_radps"), S.command_now().round(4).tolist()))+ return out+++def do_submit(meta: dict, A: np.ndarray):+ typ = meta.get("type")+ if typ == "done":+ rec = recorder(cameras_of(meta), 5, meta)+ rec.tick(force=True, last=True) # every response carries the last frames+ E["calls"] += 1+ finish("done")+ return {**meta_common(cameras_of(meta)), "chunk_id": E["calls"], "type": typ, "executed_rows": 0, "ok": True}, rec.parts("none", 5)+ if typ != "joint_position":+ raise ValueError(f"type must be joint_position or done (not yet: {SPEC['action_types']['not_yet']})")+ dt = float(meta.get("dt", DT))+ interp = meta.get("interpolate", "linear")+ video = meta.get("video", "mp4")+ cams, fps = cameras_of(meta), video_fps(meta)+ k = dt / DT+ if A.ndim != 2 or A.shape[1] != Q.N:+ raise ValueError(f"joint_position actions must be (T, {Q.N}), got {list(A.shape)}")+ if not np.all(np.isfinite(A)):+ raise ValueError("actions contain NaN/inf")+ if not (math.isfinite(dt) and dt <= 0.5 + 1e-9 and round(k) >= 1 and abs(k - round(k)) < 1e-6):+ raise ValueError(f"dt must be a whole multiple of the {DT:g} s control period and at most 0.5 s; got {dt}")+ if A.shape[0] * dt > MAX_CHUNK_S + 1e-9:+ raise ValueError(f"chunk longer than max_chunk_s={MAX_CHUNK_S}: {A.shape[0]} rows x {dt} s")+ if interp not in ("hold", "linear"):+ raise ValueError("interpolate must be hold|linear")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, clipped = recorder(cams, fps, meta), []+ E["calls"] += 1+ step0, before = E["step"], ctrl_steps()+ rec.tick(force=True)+ prev = S.targets.copy()+ for ri, row in enumerate(A):+ E["step"] += 1+ target = np.clip(row, LIMITS[:, 0], LIMITS[:, 1])+ for j in np.flatnonzero(target != row)[:20]:+ clipped.append({"row": ri, "index": int(j), "reason": f"{S.joint_names[j]} limit [{LIMITS[j, 0]:g}, {LIMITS[j, 1]:g}]"})+ n = int(round(k))+ stop = False+ for s in range(1, n + 1):+ a = target if interp == "hold" else prev + (target - prev) * (s / n)+ if ctrl_step(a, rec):+ stop = True+ break+ prev = target+ if stop:+ break+ rec.tick(force=True, last=True)+ out = {**meta_common(cams), "chunk_id": E["calls"], "type": typ, "executed_rows": E["step"] - step0,+ "control_steps_chunk": ctrl_steps() - before, "physics_steps_chunk": (ctrl_steps() - before) * SUBSTEPS,+ "clipped": clipped[:200], "n_clipped": len(clipped), "plan": [], "ok": True}+ EP.log({"ev": "submit", "call": E["calls"], "rows": E["step"] - step0, "dt": dt, "interpolate": interp, "cameras": cams,+ "control_steps": ctrl_steps() - before, "n_clipped": len(clipped), "note": (meta.get("note") or "")[:500],+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video, fps)+++def do_observe(meta: dict):+ cams, fps = cameras_of(meta), video_fps(meta)+ seconds = float(meta.get("seconds", 0))+ video = meta.get("video", "frames")+ if not math.isfinite(seconds) or seconds < 0 or seconds > MAX_WATCH_S:+ raise ValueError(f"seconds must be in [0, {MAX_WATCH_S}]")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, before = recorder(cams, fps, meta), ctrl_steps()+ if seconds > 0 and not E["done"]:+ rec.tick(force=True)+ hold = S.targets.copy()+ for _ in range(int(round(seconds / DT))):+ if ctrl_step(hold, rec):+ break+ rec.tick(force=True, last=True)+ E["calls"] += 1+ out = {**meta_common(cams), "obs_id": E["calls"], "seconds": seconds, "control_steps_watch": ctrl_steps() - before,+ "physics_steps_watch": (ctrl_steps() - before) * SUBSTEPS, "ok": True}+ EP.log({"ev": "observe", "call": E["calls"], "seconds": seconds, "cameras": cams, "control_steps": ctrl_steps() - before,+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video if seconds > 0 else ("frames" if video == "mp4" else video), fps)+++def status() -> dict:+ return {"step": E["step"], "calls": E["calls"], "control_steps": ctrl_steps(), "done": E["done"], "reason": E["reason"],+ "elapsed_s": round(time.time() - E["t0"], 1)}+++def end_from_signal() -> None:+ """The collect hook's SIGUSR1: end the episode (the agent's time is over), dump it, exit so the replays can start."""+ with LOCK:+ E["exiting"] = True+ if not E["done"]:+ finish("timeout")+ EP.log({"ev": "exit", "reason": "collect hook: episode dumped"})+ if not os.path.exists(PID_FILE):+ open(PID_FILE, "w").write(str(os.getpid()))+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(0)+++def replay_row(row) -> None:+ """A journaled row during a resume."""+ S.step(row)+ ROWS.append(np.asarray(row, dtype=np.float64))+++EP.begin(state=E, step=replay_row, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, on_end=end_from_signal,+ start_event={"env": S.env, "seed": S.inst.get("seed"), "cameras": CAMS})+if E["done"]:+ dump() # resumed after the episode had ended: the record is rewritten from the replay+E["ready"] = True+write_final()+open(PID_FILE, "w").write(str(os.getpid()))+print(f"{L.PROTOCOL} MuJoCo Playground quadruped sim ready ({S.env}; startup {EP.n_startups}, resumes {EP.resumes})", flush=True)+L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics, status=status,+ on_submit_error=lambda exc: finish("error"), log=EP.log, episode=EP, state_sha=S.state_sha,+ proprio=proprio_row), port=int(os.environ.get("RCB_PORT", "8000")))diff --git a/tasks/mujoco_playground_barkour_joystick-standard/instruction.md b/tasks/mujoco_playground_barkour_joystick-standard/instruction.mdnew file mode 100644index 0000000000..174fa002e8--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/instruction.md@@ -0,0 +1,56 @@+# MuJoCo Playground · BarkourJoystick — STANDARD MODE (robot as a service, eai-standard/2.2)++**Task:** Make Google's Barkour quadruped follow the joystick command schedule for the whole 10 s episode, through random pushes, without falling over.++You control the Google Barkour vB quadruped — **as if it were real hardware** — in one episode of MuJoCo Playground's+`BarkourJoystick` environment (plain MuJoCo 3.3.7 with Playground's scene, commit 4057c14). The simulator runs in a service you+cannot open. You get one client and one episode.++## The episode+The robot starts standing still at Playground's `home` pose (this environment's reset does not move it). The ground is flat. One control step is 10 ms of simulated time: Playground's Barkour environment keeps Menagerie's 2 ms timestep and takes 5 substeps.+For 10 s (1000 control steps) it is given this command schedule, drawn by Playground's command process (a new draw after 501 control steps). A command is a velocity in the robot's own frame: vx forward, vy to the left (the trunk's planar velocity), and the yaw rate:++| from (s) | vx (m/s) | vy (m/s) | yaw rate (rad/s) |+|---:|---:|---:|---:|+| 0.00 | +0.459 | +0.221 | +0.016 |+| 5.01 | +0.090 | -0.389 | +0.643 |++The torso is pushed 12 times at moments you are not told (Playground's kicks: half-sine pushes of up to 35 N lasting 0.05 s, in random horizontal directions).++The same schedule is `spec["command_schedule"]`; every response's `meta["command_now"]` is the current command.++## Rules (real-robot rules)+- **No reset.** One episode. You see four cameras that follow the robot (RGB, depth if you ask) and the robot's own+ sensors: joint positions, velocities and torques, the IMU (gyro, accelerometer, gravity's direction, the trunk's+ velocity), foot contacts. No world positions, no success check.+- **The episode ends** after 1000 control steps, the whole schedule (`spec["max_control_steps"]`, counted by `meta["control_steps"]`), when the robot meets its termination rule (the trunk's up axis pointing below the horizon, a joint outside its box (abduction [-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m: a failure), when you submit `done`, or when your time is up (before the end of the schedule, both are failures).+- **Success** is judged on the whole schedule: no termination, and in every command segment, after its first 25 control steps, a mean |v_xy - cmd_xy| of at most 0.2 m/s (`imu_linvel`) and a mean |w_z - cmd_wz| of at most 0.3 rad/s (`imu_gyro`).+- Your wall-clock budget is 3600 s from your start. Simulated time only advances with your commands (and+ `get_obs(seconds=...)`, which holds the current targets).+- Nothing to hand in: the service records the episode and grades it. Leave your script at `/app/output/gen.py`.+- **If the service crashes**, a call fails with a connection error: it restarts and resumes the SAME episode (never a+ reset) in the state after the last call it completed. `r.wait_ready()` waits for it; then check `r.status()`.+- Nothing is put into your context automatically: images come back as arrays in Python objects.++## Client (`/opt/tools/rcb_client.py`)+```python+from rcb_client import Robot+r = Robot() # connects (waits while the service starts)+spec = r.spec() # action types, limits, cameras, robot_spec (home pose, gains), kinematics, command_schedule+obs = r.get_obs() # obs.last[cam] -> uint8 (240, 320, 3); obs.meta["proprio"] {"layout", "now"}+res = r.submit("joint_position", A, dt=0.01) # A: (T, 12) rows dt apart; res.proprio (one row per frame), res.meta+obs = r.get_obs(seconds=1.0, video="mp4") # hold the current targets and watch for 1 s (max 30)+r.fk(q); r.ik({"foot_front_left": [x, y, z, 1, 0, 0, 0]}, seed=q) # feet in the trunk frame <-> joints (no physics)+r.submit("done", []) # end the episode now+r.status() # calls, control steps, done, reason, elapsed time+```+Cameras: `track` (follows the robot) and `realsense/rgb` (on its head); `spec["cameras"]` gives each one's mounting and intrinsics, and every response carries its pose. Proprioception (`spec["proprio_groups"]`): `joint_pos`, `joint_vel`, `joint_effort` (12 each, action+order), `imu_gyro`, `imu_accelerometer`, `imu_gravity`, `imu_linvel` (3 each, IMU frame: x forward, y left, z up),+`foot_contact` (foot_front_left, foot_hind_left, foot_front_right, foot_hind_right).++### `joint_position` (12)+front-left, hind-left, front-right, hind-right legs, each abduction, hip, knee: absolute targets of the joint position actuators (rad; kp = 35 N m/rad, joint damping 0.5239 N m s/rad, plus the actuators' own damping of 0.5 N m s/rad).+Rows are `dt` apart (a whole multiple of the 0.01 s control period, at most 0.5 s), `interpolate="linear"` (default) or+`"hold"` between rows; a chunk covers at most 10 s; values outside the limits+(`spec["action_types"]["joint_position"]["limits"]`) are clipped and listed in `res.meta["clipped"]`. Feedback control+means short chunks: each response tells you where the robot is now.diff --git a/tasks/mujoco_playground_barkour_joystick-standard/solution/oracle.npy b/tasks/mujoco_playground_barkour_joystick-standard/solution/oracle.npynew file mode 100644index 0000000000..56910d0997Binary files /dev/null and b/tasks/mujoco_playground_barkour_joystick-standard/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_barkour_joystick-standard/solution/oracle_replay.py b/tasks/mujoco_playground_barkour_joystick-standard/solution/oracle_replay.pynew file mode 100644index 0000000000..b6a9824592--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/solution/oracle_replay.py@@ -0,0 +1,42 @@+"""Oracle (standard mode): streams the reference rows (one per 1/50 s control step, `hold`) as `joint_position` chunks+through the client, the same interface an agent has. Uses no privileged information at run time; the service's recorded+trajectory is then exactly the privileged reference. If the service crashes it resumes the same episode+(spec["on_service_error"]): the oracle waits until it answers again and goes on from the control step it reports."""+import os+import sys+import time++import numpy as np+import requests++sys.path.insert(0, "/opt/tools")+from rcb_client import EpisodeOver, Robot # noqa: E402++Q = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy")).astype(np.float64)+r = Robot()+spec = r.spec()+dt = 1.0 / float(spec["control_hz"])+per_chunk = max(1, int(spec.get("max_chunk_s", 10) / dt + 1e-9))+print("spec:", spec["protocol"], "rows:", len(Q), flush=True)+t0, i = time.time(), 0+while i < len(Q):+ chunk = Q[i:i + per_chunk]+ try:+ res = r.submit("joint_position", chunk, dt=dt, interpolate="hold", cameras=["track"], video="none", note=f"oracle rows {i}+")+ except EpisodeOver as e:+ print("episode over:", e)+ break+ except requests.exceptions.RequestException as e: # the service crashed: it restarts and resumes the same episode+ print("service unreachable:", repr(e)[:200], "- waiting for it to resume", flush=True)+ st = r.wait_ready()+ n = int(st["control_steps"])+ if not i <= n <= i + len(chunk):+ raise SystemExit(f"resumed at control step {n}: outside the chunk in flight (rows {i}..{i + len(chunk)})")+ i = n+ continue+ n = int(res.meta["control_steps"])+ print(f"rows {i}..{n}: clipped={res.meta['n_clipped']} done={res.meta['done']} reason={res.meta['reason']}", flush=True)+ if res.meta["done"] or n <= i:+ break+ i = n+print("status:", r.status(), "wall %.0fs" % (time.time() - t0))diff --git a/tasks/mujoco_playground_barkour_joystick-standard/solution/solve.sh b/tasks/mujoco_playground_barkour_joystick-standard/solution/solve.shnew file mode 100755index 0000000000..ecb1f6c954--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/solution/solve.sh@@ -0,0 +1,8 @@+#!/bin/bash+# Oracle (standard mode): streams the reference trajectory's joint targets (solution/oracle.npy, one row per control step)+# as `joint_position` chunks through the client. Uses no privileged information at run time (only the pre-recorded+# targets); the service's recorded trajectory is then exactly the privileged reference.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_barkour_joystick-standard/task.toml b/tasks/mujoco_playground_barkour_joystick-standard/task.tomlnew file mode 100644index 0000000000..65629dd7ce--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/task.toml@@ -0,0 +1,54 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = [+ { source = "/data/final.json", service = "sim" },+ { source = "/data/episode.jsonl", service = "sim" },+ { source = "/data/trajectory.npz", service = "sim" },+ { source = "/data/replay.mp4", service = "sim" },+ { source = "/data/server.log", service = "sim" }, # the service's own output (Harbor keeps none)+ { source = "/data/journal.f64", service = "sim" }, # crash recovery: every executed control step (float64 rows)+ { source = "/data/startups.jsonl", service = "sim" }, # crash recovery: one line per service start+ { source = "/data/replay1.log", service = "sim" }, # the collect hook's two fresh-process replays+ { source = "/data/replay2.log", service = "sim" },+ { source = "/data/replay3.log", service = "sim" }, # and its third, which renders replay.mp4+ "/app/output/",+]++[task]+name = "robot-coding-bench/mujoco_playground_barkour_joystick-standard"+description = "STANDARD MODE (robot as a service, eai-standard/2.2): MuJoCo Playground BarkourJoystick (Google Barkour vB) on the same frozen instance as mujoco_playground_barkour_joystick-privileged: Make Google's Barkour quadruped follow the joystick command schedule for the whole 10 s episode, through random pushes, without falling over. The agent only gets a client: four cameras that follow the robot (RGB, optional depth), the robot's joints and IMU, joint position chunks at 50 Hz, the feet's kinematics; one episode, no reset, no world state; the sim service records the episode, replays it in fresh processes and grades it."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "google-barkour-vb", "quadruped", "locomotion", "joystick", "code-as-policy", "trajectory", "standard-mode"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "google-barkour-vb"+family = "mujoco_playground/BarkourJoystick"+mode = "standard"+protocol = "eai-standard/2.2"+oracle = "full"+instance_seed = 2+expert_time_estimate_hours = 4.0++[verifier]+timeout_sec = 600.0+environment_mode = "separate"+network_mode = "no-network"++[[verifier.collect]]+service = "sim"+command = "sh /srv/finalize.sh" # end + dump + exit the service, replay twice in fresh processes, write final.json, video+timeout_sec = 1200++[agent]+timeout_sec = 3600.0+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_barkour_joystick-standard/tests/Dockerfile b/tasks/mujoco_playground_barkour_joystick-standard/tests/Dockerfilenew file mode 100644index 0000000000..26bc699ebe--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/tests/Dockerfile@@ -0,0 +1,5 @@+# Separate verifier sandbox: grades the sim service's own artifacts; needs nothing but python (the shared client base).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY test.sh /tests/test.sh+COPY grade.py /tests/grade.py+RUN chmod +x /tests/test.shdiff --git a/tasks/mujoco_playground_barkour_joystick-standard/tests/grade.py b/tasks/mujoco_playground_barkour_joystick-standard/tests/grade.pynew file mode 100644index 0000000000..5b990bf458--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/tests/grade.py@@ -0,0 +1,64 @@+"""Standard-mode verifier (MuJoCo Playground quadrupeds): reads what the sim service (which the agent could not touch) wrote:+/data/final.json (live success, two fresh-process replays of the recorded trajectory, determinism, crash-recovery+fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, the+replays having started in the instance's t = 0 state. Numeric-only reward.json."""++import json, os, shutil++LOG = "/logs/verifier"+os.makedirs(LOG, exist_ok=True)+++def write(ok, out):+ open(f"{LOG}/reward.txt", "w").write("1\n" if ok else "0\n")+ json.dump(out, open(f"{LOG}/reward.json", "w"))+ print(out)+++p = "/data/final.json"+if not os.path.exists(p):+ write(False, {"success": 0, "missing_log": 1, "grader_error": 0, "infra_error": 0})+ raise SystemExit+d = json.load(open(p))+for f in ("replay.mp4", "trajectory.npz", "episode.jsonl"):+ if os.path.exists(f"/data/{f}"):+ shutil.copy(f"/data/{f}", f"{LOG}/{f}")+ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic"))+ok = ok and not d.get("instance_mismatch")+num = lambda k: float(d.get(k) or 0) # noqa: E731+write(+ ok,+ {+ "success": int(ok),+ "live_success": int(bool(d.get("success"))),+ "replay_success": int(bool(d.get("replay_success"))),+ "deterministic": int(bool(d.get("deterministic"))),+ "live_matches_replay": int(bool(d.get("live_matches_replay"))),+ "finalized": int(bool(d.get("finalized"))),+ "n_actions": int(d.get("n_actions") or 0),+ "sim_steps": int(d.get("control_steps") or 0),+ "physics_steps": int(d.get("physics_steps") or 0),+ "steps": int(d.get("steps") or 0),+ "elapsed_s": float(d.get("elapsed_s") or 0),+ "video_rendered": int(bool(d.get("video"))),+ "fell": int(d.get("fell_at") is not None),+ "worst_lin_err": float(d["worst_lin_err"]) if d.get("worst_lin_err") is not None else -1.0,+ "worst_yaw_err": float(d["worst_yaw_err"]) if d.get("worst_yaw_err") is not None else -1.0,+ "end_tilt_deg": float(d["tilt_deg"]) if d.get("tilt_deg") is not None else -1.0,+ "end_imu_height": float(d["imu_height"]) if d.get("imu_height") is not None else -1.0,+ "end_pose_angle_deg": float(d["pose_angle_deg"]) if d.get("pose_angle_deg") is not None else -1.0,+ # a replay process gave no result, or the image no longer builds the frozen start: not the agent's 0+ "grader_error": int(bool(d.get("replay_failed") or d.get("instance_mismatch"))),+ "instance_mismatch": int(bool(d.get("instance_mismatch"))),+ # an infrastructure failure, not the agent's (PROTOCOL §2.6): a give-up after crashes between calls or a failed+ # resume (docs/STANDARD_MODE_2_2.md §13), the service not ending its episode for the collect hook, a replay+ # process that gave no result, replays that did not start in the instance's t = 0 state+ "infra_error": int(bool(d.get("infra_error"))),+ "gave_up": int(bool(d.get("gave_up"))),+ "sim_error": int(d.get("reason") == "error"),+ "sim_startups": int(d.get("sim_startups") or 0),+ "resumes": int(d.get("resumes") or 0),+ "resume_state_mismatch": int(d.get("resume_state_mismatch") or 0),+ "resume_max_joint_dev": num("resume_max_joint_dev"),+ },+)diff --git a/tasks/mujoco_playground_barkour_joystick-standard/tests/test.sh b/tasks/mujoco_playground_barkour_joystick-standard/tests/test.shnew file mode 100755index 0000000000..bc608aa8b9--- /dev/null+++ b/tasks/mujoco_playground_barkour_joystick-standard/tests/test.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Verifier (separate sandbox): the sim sidecar's artifacts were uploaded to /data by Harbor.+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)+mkdir -p /logs/verifier+python /tests/grade.py 2> /logs/verifier/grade.logdiff --git a/tasks/mujoco_playground_go1_footstand-privileged/README.md b/tasks/mujoco_playground_go1_footstand-privileged/README.mdnew file mode 100644index 0000000000..64850627ba--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-privileged/README.md@@ -0,0 +1,42 @@+# mujoco_playground_go1_footstand-privileged++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | privileged |+| Twin | `mujoco_playground_go1_footstand-standard` |+| Simulator / robot | `mujoco` / `unitree-go1` |+| Family / instance | `mujoco_playground/Go1Footstand` / seed 0 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `Go1Footstand` (Unitree Go1), rebuilt in plain MuJoCo from Playground's scene files: Make the Unitree Go1 stand up on its hind legs, nose up, front legs in the air, and balance there for 2 s.+From standing, it has 10 s to get into a footstand on its hind legs and hold it for 2 s (Playground's footstand reward aims at the IMU 0.53 m high). The deliverable is one replayable trajectory of joint position targets+(`/app/output/trajectory.npz`, `(T, 12)`, 1 <= T <= 500).++## Difficulty+Dynamic balance on two legs: the robot has to throw its weight onto its hind legs, lift the other pair and then balance an inverted, top-heavy body on two small feet with 35 N m/rad position drives, correcting continuously; a front leg touching the floor or a tip-over ends it. Playground's footstand is trained with 100 M steps of PPO.++## Reference solution+A policy trained here on Playground's Go1Footstand reward (PPO on the CPU, `scripts/mujoco-playground/train/`, not in the image) with three training-only changes (`train/qenv.py` Go1FootstandStrict3): this task's hind-leg termination (with Playground's rule alone it learns to sit on a hind hip), half of the episodes starting in Playground's `footstand` keyframe, and a steeper height reward (with Playground's it settles in a squat at 0.2 m), run closed loop with Playground's action semantics (targets accumulate) until the hold completes (`scripts/mujoco-playground/oracle.py`): 113 control steps, pose angle 9.6 deg and IMU at 0.541 m at the end. Replayed by `solution/solve.sh` (`solution/oracle.npy`, 113 rows); the rows are float32-exact, so the+standard twin's client executes the same targets. Re-verified by `scripts/mujoco-playground/select_instances.py`: two+fresh-process replays succeed and end in the same state.++## Verification+`tests/grade.py` in a separate sandbox without network: two replays, each in a fresh process, from the verifier's own+copy of the instance (`tests/instance.json`; the start state is checked against its hash on every load); pass iff both+succeed and end in the same state (`deterministic`). Oracle: success after 113 control steps. `nop`: no trajectory, reward 0.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `locomotion/go1/xmls/scene_mjx_flat_terrain.xml`; MuJoCo Menagerie @ 1b86ece (`unitree_go1`); simulated in MuJoCo 3.3.7 on the CPU |+| Instance | Playground's `reset` with `jax.random.PRNGKey(0)` (xy, yaw and base velocity); chosen by `scripts/mujoco-playground/select_instances.py` (seed 0; the first candidate) |+| Actions | 12 joint position targets per control step (0.02 s of simulated time); kp = 35 N m/rad, joint damping 0.5 N m s/rad |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py` from `scripts/mujoco-playground/instances/Go1Footstand.json`+(`make_instances.py`, `select_instances.py`) and `scripts/mujoco-playground/oracles/Go1Footstand.npy` (`oracle.py`).diff --git a/tasks/mujoco_playground_go1_footstand-privileged/environment/Dockerfile b/tasks/mujoco_playground_go1_footstand-privileged/environment/Dockerfilenew file mode 100644index 0000000000..7bdd7d2938--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-privileged/environment/Dockerfile@@ -0,0 +1,8 @@+# MuJoCo Playground quadruped task (privileged): plain MuJoCo with Playground's and Menagerie's assets+# (images/mujoco/prepare_assets.sh), the task's tooling and its frozen instance.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY instance.json /app/instance.json+COPY rcb_quadruped.py /opt/tools/rcb_quadruped.py+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_go1_footstand-privileged/environment/instance.json b/tasks/mujoco_playground_go1_footstand-privileged/environment/instance.jsonnew file mode 100644index 0000000000..51305c694d--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-privileged/environment/instance.json@@ -0,0 +1,68 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1Footstand",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ -0.3957096338272095,+ -0.1560124158859253,+ 0.27799999713897705,+ 0.2572470009326935,+ 0.0,+ 0.0,+ -0.9663457870483398,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842+ ],+ "qvel0": [+ -0.4893399477005005,+ 0.021045565605163574,+ 0.45396435260772705,+ -0.16251015663146973,+ -0.030068635940551758,+ -0.1645064353942871,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "text": "Make the Unitree Go1 stand up on its hind legs, nose up, front legs in the air, and balance there for 2 s.",+ "facts": {+ "start_xy_m": [+ -0.396,+ -0.156+ ],+ "start_yaw_deg": -150.2,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.272,+ "reference_rows": 113,+ "torso_mass_kg": 12.743,+ "reference_imu_height": 0.5408,+ "reference_pose_angle_deg": 9.62+ },+ "state_sha": "edd665f20ded",+ "horizon": 500,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s), when its pushes (Barkour) are null or\n weak (peak under 20% of the torso's weight), or when the reference trajectory (oracle.py) fails the task's\n success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_go1_footstand-privileged/environment/rcb_quadruped.py b/tasks/mujoco_playground_go1_footstand-privileged/environment/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-privileged/environment/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_go1_footstand-privileged/instruction.md b/tasks/mujoco_playground_go1_footstand-privileged/instruction.mdnew file mode 100644index 0000000000..ed13925954--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-privileged/instruction.md@@ -0,0 +1,48 @@+# MuJoCo Playground · Go1Footstand — frozen episode++**Task:** Make the Unitree Go1 stand up on its hind legs, nose up, front legs in the air, and balance there for 2 s.++You control the Unitree Go1 quadruped in one episode of MuJoCo Playground's `Go1Footstand` environment, rebuilt in plain+MuJoCo 3.3.7 from Playground's own scene files (Apache-2.0, commit 4057c14) and the robot from MuJoCo Menagerie. The+episode is frozen: it starts the same way after every reset (Playground's `reset` with seed 0), and you may reset+as often as you like. Your deliverable is **one open-loop trajectory**, not a general policy.++## The episode+The robot starts at Playground's `home` pose, its base moved to (-0.396, -0.156) m, turned to a yaw of -150.2 deg, with a random base velocity (Playground's reset). You have 500 control steps (10 s).++## Success+Success iff the trajectory (at most 500 rows) ends with 100 control steps in a row (2 s) after each of which the trunk's forward axis (the IMU frame's x axis) is within 30 deg of straight up, the IMU is at least 0.4 m above the floor and the front (FR, FL) feet are off the ground; and no control step before its end meets Playground's termination rule: the trunk's up axis below -0.25 (z component of the IMU frame's z axis), or any part of a front leg other than its foot (thigh, calf, hip) touching the floor (Playground's rule as its code reads it), or the same for a hind leg (the list its Footstand sets up but never reads; without it, sitting on a hind hip would count). End the trajectory once the hold is complete. `s.check()` reports `fell_at`, the last pose angle and height, and `success`.++## Deliverable+`/app/output/trajectory.npz` with `actions`: float64 (T, 12), one row per control step (0.02 s): absolute targets of+the 12 joint position actuators, in `s.joint_names` order (FR, FL, RR, RL legs, each hip (abduction), thigh (hip pitch), calf (knee)), in radians; 1 <= T <= 500. Values+outside the actuator ranges (`s.lower`, `s.upper`) are clipped. `s.save_trajectory(rows)` writes it. Also leave the+script that produced it at `/app/output/gen.py`. Save a working trajectory as soon as you have one and overwrite it as+you improve it: whatever is in `/app/output/` when your 3600 s are up is graded. The tooling logs your sessions and+resets (cost accounting, not graded).++## Tooling (installed; `python` from any directory)+```python+from rcb_quadruped import Session+s = Session("/app/instance.json") # the frozen episode at t = 0 (checked against the instance's state hash)+s.joint_names; s.lower; s.upper # the actuator order and ranges (rad)+s.home # Playground's standing pose (its `home` keyframe), in that order+s.step(row) # one control step: 12 joint targets, 5 physics steps of 0.004 s; returns s.check()+s.check() # the task's check on the steps so far (see Success)+s.state() # qpos, qvel, IMU (local_linvel, gyro, gravity, accelerometer, pose), feet, contacts+s.sensor(name); s.gravity() # one MuJoCo sensor; gravity's direction in the IMU frame+s.model, s.data # the live MuJoCo model and data (read them; changing them is not part of the replay)+s.render(cam); s.cameras # uint8 (240, 320, 3) from cameras that follow the robot: `track`, `side`, `back`, `top` (they follow the robot)+s.reset() # back to t = 0+s.replay(rows) # reset, run the rows, return the check and the final state's hash+s.render_video(rows, "/app/output/try.mp4")+s.save_trajectory(rows, "/app/output/trajectory.npz")+```+The grader runs exactly this CLI in two fresh processes, so run it to check yourself:+`python /opt/tools/rcb_quadruped.py replay --instance /app/instance.json --traj /app/output/trajectory.npz`++## Conventions+- Joint position actuators (PD): kp = 35 N m/rad, joint damping 0.5 N m s/rad, as Playground's environment sets them; the physics step is 0.004 s,+ the control step 0.02 s (5 physics steps); a row holds until the next one.+- World frame z up, metres; quaternions **wxyz**. The IMU frame is the trunk's: x forward, y left, z up.+- Physics is MuJoCo on the CPU: the same rows from the same start give the same result in every fresh process.diff --git a/tasks/mujoco_playground_go1_footstand-privileged/solution/oracle.npy b/tasks/mujoco_playground_go1_footstand-privileged/solution/oracle.npynew file mode 100644index 0000000000..32569d8ff9Binary files /dev/null and b/tasks/mujoco_playground_go1_footstand-privileged/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_go1_footstand-privileged/solution/oracle_replay.py b/tasks/mujoco_playground_go1_footstand-privileged/solution/oracle_replay.pynew file mode 100644index 0000000000..46987df1d0--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-privileged/solution/oracle_replay.py@@ -0,0 +1,15 @@+"""Oracle (privileged): replay the reference rows in the tooling, check them, and save them as the deliverable."""+import json+import os+import sys++import numpy as np++sys.path.insert(0, "/opt/tools")+from rcb_quadruped import Session # noqa: E402++rows = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy"))+s = Session("/app/instance.json")+r = s.replay(rows)+s.save_trajectory(rows, "/app/output/trajectory.npz", meta={"source": "reference trajectory (solution/oracle.npy)"})+print(json.dumps({k: v for k, v in r.items() if k != "segments"}))diff --git a/tasks/mujoco_playground_go1_footstand-privileged/solution/solve.sh b/tasks/mujoco_playground_go1_footstand-privileged/solution/solve.shnew file mode 100755index 0000000000..430ffb6017--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-privileged/solution/solve.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Oracle (privileged): write the reference trajectory frozen at generation time (solution/oracle.npy; how it was made:+# scripts/mujoco-playground/oracle.py) as the deliverable.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_go1_footstand-privileged/task.toml b/tasks/mujoco_playground_go1_footstand-privileged/task.tomlnew file mode 100644index 0000000000..78567215db--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-privileged/task.toml@@ -0,0 +1,43 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = ["/app/output/", "/logs/agent/rcb/"]++[task]+name = "robot-coding-bench/mujoco_playground_go1_footstand-privileged"+description = "MuJoCo Playground Go1Footstand in plain MuJoCo (Unitree Go1, joint position control every 0.02 s): Make the Unitree Go1 stand up on its hind legs, nose up, front legs in the air, and balance there for 2 s. Produce one replayable trajectory of joint position targets on a frozen instance (Playground's reset with seed 0); graded by a footstand held for the trajectory's last 2 s, without a termination (two fresh-process replays)."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "unitree-go1", "quadruped", "locomotion", "stand_on_two", "code-as-policy", "trajectory", "privileged"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "unitree-go1"+family = "mujoco_playground/Go1Footstand"+mode = "privileged"+oracle = "full"+instance_seed = 0 # the PRNGKey of Playground's reset (and, for the joystick tasks, its command process)+expert_time_estimate_hours = 3.0++[verifier]+timeout_sec = 1200.0+environment_mode = "separate"+network_mode = "no-network"++[verifier.environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192++[agent]+timeout_sec = 3600.0+# MuJoCo Playground's trained policies are public upstream, so the agent reaches the model APIs and nothing else+# (scripts/set_agent_egress.py HOSTS).+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_go1_footstand-privileged/tests/Dockerfile b/tasks/mujoco_playground_go1_footstand-privileged/tests/Dockerfilenew file mode 100644index 0000000000..f49c79154d--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-privileged/tests/Dockerfile@@ -0,0 +1,7 @@+# Separate verifier sandbox (PROTOCOL §4): the same image with the verifier's own copies of the tooling and the frozen+# instance. Nothing the agent did in its container reaches this one: Harbor uploads only the declared artifacts.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY grade.py instance.json rcb_quadruped.py test.sh /tests/+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier+ENV PYTHONPATH=/tests+WORKDIR /testsdiff --git a/tasks/mujoco_playground_go1_footstand-privileged/tests/grade.py b/tasks/mujoco_playground_go1_footstand-privileged/tests/grade.pynew file mode 100644index 0000000000..e5668de85f--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-privileged/tests/grade.py@@ -0,0 +1,126 @@+"""Verifier (privileged): replay /app/output/trajectory.npz from the frozen instance and write Harbor's rewards.++ python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz++Two replays, each in its own fresh process (`rcb_quadruped.py replay`: the frozen start, one control step per row, the+task's success check on the whole trajectory). success = both replays succeed and end in the same state. Writes+/logs/verifier/reward.txt (1/0) and reward.json (numbers only); then a third replay renders replay.mp4, after the+verdict is on disk (it never changes it).+"""+import argparse+import json+import os+import subprocess+import sys+import tempfile+import traceback++import numpy as np++LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")+TOOL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_quadruped.py")+REPLAY_TIMEOUT_S = 300 # a 1000-step replay takes a few seconds; the video replay renders 4 views every 2nd step+++def write(ok: bool, out: dict) -> None:+ os.makedirs(LOG_DIR, exist_ok=True)+ open(os.path.join(LOG_DIR, "reward.txt"), "w").write("1\n" if ok else "0\n")+ json.dump(out, open(os.path.join(LOG_DIR, "reward.json"), "w"))+ print(json.dumps(out), flush=True)+++def agent_cost() -> dict:+ """Self-reported cost from the tooling's log in the agent's container (accounting, not evidence)."""+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_replays": 0, "agent_cost_self_reported": 1}+ for path in ("/logs/agent/rcb/rcb_session_log.jsonl", "/app/output/rcb_session_log.jsonl"):+ if not os.path.exists(path):+ continue+ try:+ with open(path) as f:+ for i, line in enumerate(f):+ if i > 200_000 or len(line) > 10_000:+ break+ try:+ e = json.loads(line)+ ev = e.get("ev") if isinstance(e, dict) else None+ if ev == "session_start":+ cost["agent_sessions"] += 1+ elif ev == "reset":+ cost["agent_resets"] += 1+ elif ev == "replay":+ cost["agent_replays"] += 1+ elif ev == "session_end":+ cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)+ except Exception: # noqa: BLE001 -- one bad line must not sink the verdict+ continue+ except OSError:+ pass+ break+ return cost+++def replay(instance: str, traj: str, video: str | None) -> dict:+ """One replay in a fresh process; its result (`--out`), or {"error": ...}."""+ with tempfile.NamedTemporaryFile(suffix=".json") as out:+ cmd = [sys.executable, TOOL, "replay", "--instance", instance, "--traj", traj, "--out", out.name]+ try:+ p = subprocess.run(cmd + (["--video", video] if video else []), stdout=subprocess.DEVNULL, stderr=sys.stderr,+ timeout=REPLAY_TIMEOUT_S, env={**os.environ, "RCB_SESSION_LOG": "", "RCB_AGENT_TRACE_DIR": ""})+ except subprocess.TimeoutExpired:+ return {"error": f"replay took over {REPLAY_TIMEOUT_S} s"}+ try:+ return json.load(open(out.name))+ except ValueError:+ return {"error": f"replay process rc={p.returncode}"}+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--instance", required=True)+ ap.add_argument("--traj", default="/app/output/trajectory.npz")+ a = ap.parse_args()+ cost = agent_cost()+ if not os.path.isfile(a.traj):+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost})+ return 0+ try:+ horizon = int(json.load(open(a.instance))["horizon"])+ d = np.load(a.traj, allow_pickle=False)+ acts = np.asarray(d["actions"], dtype=np.float64) if "actions" in d.files else np.zeros((0, 0))+ if acts.ndim != 2 or acts.shape[1] != 12 or len(acts) > horizon or not np.all(np.isfinite(acts)):+ write(False, {"success": 0, "bad_trajectory": 1, "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0,+ "grader_error": 0, **cost})+ return 0+ runs = [replay(a.instance, a.traj, None), replay(a.instance, a.traj, None)]+ if any("error" in r and not r.get("bad_trajectory") for r in runs):+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ if not all(r.get("instance_ok") for r in runs): # the image no longer builds the frozen start: not the agent's 0+ write(False, {"success": 0, "grader_error": 1, "instance_mismatch": 1, **cost})+ return 0+ all_success = all(bool(r.get("success")) for r in runs)+ deterministic = runs[0].get("state_sha") == runs[1].get("state_sha")+ ok = all_success and deterministic+ r = runs[0]+ num = lambda k: float(r.get(k) if r.get(k) is not None else -1) # noqa: E731+ out = {"success": int(ok), "replay_success": int(all_success), "deterministic": int(deterministic),+ "n_actions": int(len(acts)), "horizon": horizon, "fell": int(r.get("fell_at") is not None),+ "fell_at_step": num("fell_at"), "worst_lin_err": num("worst_lin_err"), "worst_yaw_err": num("worst_yaw_err"),+ "end_tilt_deg": num("tilt_deg"), "end_imu_height": num("imu_height"), "end_pose_angle_deg": num("pose_angle_deg"),+ "grader_error": 0,+ "video_rendered": 0, **cost}+ write(ok, out) # the verdict, before any video+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ try: # the video, for humans: it never changes the verdict+ if replay(a.instance, a.traj, os.path.join(LOG_DIR, "replay.mp4")).get("video"):+ write(ok, {**out, "video_rendered": 1})+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/mujoco_playground_go1_footstand-privileged/tests/instance.json b/tasks/mujoco_playground_go1_footstand-privileged/tests/instance.jsonnew file mode 100644index 0000000000..51305c694d--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-privileged/tests/instance.json@@ -0,0 +1,68 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1Footstand",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ -0.3957096338272095,+ -0.1560124158859253,+ 0.27799999713897705,+ 0.2572470009326935,+ 0.0,+ 0.0,+ -0.9663457870483398,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842+ ],+ "qvel0": [+ -0.4893399477005005,+ 0.021045565605163574,+ 0.45396435260772705,+ -0.16251015663146973,+ -0.030068635940551758,+ -0.1645064353942871,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "text": "Make the Unitree Go1 stand up on its hind legs, nose up, front legs in the air, and balance there for 2 s.",+ "facts": {+ "start_xy_m": [+ -0.396,+ -0.156+ ],+ "start_yaw_deg": -150.2,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.272,+ "reference_rows": 113,+ "torso_mass_kg": 12.743,+ "reference_imu_height": 0.5408,+ "reference_pose_angle_deg": 9.62+ },+ "state_sha": "edd665f20ded",+ "horizon": 500,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s), when its pushes (Barkour) are null or\n weak (peak under 20% of the torso's weight), or when the reference trajectory (oracle.py) fails the task's\n success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_go1_footstand-privileged/tests/rcb_quadruped.py b/tasks/mujoco_playground_go1_footstand-privileged/tests/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-privileged/tests/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_go1_footstand-privileged/tests/test.sh b/tasks/mujoco_playground_go1_footstand-privileged/tests/test.shnew file mode 100755index 0000000000..1c3d2f767b--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-privileged/tests/test.sh@@ -0,0 +1,9 @@+#!/bin/bash+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in two fresh processes (the+# verdict), then a third that renders replay.mp4.+# Writes /logs/verifier/reward.txt (1/0) and reward.json (numeric fields, docs/PROTOCOL.md §2.6).+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/*+mkdir -p /logs/verifier+python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz 2> /logs/verifier/grade.logdiff --git a/tasks/mujoco_playground_go1_footstand-standard/README.md b/tasks/mujoco_playground_go1_footstand-standard/README.mdnew file mode 100644index 0000000000..12b7db56e8--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/README.md@@ -0,0 +1,44 @@+# mujoco_playground_go1_footstand-standard++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | standard (`eai-standard/2.2`) |+| Twin | `mujoco_playground_go1_footstand-privileged` |+| Simulator / robot | `mujoco` / `unitree-go1` |+| Family / instance | `mujoco_playground/Go1Footstand` / seed 0 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `Go1Footstand` (Unitree Go1) on the same frozen instance as `mujoco_playground_go1_footstand-privileged`: Make the Unitree Go1 stand up on its hind legs, nose up, front legs in the air, and balance there for 2 s.+From standing, it has 10 s to get into a footstand on its hind legs and hold it for 2 s (Playground's footstand reward aims at the IMU 0.53 m high). Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with only+the robot's own sensors and four cameras that follow it.++## Difficulty+Same instance and success check as `mujoco_playground_go1_footstand-privileged`. In standard mode the agent loses resets, the simulator and+the world state: it sees camera images and proprioception (joints, IMU, foot contacts), acts in joint position chunks,+and gets one episode, so it has to close the loop on the robot's own sensors and recover from its own mistakes without+starting over.++## Reference solution+`solution/oracle_replay.py` streams the privileged reference's rows (`solution/oracle.npy`, 113 rows, float32-exact)+through the client in `hold` chunks; it uses no privileged information at run time. The service's recorded trajectory+is then exactly the privileged reference, and the episode ends with success after 113 control steps.++## Verification+The sim service judges the episode live and records every executed control step; the collect hook+(`environment/sim/finalize.sh`) ends the service, replays the recorded trajectory in two fresh processes and writes+`final.json`; `tests/grade.py` (separate sandbox, no network) passes iff the live check succeeded, both replays succeed,+and they end in the same state. Oracle: success after 113 control steps.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `locomotion/go1/xmls/scene_mjx_flat_terrain.xml`; MuJoCo Menagerie @ 1b86ece (`unitree_go1`); MuJoCo 3.3.7 on the CPU |+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); cameras `track`, `side`, `back`, `top` (they follow the robot) (320 x 240), the feet's kinematics in the trunk frame |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py`, as its privileged twin.diff --git a/tasks/mujoco_playground_go1_footstand-standard/environment/Dockerfile b/tasks/mujoco_playground_go1_footstand-standard/environment/Dockerfilenew file mode 100644index 0000000000..ed5eee3703--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/environment/Dockerfile@@ -0,0 +1,9 @@+# Standard mode: the agent container has NO simulator and no Playground code, only Python and the client, on the shared+# pinned client base with the shared pins (scripts/eai_standard/client.env, client-requirements.txt).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY client-requirements.txt /tmp/client-requirements.txt+RUN pip install --no-cache-dir -r /tmp/client-requirements.txt+COPY rcb_client.py rcb1.py /opt/tools/+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_go1_footstand-standard/environment/client-requirements.txt b/tasks/mujoco_playground_go1_footstand-standard/environment/client-requirements.txtnew file mode 100644index 0000000000..8aa73a968f--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/environment/client-requirements.txt@@ -0,0 +1,11 @@+# Exact pins for what the standard agent container installs (and a verifier, if it installs anything): the closure of+# `pip install requests numpy pillow scipy`, the unpinned line of every standard task at 9eb18edf, resolved on+# 2026-10-01 in CLIENT_IMAGE (client.env: Python 3.12.14, pip 25.0.1). A change here is a shared-files PR.+certifi==2026.7.22+charset-normalizer==3.5.2+idna==3.20+numpy==2.5.3+pillow==12.3.0+requests==2.34.2+scipy==1.18.1+urllib3==2.8.0diff --git a/tasks/mujoco_playground_go1_footstand-standard/environment/docker-compose.yaml b/tasks/mujoco_playground_go1_footstand-standard/environment/docker-compose.yamlnew file mode 100644index 0000000000..8ec63c582e--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/environment/docker-compose.yaml@@ -0,0 +1,23 @@+# Standard mode: the simulator runs in the `sim` sidecar (the agent cannot open it); the agent only reaches port 8000.+# No `expose`/`ports` on sim: under Harbor's egress control it shares main's network namespace (localhost:8000).+# CPU only: MuJoCo physics and rendering (EGL when a GPU is there, else OSMesa); no GPU reservation.+# Crash recovery (docs/STANDARD_MODE_2_2.md §13): run.sh exits non-zero when the service crashes, compose restarts the+# container (same container, same /data) and the service replays its journal into the same episode, never a reset.+services:+ main:+ depends_on: [sim]+ sim:+ image: ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+ volumes:+ - ./sim:/srv:ro+ working_dir: /tmp+ command: sh /srv/run.sh+ restart: on-failure:6 # N >= 3 (PROTOCOL §4.1); a resume continues the episode+ environment:+ RCB_INSTANCE: /srv/instance.json+ RCB_TOOL: /srv/rcb_quadruped.py+ RCB_DATA: /data+ RCB_WALL_CLOCK_S: "3600"+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in about a second+ PYTHONPATH: /srv+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction logdiff --git a/tasks/mujoco_playground_go1_footstand-standard/environment/rcb1.py b/tasks/mujoco_playground_go1_footstand-standard/environment/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/environment/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_go1_footstand-standard/environment/rcb_client.py b/tasks/mujoco_playground_go1_footstand-standard/environment/rcb_client.pynew file mode 100644index 0000000000..aa25b0e050--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/environment/rcb_client.py@@ -0,0 +1,211 @@+"""eai-standard/2.2 client (formerly rcb-limited/2.x) — the only thing a standard-mode agent gets (installed at+/opt/tools/rcb_client.py).++ from rcb_client import Robot+ r = Robot() # finds the service (sim:8000, then localhost:8000), waits for warm-up+ spec = r.spec() # actions, cameras (+ intrinsics, mounting), robot_spec, world, budget, kinematics+ obs = r.get_obs() # current frames: obs.last[cam] -> uint8 (H,W,3); obs.meta["proprio"]+ obs = r.get_obs(depth=True) # + obs.last_depth[cam] -> float32 (H,W) z-depth in metres, 0 = no reading+ res = r.submit("joint_position", A, dt=0.1) # A: (T, dim) rows dt apart; returns the execution video+ res = r.submit("ee_pose", P) # (T, dim) end-effector targets (see spec()["action_types"])+ res.video[cam] -> mp4 bytes res.frames[cam] -> uint8 (N,H,W,3) if video="frames"/"both" res.last[cam]+ res.proprio -> float32 (N, D), one row per frame (names: spec()["proprio_layout"]; res.group("tcp_pose"))+ res.frame_step -> int64 (N,) control step of each frame res.frame_time_s -> float64 (N,) simulated time+ res.extrinsic_cv[cam] -> float64 (N,3,4) world->camera per frame (res.meta["cameras"]: intrinsics + the last frame's pose)+ res = r.submit(..., depth="frames") # + res.depth[cam] -> float32 (N,H,W) metres, one per frame (1 mm steps)+ r.fk(q) # {"ok", "poses": {frame: [x,y,z, quaternion]}}: forward kinematics, no physics+ r.ik({frame: pose}, seed=q) # {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}: inverse kinematics+ res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, frames/<cam>/NNN.jpg, proprio.npy, depth, frame_meta.npz+ obs = r.get_obs(seconds=3, video="both") # hold the last command, let physics run 3 s, return the video+ r.status() # calls, control steps, done, reason, elapsed time++Nothing is put into your context automatically: what you look at, and where you store it, is your code's decision.++If a call fails with a connection error or a 5xx, the service may have crashed; it restarts and resumes the SAME episode+(never a reset) in the state after the last call it completed, which you may not have received. r.wait_ready() waits+until it answers again (resuming replays the episode so far: long episodes can take minutes); then check r.status()+before you continue (spec()["on_service_error"]).+"""+from __future__ import annotations+import json, os, pathlib, sys, time, zlib+import numpy as np+import requests+import rcb1++PROTOCOL = "eai-standard/2.2" # also talks to 2.0 / 2.1 services (they ignore depth and send no frame metadata)+ACCEPTED = ("eai-standard/2.", "rcb-limited/2.") # every 2.x service, under the protocol's current and former name+++class EpisodeOver(RuntimeError):+ pass+++def _decode_depth_frames(p: dict) -> np.ndarray:+ a = np.frombuffer(zlib.decompress(p["data"]), dtype="<u2").reshape(p["shape"])+ return a.astype(np.float32) / 1000.0+++class Result:+ """Decoded RCB1 response: meta (dict), video (cam -> mp4 bytes), frames (cam -> uint8 (N,H,W,3)), last (cam -> uint8+ (H,W,3)), last_depth (cam -> float32 (H,W) m), depth (cam -> float32 (N,H,W) m, one per frame), proprio (float32 (N,D)),+ frame_step (int64 (N,)), frame_time_s (float64 (N,)), extrinsic_cv (cam -> float64 (N,3,4)). save(dir) writes it out;+ show(cam, k) returns one frame; group(name) the proprio columns of one spec()["proprio_groups"] group. stopped: None,+ or why the service stopped the call early ("max_call_wall_s": it ran longer than spec()["max_call_wall_s"]); then+ meta["executed_rows"] < the rows sent, and meta["proprio"]["now"] is where the robot is."""+ def __init__(self, meta: dict, parts: dict, spec: dict | None = None):+ self.meta = meta; self.raw = parts; self._spec = spec or {}; self.stopped = meta.get("stopped")+ self.video, self.frames, self.last, self.last_depth, self.depth, self.extrinsic_cv = {}, {}, {}, {}, {}, {}+ self.proprio = None; self.frame_step = None; self.frame_time_s = None+ for name, p in parts.items():+ kind, data = p["kind"], p["data"]+ if name.startswith("video/") and kind == "mp4": self.video[name[6:]] = data+ elif name.startswith("frames/") and kind == "array": self.frames[name[7:]] = data+ elif name.startswith("last/") and kind == "array": self.last[name[5:]] = data+ elif name.startswith("last_depth/") and kind == "array": self.last_depth[name[11:]] = np.asarray(data, dtype=np.float32)+ elif name.startswith("depth_frames/") and p.get("codec") == "zlib": self.depth[name[13:]] = _decode_depth_frames(p)+ elif name.startswith("depth/") and kind == "array": self.depth[name[6:]] = np.asarray(data, dtype=np.float32) # 2.1 form+ elif name.startswith("extrinsic_cv/") and kind == "array": self.extrinsic_cv[name[13:]] = data+ elif name == "proprio": self.proprio = data+ elif name == "frame_step": self.frame_step = data+ elif name == "frame_time_s": self.frame_time_s = data++ @property+ def done(self) -> bool: return bool(self.meta.get("done"))++ def show(self, camera: str, k: int = -1) -> np.ndarray:+ if camera in self.frames: return self.frames[camera][k]+ return self.last[camera]++ def group(self, name: str, now: bool = False) -> np.ndarray:+ """Columns of proprio group `name` (spec()["proprio_groups"]): (N, n) over the frames, or (n,) of meta["proprio"]["now"]."""+ first, n = self._spec["proprio_groups"][name][:2]+ if now: return np.asarray(self.meta["proprio"]["now"], dtype=np.float64)[first:first + n]+ return self.proprio[:, first:first + n]++ def save(self, out_dir: str) -> str:+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ (out / "meta.json").write_text(json.dumps(self.meta, indent=1))+ for cam, b in self.video.items(): (out / f"{cam}.mp4").write_bytes(b)+ try:+ from PIL import Image+ for cam, img in self.last.items():+ (out / "last").mkdir(exist_ok=True); Image.fromarray(np.ascontiguousarray(img)).save(out / "last" / f"{cam}.jpg", quality=90)+ for cam, arr in self.frames.items():+ d = out / "frames" / cam; d.mkdir(parents=True, exist_ok=True)+ for i, f in enumerate(arr): Image.fromarray(np.ascontiguousarray(f)).save(d / f"{i:03d}.jpg", quality=85)+ except ImportError:+ for cam, img in self.last.items(): np.save(out / f"last_{cam}.npy", img)+ for cam, arr in self.frames.items(): np.save(out / f"frames_{cam}.npy", arr)+ for cam, arr in self.last_depth.items(): np.save(out / f"last_depth_{cam}.npy", arr)+ for cam, arr in self.depth.items(): np.savez_compressed(out / f"depth_{cam}.npz", depth_mm=np.rint(arr * 1000).astype(np.uint16))+ if self.proprio is not None: np.save(out / "proprio.npy", self.proprio)+ if self.frame_step is not None:+ np.savez(out / "frame_meta.npz", frame_step=self.frame_step, frame_time_s=self.frame_time_s,+ **{f"extrinsic_cv/{c}": e for c, e in self.extrinsic_cv.items()})+ return str(out)+++class Robot:+ def __init__(self, base: str | None = None, timeout: float = 600.0):+ cands = [base or os.environ.get("SIM_URL"), "http://sim:8000", "http://localhost:8000"]+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ for b in [c for c in cands if c]:+ try:+ r = requests.get(b + "/spec", timeout=(5, 30))+ if r.status_code == 503: last = "warming up"; break+ r.raise_for_status(); self.base = b; self._spec = r.json()+ if not str(self._spec.get("protocol", "")).startswith(ACCEPTED):+ raise RuntimeError(f"not a 2.x service: protocol {self._spec.get('protocol')!r}")+ return+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(2)+ raise RuntimeError(f"sim service unavailable: {last}")++ def spec(self) -> dict:+ return self._spec++ def _post(self, path: str, meta: dict, parts: list, timeout: float) -> Result:+ body = rcb1.encode(meta, parts)+ r = requests.post(self.base + path, data=body, headers={"Content-Type": "application/x-rcb1"}, timeout=(5, timeout))+ if r.status_code == 409:+ raise EpisodeOver(r.json().get("reason") if r.headers.get("Content-Type", "").startswith("application/json") else "episode finished")+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ m, p = rcb1.decode(r.content); return Result(m, p, self._spec)++ def _common(self, cameras, video_fps, depth, include_depth) -> dict:+ cams = list(cameras) if cameras is not None else self._spec.get("default_cameras")+ if depth is None or depth is False: depth = "frames" if include_depth else "none"+ elif depth is True: depth = "last"+ m = {"cameras": cams, "video_fps": None if video_fps is None else int(video_fps), "depth": depth}+ return {k: v for k, v in m.items() if v is not None}++ def submit(self, action_type: str, actions, dt: float | None = None, interpolate: str = "linear", cameras=None,+ video_fps: int | None = None, video: str = "mp4", depth=None, include_depth: bool = False, note: str = "") -> Result:+ """Execute a chunk of low-level actions (T, dim); see spec()['action_types'] for dims, layouts, limits and semantics.+ dt defaults to one control period, cameras to spec()['default_cameras']; depth: None | True (= "last") | "frames"."""+ a = np.asarray(actions, dtype=np.float32)+ if a.ndim == 1: a = a[None, :]+ if dt is None and self._spec.get("control_hz"): dt = 1.0 / float(self._spec["control_hz"])+ meta = {"type": action_type, "interpolate": interpolate, "video": video, "note": note,+ **({} if dt is None else {"dt": float(dt)}), **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/submit", meta, [rcb1.array_part("actions", a)], timeout=1800)+ if res.stopped:+ print(f"[rcb_client] the service stopped this call early ({res.stopped}): {res.meta.get('executed_rows')} of {len(a)} rows "+ "executed; meta['proprio']['now'] is where the robot is", file=sys.stderr)+ return res++ def get_obs(self, cameras=None, seconds: float = 0.0, video_fps: int | None = None, depth=None, include_depth: bool = False,+ video: str = "frames") -> Result:+ """Current frames (seconds=0, free) or hold the last command and watch for `seconds` (returns the video).+ depth: None | True (= "last": the last frame's depth) | "frames" (one depth map per frame)."""+ meta = {"seconds": float(seconds), "video": video, **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/observe", meta, [], timeout=600)+ if res.stopped:+ print(f"[rcb_client] the service stopped this watch early ({res.stopped}) after {res.meta.get('control_steps_watch')} control "+ "steps", file=sys.stderr)+ return res++ def status(self) -> dict:+ r = requests.get(self.base + "/status", timeout=(5, 60)); r.raise_for_status(); return r.json()++ def wait_ready(self, timeout: float = 3600.0) -> dict:+ """After a connection error: wait until the service answers GET /status again (it resumes the same episode after a+ crash), then return the status. Raises RuntimeError after `timeout` seconds."""+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ try:+ return self.status()+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(5)+ raise RuntimeError(f"sim service did not come back within {timeout:.0f} s: {last}")++ def kinematics(self, body: dict) -> dict:+ """POST /kinematics (stateless: never moves the robot, never advances time). Raises ValueError on a bad request."""+ r = requests.post(self.base + "/kinematics", json=body, timeout=(5, 120))+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ return r.json()++ def fk(self, q, links=None, base_pose=None) -> dict:+ """Forward kinematics: q in spec()['kinematics']['joint_names'] order -> {"ok", "frame", "poses": {link: [x,y,z, quat]}}+ (quaternion order spec()['world']['quaternion_order']; a mobile robot answers in its base frame unless base_pose is given)."""+ body = {"op": "fk", "q": [float(v) for v in np.asarray(q).reshape(-1)]}+ if links is not None: body["links"] = list(links)+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)++ def ik(self, targets: dict, seed=None, base_pose=None, **opts) -> dict:+ """Inverse kinematics: {frame: [x,y,z, quat]} (frames from spec()['kinematics']['ik_targets']) and an optional seed q ->+ {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}. opts: tol_pos_m, tol_rot_rad, max_iters."""+ body = {"op": "ik", "targets": {k: [float(v) for v in p] for k, p in targets.items()}, **opts}+ if seed is not None: body["seed"] = [float(v) for v in np.asarray(seed).reshape(-1)]+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)diff --git a/tasks/mujoco_playground_go1_footstand-standard/environment/sim/finalize.sh b/tasks/mujoco_playground_go1_footstand-standard/environment/sim/finalize.shnew file mode 100755index 0000000000..02048ddc74--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/environment/sim/finalize.sh@@ -0,0 +1,80 @@+#!/bin/sh+# [[verifier.collect]] hook, run inside the `sim` sidecar once Harbor has stopped the agent's container.+# 1. `rcb_limited.py end` (docs/STANDARD_MODE_2_2.md §13.3): SIGUSR1 to the service, which ends the episode if the+# agent had not (reason "timeout"), writes trajectory.npz + episode.json (live verdict, final-state hash) and exits.+# It exits 2 when final.json already holds the verdict (the service gave up after crashes): that verdict stays.+# 2. replay the trajectory from the frozen instance in TWO fresh processes (`rcb_quadruped.py replay`, the privileged+# verifier's replay): determinism = fresh process == fresh process; live_matches_replay = live == replay.+# 3. merge everything into final.json, the only thing the verifier sandbox grades;+# 4. a third replay renders replay.mp4, after the verdict is on disk (it never changes it).+set -u+DATA="${RCB_DATA:-/data}"; TOOL="${RCB_TOOL:?}"; INSTANCE="${RCB_INSTANCE:?}"+python /srv/rcb_limited.py end "$DATA" --timeout "${RCB_COLLECT_END_TIMEOUT_S:-900}"; rc=$?+if [ "$rc" = 2 ]; then+ echo "[finalize] final.json already holds the verdict; no replay"; exit 0+fi+if [ "$rc" != 0 ]; then+ echo "[finalize] the service did not end and dump the episode in time (rc $rc): an infrastructure failure"+ python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data"); p = os.path.join(d, "final.json")+try:+ out = json.load(open(p))+except Exception:+ out = {}+out.update({"finalized": True, "success": False, "replay_success": False, "deterministic": False, "infra_error": 1,+ "error": "collect hook: the sim service did not end and dump the episode in time"})+json.dump(out, open(p, "w"))+print(json.dumps(out))+PY+ exit 0+fi+replay() { # <n> [--video FILE]: one replay in a fresh process, its result in $DATA/replay<n>.json+ n=$1; shift+ RCB_SESSION_LOG= python "$TOOL" replay --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --out "$DATA/replay$n.json" \+ "$@" > /dev/null 2> "$DATA/replay$n.log"+ echo "[finalize] replay $n exit $?"+}+echo "[finalize] episode dumped; replaying twice in fresh processes"+rm -f "$DATA/replay1.json" "$DATA/replay2.json" "$DATA/replay3.json"+replay 1+replay 2+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+def result(name):+ try:+ v = json.load(open(os.path.join(d, name)))+ except (OSError, ValueError):+ return {}+ return v if isinstance(v, dict) else {}+out = {"replay_success": False, "deterministic": False, "video": False}+try:+ out.update(json.load(open(os.path.join(d, "episode.json"))))+except Exception as exc:+ out["error"] = f"no episode.json: {exc!r}"+a, b = result("replay1.json"), result("replay2.json")+out["replay_success"] = bool(a.get("success")) and bool(b.get("success"))+out["replay_sha"], out["replay_sha2"] = a.get("state_sha"), b.get("state_sha")+out["deterministic"] = bool(a.get("state_sha")) and a.get("state_sha") == b.get("state_sha")+out["live_matches_replay"] = bool(a.get("state_sha")) and a.get("state_sha") == out.get("live_sha")+if not (a.get("state_sha") and b.get("state_sha")): # a replay process died (it crashed or timed out): not the agent's 0+ out.update({"replay_failed": 1, "infra_error": 1,+ "error": "a replay process gave no result (replay1.log / replay2.log)"})+elif not (a.get("instance_ok") and b.get("instance_ok")): # the image no longer builds the frozen start: not the agent's 0+ out.update({"instance_mismatch": 1, "infra_error": 1, "error": "a replay did not start in the instance's t = 0 state"})+out["finalized"] = True+json.dump(out, open(os.path.join(d, "final.json"), "w"))+print(json.dumps(out))+PY+replay 3 --video "$DATA/replay.mp4"+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+try:+ shown = json.load(open(os.path.join(d, "replay3.json"))).get("video")+except (OSError, ValueError):+ shown = False+if shown:+ p = os.path.join(d, "final.json"); out = json.load(open(p)); out["video"] = True; json.dump(out, open(p, "w"))+PYdiff --git a/tasks/mujoco_playground_go1_footstand-standard/environment/sim/instance.json b/tasks/mujoco_playground_go1_footstand-standard/environment/sim/instance.jsonnew file mode 100644index 0000000000..51305c694d--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/environment/sim/instance.json@@ -0,0 +1,68 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1Footstand",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ -0.3957096338272095,+ -0.1560124158859253,+ 0.27799999713897705,+ 0.2572470009326935,+ 0.0,+ 0.0,+ -0.9663457870483398,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842+ ],+ "qvel0": [+ -0.4893399477005005,+ 0.021045565605163574,+ 0.45396435260772705,+ -0.16251015663146973,+ -0.030068635940551758,+ -0.1645064353942871,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "text": "Make the Unitree Go1 stand up on its hind legs, nose up, front legs in the air, and balance there for 2 s.",+ "facts": {+ "start_xy_m": [+ -0.396,+ -0.156+ ],+ "start_yaw_deg": -150.2,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.272,+ "reference_rows": 113,+ "torso_mass_kg": 12.743,+ "reference_imu_height": 0.5408,+ "reference_pose_angle_deg": 9.62+ },+ "state_sha": "edd665f20ded",+ "horizon": 500,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s), when its pushes (Barkour) are null or\n weak (peak under 20% of the torso's weight), or when the reference trajectory (oracle.py) fails the task's\n success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_go1_footstand-standard/environment/sim/rcb1.py b/tasks/mujoco_playground_go1_footstand-standard/environment/sim/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/environment/sim/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_go1_footstand-standard/environment/sim/rcb_limited.py b/tasks/mujoco_playground_go1_footstand-standard/environment/sim/rcb_limited.pynew file mode 100644index 0000000000..1ce1171787--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/environment/sim/rcb_limited.py@@ -0,0 +1,930 @@+"""eai-standard/2.2 (formerly rcb-limited/2.2): the HTTP layer, the protocol helpers and the crash recovery that every+2.2 sim service shares (docs/STANDARD_MODE_2_2.md; the 2.1 base is docs/LIMITED_MODE_PROTOCOL.md).++The source is scripts/eai_standard/rcb_limited.py; the generators copy it unchanged into every standard task's+environment/sim/ (ci_checks/check-tooling-identity.sh). A service keeps its simulator to itself (scene, action+execution, cameras, kinematic model) and hands this module plain callables:++ import rcb_limited as L+ EP = L.Episode(DATA, dim=N, resume="exact") # before the scene is built; "approx" for a nondeterministic simulator+ EP.startup() # start count, back-off after failed starts, startup watchdog+ S = <build the scene>; EP.scene_built() # the watchdog stands down+ def ctrl_step(a, rec): # every executed control step+ S.step(a); stop = EP.journal(a); rec.tick(); return E["done"] or stop+ rec = L.Recorder(cams, every, grab, proprio_row, extrinsics, clock, depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+ rec.tick(force=True) # first frame (before the chunk / watch)+ ...; rec.tick(); ... # after every control step: a frame every `every` steps+ rec.tick(force=True, last=True) # last frame (+ its depth)+ parts = rec.parts(video, fps) # RCB1 parts: video/ frames/ last/ extrinsic_cv/ last_depth/ depth_frames/ depth/ proprio frame_*+ S.record_start()+ EP.begin(state=E, step=S.step, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, start_event={...}, on_end=end_fn)+ L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics,+ status=status, on_submit_error=lambda exc: finish("error"), log=EP.log,+ episode=EP, state_sha=S.state_sha, proprio=proprio_row))++ grab(cams, want_depth) -> ({cam: uint8 (H,W,3)}, {cam: float32 (H,W) z-depth in metres, 0 = no reading})+ extrinsics(cams) -> {cam: (3,4) world -> camera, OpenCV axes (x right, y down, z forward)}+ proprio_row() -> float32 (len(spec["proprio_layout"]),)+ clock() -> int, control steps since the episode start (the frame's step index)+ do_kinematics(req) -> dict; `req` is parse_kinematics(body, spec["kinematics"]); it must never step physics++None of the callables may step physics. check_spec(SPEC) runs in serve(): a service whose /spec misses a 2.2 field, or+carries a field the protocol forbids (segmentation, object identities or sizes, physical parameters), does not start.+Crash recovery (class Episode; PROTOCOL §4.7): every executed control step is journaled, every completed call+checkpointed (rows, state hash, the robot's proprio row); after a crash compose restarts the container and the service+replays the journal and continues the SAME episode, never a reset. `python rcb_limited.py end <data dir>` is the shared+first half of a collect hook."""+from __future__ import annotations+import faulthandler, json, math, os, re, select, signal, socket, sys, tempfile, threading, time, traceback, zlib+from http.server import BaseHTTPRequestHandler, HTTPServer+from typing import Any, Callable++import numpy as np++import rcb1++PROTOCOL = "eai-standard/2.2"+COMPAT = ["rcb-limited/2.0", "rcb-limited/2.1", "eai-standard/2.1"] # requests written for these are served unchanged+MAX_BODY = 64 * 1024 * 1024+MAX_RESP = 256 * 1024 * 1024+DEPTH_MODES = ("none", "last", "frames")+DEPTH_MAX_M = 65.535 # uint16 millimetres; a farther surface reads 0 (no reading)+DEPTH_NOISE = os.environ.get("RCB_DEPTH_NOISE", "off").strip().lower() # off | realsense (as rcb-limited/2.1)+_RNG = np.random.default_rng(int(os.environ.get("RCB_DEPTH_NOISE_SEED", "0")))+PROPRIO_GROUPS_REQUIRED = ("joint_pos", "joint_vel", "gripper_opening", "tcp_pose", "joint_effort")+PART_PREFIXES = ("video/", "frames/", "last/", "last_depth/", "depth_frames/", "depth/", "extrinsic_cv/")+PART_NAMES = ("proprio", "frame_step", "frame_time_s")+++# ---------------------------------------------------------------- depth+def depth_mode(meta: dict) -> str:+ """The request's depth mode: "none" | "last" | "frames" (2.2 field `depth`), or "legacy" for a 2.0/2.1 request that+ sets `include_depth: true` and no `depth` (answered as 2.1 did: `depth/<cam>` float16 (N,H,W) metres)."""+ d = meta.get("depth")+ if d is None or d is False:+ return "legacy" if meta.get("include_depth") is True else "none"+ if d is True:+ return "last"+ if isinstance(d, str) and d in DEPTH_MODES:+ return d+ raise ValueError(f"depth must be one of {'|'.join(DEPTH_MODES)} (got {d!r})")+++def clean_depth(z) -> np.ndarray:+ """float32 z-depth in metres: non-finite, negative and beyond-range pixels read 0 (no reading); the optional+ RCB_DEPTH_NOISE=realsense model (sigma = 2 mm + 2.5 mm * z^2, 1 % dropouts) is applied here, after rendering, so it+ never touches physics."""+ z = np.asarray(z, dtype=np.float32).copy()+ if z.ndim == 3 and z.shape[-1] == 1:+ z = z[..., 0]+ bad = ~np.isfinite(z) | (z <= 0) | (z > DEPTH_MAX_M)+ z[bad] = 0.0+ if DEPTH_NOISE == "realsense":+ valid = z > 0+ z = z + _RNG.normal(0.0, 1.0, z.shape).astype(np.float32) * (0.002 + 0.0025 * z * z)+ z[_RNG.random(z.shape) < 0.01] = 0.0+ z[~valid] = 0.0+ z[(z < 0) | (z > DEPTH_MAX_M)] = 0.0+ return z.astype(np.float32)+++def depth_frames_part(name: str, stack: np.ndarray) -> tuple[str, str, bytes, dict]:+ """(N,H,W) metres -> an RCB1 "bytes" part: zlib of C-order uint16 millimetres (0 = no reading). Clients that do not+ know it keep the raw bytes and ignore it; rcb_client decodes it back to float32 metres."""+ mm = np.rint(np.asarray(stack, dtype=np.float64) * 1000.0)+ mm[(mm < 0) | (mm > 65535)] = 0+ a = np.ascontiguousarray(mm.astype("<u2"))+ return (name, "bytes", zlib.compress(a.tobytes(), 1), {"codec": "zlib", "dtype": "uint16", "shape": list(a.shape), "unit": "mm"})+++def encode_mp4(frames: np.ndarray, fps: int) -> bytes:+ """H.264 mp4 (yuv420p, faststart) of uint8 (N,H,W,3) frames: the same encoding every 2.0 service used."""+ import imageio.v2 as imageio+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tf:+ path = tf.name+ try:+ with imageio.get_writer(path, format="FFMPEG", mode="I", fps=fps, codec="libx264", macro_block_size=1,+ output_params=["-movflags", "+faststart", "-pix_fmt", "yuv420p"]) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ return open(path, "rb").read()+ finally:+ try:+ os.unlink(path)+ except OSError:+ pass+++# ---------------------------------------------------------------- recording what the cameras see during one call+class Recorder:+ """Frames of the requested cameras every `every` clock ticks, plus forced first/last frames; for every frame the+ proprio row, the clock (step index), each camera's extrinsics and, if asked, its depth. All arrays share one frame+ axis N: frames/<cam>, the mp4's frames, proprio, frame_step, frame_time_s, extrinsic_cv/<cam>, depth_frames/<cam>."""++ def __init__(self, cameras, every: int, grab: Callable, proprio_row: Callable, extrinsics: Callable, clock: Callable,+ depth: str = "none", clock_hz: float = 1.0):+ if depth not in DEPTH_MODES + ("legacy",):+ raise ValueError(f"bad depth mode {depth!r}")+ self.cams = list(cameras); self.every = max(1, int(every)); self.mode = depth; self.hz = float(clock_hz)+ self._grab, self._prop, self._ext, self._clock = grab, proprio_row, extrinsics, clock+ self.frames: dict = {c: [] for c in self.cams}; self.depth: dict = {c: [] for c in self.cams}+ self.ext: dict = {c: [] for c in self.cams}; self.last_depth: dict = {}+ self.prop: list = []; self.steps: list = []; self.n = 0; self.missing = 0++ def tick(self, force: bool = False, last: bool = False) -> None:+ if force or last or self.n % self.every == 0:+ self._capture(last)+ self.n += 1++ def _capture(self, last: bool) -> None:+ want = self.mode in ("frames", "legacy") or (last and self.mode == "last")+ rgb, dep = self._grab(self.cams, want)+ ext = self._ext(self.cams)+ for c in self.cams:+ img = rgb.get(c)+ if img is not None:+ img = np.ascontiguousarray(np.asarray(img)[..., :3].astype(np.uint8))+ else: # a camera that failed to render: a black frame (sized in parts()) keeps one frame axis+ self.missing += 1+ self.frames[c].append(img)+ e = ext.get(c)+ self.ext[c].append(np.full((3, 4), np.nan) if e is None else np.asarray(e, dtype=np.float64).reshape(3, 4))+ if want:+ d = dep.get(c)+ if d is None:+ d = np.zeros(img.shape[:2] if img is not None else (1, 1), np.float32)+ else:+ d = clean_depth(d)+ if img is not None and d.shape != img.shape[:2]:+ raise RuntimeError(f"depth of {c} is {d.shape}, its RGB {img.shape[:2]}: they must be pixel-aligned")+ if self.mode in ("frames", "legacy"):+ self.depth[c].append(d)+ if last or self.mode == "frames":+ self.last_depth[c] = d+ self.prop.append(np.asarray(self._prop(), dtype=np.float32).reshape(-1))+ self.steps.append(int(self._clock()))++ def parts(self, video: str, fps: int) -> list:+ if self.mode == "last" and not self.last_depth and self.prop: # no last=True tick: the state has not moved since+ _, dep = self._grab(self.cams, True)+ self.last_depth = {c: clean_depth(dep[c]) for c in self.cams if c in dep}+ out = []+ for c in self.cams:+ good = [f for f in self.frames[c] if f is not None]+ hw = good[-1].shape[:2] if good else (1, 1)+ if len(good) < len(self.frames[c]):+ self.frames[c] = [f if f is not None else np.zeros(hw + (3,), np.uint8) for f in self.frames[c]]+ self.depth[c] = [d if d.shape == hw else np.zeros(hw, np.float32) for d in self.depth[c]]+ if c in self.last_depth and self.last_depth[c].shape != hw:+ self.last_depth[c] = np.zeros(hw, np.float32)+ fr = np.stack(self.frames[c]) if self.frames[c] else np.zeros((0, 1, 1, 3), np.uint8)+ if video in ("mp4", "both") and len(fr):+ out.append((f"video/{c}", "mp4", encode_mp4(fr, fps), {"fps": fps, "n": int(len(fr))}))+ if video in ("frames", "both"):+ out.append(rcb1.array_part(f"frames/{c}", fr))+ if len(fr):+ out.append(rcb1.array_part(f"last/{c}", fr[-1]))+ out.append(rcb1.array_part(f"extrinsic_cv/{c}", np.stack(self.ext[c]) if self.ext[c] else np.zeros((0, 3, 4))))+ if self.mode in ("last", "frames") and c in self.last_depth:+ out.append(rcb1.array_part(f"last_depth/{c}", self.last_depth[c]))+ if self.mode == "frames" and self.depth[c]:+ out.append(depth_frames_part(f"depth_frames/{c}", np.stack(self.depth[c])))+ if self.mode == "legacy" and self.depth[c]:+ out.append(rcb1.array_part(f"depth/{c}", np.stack(self.depth[c]).astype(np.float16)))+ out.append(rcb1.array_part("proprio", np.stack(self.prop) if self.prop else np.zeros((0, 0), np.float32)))+ st = np.asarray(self.steps, dtype=np.int64)+ out.append(rcb1.array_part("frame_step", st))+ out.append(rcb1.array_part("frame_time_s", st.astype(np.float64) / self.hz))+ return out+++def encode_response(meta: dict, parts: list, max_bytes: int = MAX_RESP) -> bytes:+ """The RCB1 body; over `max_bytes` the per-frame depth goes first, then the raw frames (mp4, last frames, last+ depth, proprio and the per-frame arrays always stay), and meta["degraded"] says what was dropped."""+ body = rcb1.encode(meta, parts)+ dropped = []+ for prefixes in (("depth_frames/", "depth/"), ("frames/",)):+ if len(body) <= max_bytes:+ break+ keep = [p for p in parts if not p[0].startswith(prefixes)]+ if len(keep) < len(parts):+ parts = keep; dropped += [x.rstrip("/") for x in prefixes]+ body = rcb1.encode({**meta, "degraded": f"response over {max_bytes} bytes: {', '.join(dropped)} dropped"}, parts)+ return body+++# ---------------------------------------------------------------- kinematics+def _vec(x, n: int, what: str) -> list:+ a = np.asarray(x, dtype=np.float64).reshape(-1) if x is not None else None+ if a is None or a.size != n or not np.all(np.isfinite(a)):+ raise ValueError(f"{what} must be {n} finite numbers")+ return a.tolist()+++def _pose(x, what: str) -> list:+ p = _vec(x, 7, what)+ nq = math.sqrt(sum(v * v for v in p[3:]))+ if nq < 1e-6:+ raise ValueError(f"{what}: quaternion has zero norm")+ return p[:3] + [v / nq for v in p[3:]]+++def parse_kinematics(body: dict, kin: dict) -> dict:+ """Validate a /kinematics request against spec["kinematics"] (ValueError -> 400). Returns+ {"op": "fk", "q", "links", "base_pose"} or {"op": "ik", "targets": {frame: pose7}, "seed", "base_pose", "tol_pos_m",+ "tol_rot_rad", "max_iters"}; poses are x y z + a unit quaternion in the spec's order; q follows kin["joint_names"]."""+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object")+ op = body.get("op"); n = len(kin["joint_names"])+ base = None+ if body.get("base_pose") is not None:+ if kin.get("frame") != "base":+ raise ValueError("base_pose is only accepted by a mobile robot (spec kinematics.frame == 'base')")+ base = _pose(body["base_pose"], "base_pose")+ if op == "fk":+ links = body.get("links") or list(kin["links"])+ if not isinstance(links, list) or any(l not in kin["links"] for l in links):+ raise ValueError(f"links must be a list of names from spec kinematics.links: {kin['links']}")+ return {"op": "fk", "q": _vec(body.get("q"), n, "q"), "links": links, "base_pose": base}+ if op == "ik":+ tg = body.get("targets")+ if not isinstance(tg, dict) or not tg or any(k not in kin["ik_targets"] for k in tg):+ raise ValueError(f"targets must map frames from spec kinematics.ik_targets {kin['ik_targets']} to poses")+ ik = kin.get("ik", {})+ seed = None if body.get("seed") is None else _vec(body["seed"], n, "seed")+ tol_p = float(body.get("tol_pos_m", ik.get("tol_pos_m", 0.005)))+ tol_r = float(body.get("tol_rot_rad", ik.get("tol_rot_rad", 0.05)))+ it = int(body.get("max_iters", ik.get("max_iters", 200)))+ if not (1e-5 <= tol_p <= 0.5 and 1e-4 <= tol_r <= 3.2 and 1 <= it <= 5000):+ raise ValueError("tol_pos_m in [1e-5, 0.5], tol_rot_rad in [1e-4, 3.2], max_iters in [1, 5000]")+ return {"op": "ik", "targets": {k: _pose(v, f"targets[{k}]") for k, v in tg.items()}, "seed": seed, "base_pose": base,+ "tol_pos_m": tol_p, "tol_rot_rad": tol_r, "max_iters": it}+ raise ValueError("op must be 'fk' or 'ik'")+++def fk_response(poses: dict, frame: str) -> dict:+ return {"ok": True, "op": "fk", "frame": frame, "poses": {k: [float(v) for v in np.asarray(p, dtype=np.float64).reshape(7)] for k, p in poses.items()}}+++def ik_response(q, ok: bool, errors: dict, frame: str, note: str | None = None) -> dict:+ """errors: {frame: (position error m, rotation error rad)} of the returned q (None / non-finite -> null: no solution)."""+ fin = lambda v: float(v) if v is not None and math.isfinite(float(v)) else None # noqa: E731+ out = {"ok": bool(ok), "op": "ik", "frame": frame, "q": None if q is None else [float(v) for v in np.asarray(q).reshape(-1)],+ "error": {k: {"pos_m": fin(e[0]), "rot_rad": fin(e[1])} for k, e in errors.items()}}+ if note:+ out["note"] = note+ return out+++def quat_angle(q1, q2) -> float:+ """Rotation angle (rad) between two unit quaternions of the same order."""+ d = abs(float(np.dot(np.asarray(q1, dtype=np.float64), np.asarray(q2, dtype=np.float64))))+ return 2.0 * math.acos(min(1.0, d))+++# ---------------------------------------------------------------- /spec self-check+FORBIDDEN_KEY = re.compile(r"mask|segment|semantic(?!s$)|instance_?id|bbox|bounding|categor|object|\bobj_|label|mass|friction|"+ r"restitution|inertia|density|damping|stiffness", re.I)+GAIN_PATHS = ("robot_spec.controller",) # joint drive gains (stiffness, damping) are the robot's own, and allowed there+POSITION_KEY = re.compile(r"(?:^|_)(?:pos|position|positions|pose|poses|origin|location|coords?|coordinates|world|translation)(?:_|$)|"+ r"(?:^|_)cent(?:er|re)s?(?:_|$)|(?:^|_)xyz?$|(?:^|_)(?:top|surface|floor|table|plane|height|elevation)?_?z$", re.I)+WORLD_TEXT = re.compile(r"\bworld\s+[xyz]\s*=", re.I)+COORDS = re.compile(r"\(\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*(?:,\s*-?\d+(?:\.\d+)?\s*)?\)")+++def world_text(s: str) -> bool:+ """A text that gives a world coordinate: a pixel-to-world formula, or a coordinate tuple with a decimal point that is+ not the robot's own pose ("robot base at (0, 0, 1.08)" stays)."""+ return bool(WORLD_TEXT.search(s)) or any("." in m.group(0) and not re.search(r"base|robot|origin", s[max(0, m.start() - 40):m.start()], re.I)+ for m in COORDS.finditer(s))+CONVENTIONS = {"static.floor_z": 0.0} # BEHAVIOR: the floor is the plane z = 0 (the world frame's definition)+++def static_positions(obj: Any, path: str = "static") -> list[str]:+ """Paths in /spec static that say WHERE something is (keys naming positions, heights, centres; texts with world+ coordinates). Names, inventories, sizes and colours may stay in static; positions never (docs § Never provided)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}"+ if POSITION_KEY.search(str(k)) and CONVENTIONS.get(p, object()) != v:+ out.append(p)+ else:+ out += static_positions(v, p)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += static_positions(v, f"{path}[{i}]")+ elif isinstance(obj, str) and world_text(obj):+ out.append(path)+ return out+++SPEC_REQUIRED = ("protocol", "protocol_compat", "simulator", "robot", "task_text", "control_hz", "cameras", "default_cameras",+ "action_types", "proprio_layout", "proprio_groups", "static", "world", "budget", "robot_spec", "kinematics", "depth")+++def forbidden_keys(obj: Any, path: str = "", skip: tuple = ()) -> list[str]:+ """Key paths that name something the protocol never provides (key paths in `skip` are not searched)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}" if path else str(k)+ if p in skip:+ continue+ if FORBIDDEN_KEY.search(str(k)) and not (re.search(r"damping|stiffness", str(k), re.I) and p.startswith(GAIN_PATHS)):+ out.append(p)+ out += forbidden_keys(v, p, skip)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += forbidden_keys(v, f"{path}[{i}]", skip)+ return out+++def check_spec(spec: dict) -> None:+ """Raise if /spec is not a complete 2.2 spec or names anything forbidden (run at startup, before binding :8000)."""+ miss = [k for k in SPEC_REQUIRED if k not in spec]+ if miss:+ raise RuntimeError(f"/spec misses {miss}")+ if spec["protocol"] != PROTOCOL:+ raise RuntimeError(f"/spec protocol {spec['protocol']!r} != {PROTOCOL}")+ bad = forbidden_keys(spec, skip=())+ if bad:+ raise RuntimeError(f"/spec names forbidden fields: {bad}")+ pos = static_positions(spec["static"])+ if pos:+ raise RuntimeError(f"/spec static says where things are (never provided): {pos}")+ lay = spec["proprio_layout"]+ if len(set(lay)) != len(lay):+ raise RuntimeError("proprio_layout names are not unique")+ for g in PROPRIO_GROUPS_REQUIRED:+ if g not in spec["proprio_groups"]:+ raise RuntimeError(f"proprio_groups misses {g}")+ for g, (first, n, _meaning) in spec["proprio_groups"].items():+ if not (0 <= first and first + n <= len(lay)):+ raise RuntimeError(f"proprio group {g} [{first}, +{n}) outside the {len(lay)} columns")+ kin = spec["kinematics"]+ for k in ("endpoint", "joint_names", "frame", "quaternion_order", "links", "tcp_frames", "ee_frames", "ik_targets"):+ if k not in kin:+ raise RuntimeError(f"kinematics misses {k}")+ if any(j not in lay for j in kin["joint_names"]):+ raise RuntimeError("kinematics.joint_names must be proprio_layout columns (the measured joint positions)")+ if any(f not in kin["links"] for f in list(kin["tcp_frames"]) + list(kin["ee_frames"]) + list(kin["ik_targets"])):+ raise RuntimeError("kinematics tcp_frames / ee_frames / ik_targets must be listed in kinematics.links")+ if spec["proprio_groups"]["tcp_pose"][1] != 7 * len(kin["tcp_frames"]):+ raise RuntimeError("proprio group tcp_pose must hold 7 columns per kinematics.tcp_frames entry")+ for c, cam in spec["cameras"].items():+ for k in ("rgb", "depth", "mounted", "resolution", "intrinsic_cv", "mount"):+ if k not in cam:+ raise RuntimeError(f"cameras.{c} misses {k}")+ if cam["mount"].get("type") not in ("static", "link"):+ raise RuntimeError(f"cameras.{c}.mount.type must be static|link")+ if any(c not in spec["cameras"] for c in spec["default_cameras"]):+ raise RuntimeError("default_cameras must be cameras")+++# ---------------------------------------------------------------- crash recovery (PROTOCOL §4.7; docs/STANDARD_MODE_2_2.md)+MAX_RESUMES = int(os.environ.get("RCB_MAX_RESUMES", "2"))+STARTUP_TIMEOUT_S = float(os.environ.get("RCB_STARTUP_TIMEOUT_S", "900")) # a task with a slower scene build sets more+MAX_CALL_WALL_S = float(os.environ.get("RCB_MAX_CALL_WALL_S", "900")) # < the client's 1800 s /submit read timeout+RESUME_MAX_DEV_M = float(os.environ.get("RCB_RESUME_MAX_DEV_M", "0.05")) # approx resumes: the gross-divergence guard+ON_SERVICE_ERROR = ("a connection error means the service crashed: it restarts and resumes the SAME episode (never a reset) "+ "in the state after the last call it completed, which you may not have received. Wait until GET /status "+ "answers again (rcb_client: Robot.wait_ready(); resuming replays the episode so far, which can take "+ "minutes in a long episode, and the wall clock keeps running), then check calls and control_steps "+ "before you continue. A 500 means the simulator failed: the episode is over (reason \"error\"). A call "+ "that runs longer than max_call_wall_s seconds stops at the next control step and returns what it "+ "executed (meta.stopped, executed_rows).")+++def _jsonable(v: Any) -> Any:+ if isinstance(v, np.ndarray):+ return v.tolist()+ if isinstance(v, (np.floating, np.integer, np.bool_)):+ return v.item()+ if isinstance(v, (list, tuple)):+ return [_jsonable(x) for x in v]+ if isinstance(v, dict):+ return {str(k): _jsonable(x) for k, x in v.items()}+ return v+++def _peer_closed(sock) -> bool:+ """True when the client of an HTTP request has closed its connection (it gave up on the call): the socket reads as+ end-of-file. A client never sends anything while it waits for the response, so readable means closed."""+ try:+ r, _, _ = select.select([sock], [], [], 0)+ return bool(r) and sock.recv(1, socket.MSG_PEEK) == b""+ except (OSError, ValueError):+ return True+++def _read_json(path: str) -> dict:+ try:+ with open(path) as f:+ d = json.load(f)+ return d if isinstance(d, dict) else {}+ except (OSError, ValueError):+ return {}+++def _write_json(path: str, obj: dict) -> None:+ tmp = f"{path}.{os.getpid()}.tmp"+ with open(tmp, "w") as f:+ json.dump(obj, f)+ os.replace(tmp, path)+++def final_verdict(data: str) -> dict | None:+ """final.json if it already holds a verdict that nothing may overwrite: the grading result (finalized, with+ `deterministic`) or the end of an episode the service gave up after crashes (`gave_up`)."""+ fin = _read_json(os.path.join(data, "final.json"))+ if fin.get("finalized") and (fin.get("gave_up") or fin.get("deterministic") is not None):+ return fin+ return None+++class Episode:+ """Crash-safe episode bookkeeping, the same rules as the RoboTwin and MuJoCo services (PROTOCOL §4.7):++ - startup(): before the scene is built. One line in startups.jsonl; a back-off of min(120, 20 (n - 1)) s when the+ earlier starts never began an episode (they crashed while building, e.g. GPU memory taken by other trials); the+ startup watchdog (faulthandler, a C thread: it fires even when a native scene build holds the GIL) dumps every+ thread's traceback and exits 1 after RCB_STARTUP_TIMEOUT_S, so compose restarts the build. Until begin() a SIGUSR1+ (the collect hook's "the agent phase is over") is only remembered.+ - journal(row): every executed control step (the exact row given to the simulator's step) goes to journal.f64.+ - checkpoint(): after every completed call (the HTTP layer calls it): the journal is flushed, then the call's+ checkpoint is logged in episode.jsonl (rows, control steps, state hash, the robot's proprio row, `persist` keys).+ - begin(): a fresh episode, or after a crash (run.sh exits non-zero, compose restarts the container, `restart:+ on-failure:N`) the SAME episode resumed: the journal is replayed up to the last checkpoint, the journal truncated+ there (the call that was in flight is lost as a whole: its caller got an error, not a result), the state hash+ compared, the service's counters restored; the wall clock keeps running from the first start.+ - Resume check, by the simulator's determinism class: `exact` (bit-exact in a fresh process): the hash must match,+ else the episode ends `resume_failed` (infra_error). `approx` (a simulator declared nondeterministic): a+ mismatch is recorded (resume_state_mismatch, and the robot's deviation from its checkpointed proprio: joint_pos and+ tcp_pose) and the episode continues, unless a TCP is more than RCB_RESUME_MAX_DEV_M from where it was+ (resume_failed, infra_error). The verdict never comes from the live state but from fresh replays of the complete+ recorded trajectory, so continuing cannot raise a score.+ - More than RCB_MAX_RESUMES crashes end the episode: `sim_crashed_on_call` if every crash happened while a call was+ being served (the agent's failure), else `sim_crashed` (infra_error = 1). A verdict already on disk is never+ overwritten; the service then idles with its PID file for the collect hook.+ - Per call, two bounds keep one call from holding the single-threaded service: a call that runs longer than+ max_call_wall_s, or whose client has hung up, stops at the next control step and returns what it executed+ (journal() returns True; meta.stopped says why). Neither bounds the episode: the wall clock is its only budget."""++ def __init__(self, data: str, dim: int, resume: str = "exact", persist: tuple = ()):+ if resume not in ("exact", "approx"):+ raise ValueError("resume must be 'exact' or 'approx'")+ self.data, self.dim, self.resume_class, self.persist = data, int(dim), resume, tuple(persist)+ os.makedirs(data, exist_ok=True)+ p = lambda n: os.path.join(data, n) # noqa: E731+ self.f_events, self.f_journal, self.f_final, self.f_pid, self.f_startups = (+ p("episode.jsonl"), p("journal.f64"), p("final.json"), p("server.pid"), p("startups.jsonl"))+ self.rows = 0 # control steps executed in this episode (journaled)+ self.max_call_wall_s = MAX_CALL_WALL_S+ self.n_startups = 0; self.resumes = 0; self.mismatches = 0; self.max_tcp_dev = 0.0; self.max_joint_dev = 0.0+ self._jf = None; self._call: dict | None = None; self._ids = 0; self._ck: tuple | None = None+ self._on_end: Callable | None = None; self._end_pending = False++ # ---- startup+ def startup(self) -> None:+ signal.signal(signal.SIGUSR1, self._usr1)+ try:+ os.remove(self.f_pid) # a PID file from before a crash would send the collect hook to a dead process+ except OSError:+ pass+ with open(self.f_startups, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid()}) + "\n")+ with open(self.f_startups) as f:+ self.n_startups = sum(1 for line in f if line.strip())+ if self.n_startups > 1 and not any(e.get("ev") == "start" for e in self.events()):+ time.sleep(min(120.0, 20.0 * (self.n_startups - 1)))+ faulthandler.dump_traceback_later(STARTUP_TIMEOUT_S, exit=True)++ def scene_built(self) -> None:+ faulthandler.cancel_dump_traceback_later() # the scene exists: a resume replay may take long, it is not a hang++ def _usr1(self, *_):+ if self._on_end is None:+ self._end_pending = True+ else:+ threading.Thread(target=self._on_end, daemon=True).start()++ # ---- the record+ def log(self, ev: dict) -> None:+ with open(self.f_events, "a") as f:+ f.write(json.dumps(_jsonable({"ts": time.time(), **ev})) + "\n")++ def events(self) -> list:+ out = []+ try:+ with open(self.f_events) as f:+ for line in f:+ try:+ out.append(json.loads(line))+ except ValueError: # a line cut by a crash+ pass+ except OSError:+ pass+ return [e for e in out if isinstance(e, dict)]++ def journal(self, row) -> bool:+ """One executed control step. True: the call in progress must stop at this step boundary (meta.stopped)."""+ a = np.asarray(row, dtype=np.float64).reshape(-1)+ if a.size != self.dim:+ raise ValueError(f"journal rows have {self.dim} entries, got {a.size}")+ if self._jf is None:+ self._jf = open(self.f_journal, "ab")+ self._jf.write(a.tobytes()); self.rows += 1+ c = self._call+ if c is None:+ return False+ if c["stopped"] is None:+ now = time.monotonic()+ if now - c["t0"] > self.max_call_wall_s:+ c["stopped"] = "max_call_wall_s"+ elif c["sock"] is not None and now - c["polled"] >= 0.2:+ c["polled"] = now+ if _peer_closed(c["sock"]):+ c["stopped"] = "client_disconnected"+ return c["stopped"] is not None++ @property+ def stopping(self) -> bool:+ """The call in progress must stop (adapters whose loops test E["done"] test this too)."""+ return bool(self._call and self._call["stopped"])++ @property+ def stop_reason(self) -> str | None:+ return self._call["stopped"] if self._call else None++ def call_begin(self, path: str, sock=None) -> int:+ self._ids += 1+ if path != "/kinematics":+ self._call = {"id": self._ids, "t0": time.monotonic(), "sock": sock, "polled": 0.0, "stopped": None}+ self.log({"ev": "call_begin", "id": self._ids, "path": path})+ return self._ids++ def call_end(self, cid: int, path: str, **extra) -> None:+ self.log({"ev": "call_end", "id": cid, "path": path, **extra})+ if path != "/kinematics":+ self._call = None++ def checkpoint(self, state: dict, state_sha: Callable | None, proprio: Callable | None) -> None:+ if self._jf is not None:+ self._jf.flush() # the rows reach the file before the checkpoint that counts them+ if self._ck is not None and self._ck[0] == self.rows:+ sha, pr = self._ck[1], self._ck[2] # no physics since the last checkpoint+ else:+ try:+ sha = state_sha() if state_sha else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); sha = None+ pr = self._proprio_row(proprio)+ self._ck = (self.rows, sha, pr)+ self.log({"ev": "checkpoint", "call": int(state.get("calls") or 0), "step": int(state.get("step") or 0),+ "control_steps": self.rows, "success": bool(state.get("success")), "done": bool(state.get("done")),+ "reason": state.get("reason"), "state_sha": sha, "proprio": pr,+ **({"persist": {k: state.get(k) for k in self.persist}} if self.persist else {})})++ @staticmethod+ def _proprio_row(proprio: Callable | None) -> list | None:+ try:+ return [round(float(v), 6) for v in np.asarray(proprio(), dtype=np.float64).reshape(-1)] if proprio else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); return None++ def final_fields(self) -> dict:+ """Crash-recovery fields for final.json / episode.json (all numeric, for reward.json)."""+ return {"sim_startups": self.n_startups, "resumes": self.resumes, "resume_state_mismatch": int(self.mismatches > 0),+ "resume_max_tcp_dev_m": round(self.max_tcp_dev, 6), "resume_max_joint_dev": round(self.max_joint_dev, 6)}++ # ---- start or resume+ def begin(self, *, state: dict, step: Callable, state_sha: Callable, proprio: Callable, spec: dict,+ start_event: dict | None = None, on_end: Callable | None = None) -> bool:+ """Start the episode, or resume it after a crash. `step(row)` executes one journaled row on the simulator (the+ recorder on, no rendering needed); `on_end` is what the collect hook's SIGUSR1 runs (in a thread). Returns True+ if the episode was resumed."""+ try: # a line cut by the crash must not swallow the next record+ with open(self.f_events, "rb+") as f:+ f.seek(0, os.SEEK_END)+ if f.tell():+ f.seek(-1, os.SEEK_END)+ if f.read(1) != b"\n":+ f.write(b"\n")+ except OSError:+ pass+ ev = self.events()+ starts = [e for e in ev if e.get("ev") == "start"]+ if not starts:+ try:+ os.remove(self.f_journal)+ except OSError:+ pass+ sha = state_sha()+ self._ck = (0, sha, self._proprio_row(proprio))+ self.log({**(start_event or {}), "ev": "start", "state_sha": sha, "protocol": PROTOCOL, "resume": self.resume_class,+ "journal_dim": self.dim})+ state["t0"] = time.time()+ self._arm(on_end)+ return False+ tries = [e for e in ev if e.get("ev") == "resuming"] # earlier resumes (a crash during one counts too)+ resumed = [e for e in ev if e.get("ev") == "resumed"]+ self.resumes = len(tries) # the record so far, also for a give-up below (final_fields)+ self.mismatches = sum(1 for e in resumed if e.get("exact") is False)+ self.max_tcp_dev = max([float(e.get("tcp_dev_m") or 0) for e in resumed] + [0.0])+ self.max_joint_dev = max([float(e.get("joint_dev") or 0) for e in resumed] + [0.0])+ if final_verdict(self.data):+ self.give_up("restarted after finalize", infra=False)+ k = max(i for i, e in enumerate(ev) if e.get("ev") in ("start", "resuming", "resumed"))+ tail = ev[k + 1:]+ in_call = bool({e.get("id") for e in tail if e.get("ev") == "call_begin"} - {e.get("id") for e in tail if e.get("ev") == "call_end"})+ if len(tries) >= MAX_RESUMES:+ agent = sum(1 for e in tries if e.get("crashed_in_call")) + int(in_call) == len(tries) + 1+ self.give_up("sim_crashed_on_call" if agent else "sim_crashed", infra=not agent)+ self.log({"ev": "resuming", "attempt": len(tries) + 1, "crashed_in_call": in_call,+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self.resumes = len(tries) + 1 # this attempt counts, whether or not it succeeds+ cps = [e for e in ev if e.get("ev") == "checkpoint"]+ last = cps[-1] if cps else {"call": 0, "step": 0, "control_steps": 0, "success": False, "state_sha": starts[0].get("state_sha")}+ n = int(last.get("control_steps") or 0)+ try:+ R = np.fromfile(self.f_journal, dtype=np.float64)+ except (OSError, ValueError):+ R = np.zeros(0)+ if R.size < n * self.dim:+ self.give_up("resume_failed: journal shorter than the log", infra=True)+ R = R[: n * self.dim].reshape(n, self.dim)+ t = time.time()+ for row in R:+ step(row)+ replay_s = time.time() - t+ R.tofile(self.f_journal) # drop the rows of the call that was in flight+ self.rows = n+ sha = state_sha(); want = last.get("state_sha")+ exact = None if want is None else sha == want+ dev = self._deviation(last.get("proprio"), proprio, spec)+ if exact is False: # recorded first: a give-up below reports it too+ self.mismatches += 1+ self.max_tcp_dev = max(self.max_tcp_dev, dev.get("tcp_m") or 0.0)+ self.max_joint_dev = max(self.max_joint_dev, dev.get("joint") or 0.0)+ if self.resume_class == "exact":+ self.give_up("resume_failed: replayed state differs from the logged one", infra=True)+ if dev.get("tcp_m") is not None and dev["tcp_m"] > RESUME_MAX_DEV_M:+ self.give_up(f"resume_failed: a replayed TCP is {dev['tcp_m']:.3f} m from its checkpoint (> {RESUME_MAX_DEV_M} m)", infra=True)+ state["calls"] = int(last.get("call") or 0); state["step"] = int(last.get("step") or 0)+ if "success" in state:+ state["success"] = bool(last.get("success"))+ for key, v in (last.get("persist") or {}).items():+ state[key] = v+ state["t0"] = float(starts[0]["ts"])+ ended = [e for e in ev if e.get("ev") == "end" and int(e.get("control_steps") or 0) <= n] # not the lost call's+ if ended:+ state["done"] = True; state["reason"] = ended[-1].get("reason"); state["t_end"] = float(ended[-1]["ts"])+ state["episode_control_steps"] = int(ended[-1].get("control_steps") or n)+ self._ck = (n, sha, self._proprio_row(proprio)) # the replayed state's row (it may differ under approx)+ self.log({"ev": "resumed", "attempt": self.resumes, "control_steps": n, "calls": state["calls"], "state_sha": sha,+ "logged_sha": want, "exact": exact, "class": self.resume_class, "tcp_dev_m": dev.get("tcp_m"),+ "joint_dev": dev.get("joint"), "crashed_in_call": in_call, "replay_s": round(replay_s, 1),+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self._arm(on_end)+ return True++ @staticmethod+ def _deviation(ref, proprio: Callable, spec: dict) -> dict:+ """The replayed robot against its checkpointed proprio row: max |joint_pos| difference (rad or m) and the largest+ TCP position error (m) over the tcp_pose frames (7 columns each: x y z + quaternion)."""+ if ref is None:+ return {}+ try:+ now = np.asarray(proprio(), dtype=np.float64).reshape(-1); ref = np.asarray(ref, dtype=np.float64).reshape(-1)+ except Exception: # noqa: BLE001+ return {}+ if now.shape != ref.shape:+ return {}+ g, out = spec.get("proprio_groups") or {}, {}+ if "joint_pos" in g:+ f, n = int(g["joint_pos"][0]), int(g["joint_pos"][1])+ out["joint"] = float(np.max(np.abs(now[f:f + n] - ref[f:f + n]))) if n else 0.0+ if "tcp_pose" in g:+ f, n = int(g["tcp_pose"][0]), int(g["tcp_pose"][1]); m = n // 7+ d = (now[f:f + 7 * m] - ref[f:f + 7 * m]).reshape(m, 7)[:, :3]+ out["tcp_m"] = float(np.max(np.linalg.norm(d, axis=1))) if m else 0.0+ return out++ def _arm(self, on_end: Callable | None) -> None:+ self._on_end = on_end+ signal.signal(signal.SIGUSR1, self._usr1)+ if on_end is not None and self._end_pending:+ self._end_pending = False+ threading.Thread(target=on_end, daemon=True).start()++ def give_up(self, reason: str, infra: bool) -> None:+ """End the trial's episode without a new one (never a reset): log it, write the verdict unless one is on disk,+ leave the PID file for the collect hook, and idle until the container is removed."""+ faulthandler.cancel_dump_traceback_later()+ self.log({"ev": "restart_refused", "reason": reason})+ if not final_verdict(self.data):+ fin = _read_json(self.f_final)+ fin.update({"success": False, "done": True, "reason": reason, "finalized": True, "gave_up": True, "protocol": PROTOCOL,+ **self.final_fields(), **({"infra_error": 1} if infra else {})})+ _write_json(self.f_final, fin)+ with open(self.f_pid, "w") as f:+ f.write(str(os.getpid()))+ signal.signal(signal.SIGUSR1, lambda *_: None)+ print(f"[{PROTOCOL}] restart refused: {reason}", flush=True)+ while True:+ time.sleep(3600)+++# ---------------------------------------------------------------- the HTTP layer+class Service:+ """What a sim service hands to serve(): spec (dict), lock, state (the service's E dict: done, reason, exiting, error),+ submit(meta, actions) and observe(meta) -> (meta_out, rcb1 parts), kinematics(req) -> dict, status() -> dict,+ on_submit_error(exc) (a simulator error in /submit or /observe: it ends the episode, reason "error"), log(event dict),+ and for crash recovery the Episode with the simulator's state_sha() and proprio row()."""++ def __init__(self, *, spec: dict, lock, state: dict, submit: Callable, observe: Callable, kinematics: Callable,+ status: Callable, on_submit_error: Callable, log: Callable, max_resp: int = MAX_RESP,+ episode: Episode | None = None, state_sha: Callable | None = None, proprio: Callable | None = None):+ self.spec, self.lock, self.state, self.submit, self.observe = spec, lock, state, submit, observe+ self.kinematics, self.status, self.on_submit_error, self.log, self.max_resp = kinematics, status, on_submit_error, log, max_resp+ self.episode, self.state_sha, self.proprio = episode, state_sha, proprio+ self.kin_calls = 0+++def make_handler(svc: Service):+ class H(BaseHTTPRequestHandler):+ def _send(self, code: int, ctype: str, body: bytes) -> None:+ try:+ self.send_response(code); self.send_header("Content-Type", ctype); self.send_header("Content-Length", str(len(body)))+ self.end_headers(); self.wfile.write(body)+ except (BrokenPipeError, ConnectionResetError): # the client hung up (its call was abandoned)+ pass++ def _json(self, code: int, obj: dict) -> None:+ self._send(code, "application/json", json.dumps(obj).encode())++ def _rcb1(self, meta: dict, parts: list) -> None:+ self._send(200, "application/x-rcb1", encode_response(meta, parts, svc.max_resp))++ def log_message(self, *a):+ pass++ def _body(self):+ try:+ n = int(self.headers.get("Content-Length", 0))+ except ValueError:+ raise ValueError("bad Content-Length")+ if n > MAX_BODY:+ raise ValueError("request too large")+ raw = self.rfile.read(n) if n else b""+ if raw[:4] == rcb1.MAGIC:+ return rcb1.decode(raw)+ body = json.loads(raw or b"{}")+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object or an RCB1 frame")+ return body, {}++ def do_GET(self):+ if self.path == "/spec":+ return self._json(200, svc.spec)+ if self.path == "/status":+ st = svc.status()+ return self._json(200, {**st, "resumes": svc.episode.resumes} if svc.episode else st)+ return self._json(404, {"error": "no such endpoint"})++ def do_POST(self):+ if self.path not in ("/submit", "/observe", "/kinematics"):+ return self._json(404, {"error": "no such endpoint"})+ try:+ meta, parts = self._body()+ except Exception as exc: # noqa: BLE001+ return self._json(413 if "too large" in str(exc) else 400, {"error": str(exc)[:200]})+ E, ep = svc.state, svc.episode+ if self.path == "/kinematics": # stateless: never steps physics, never waits for the episode lock+ cid = ep.call_begin(self.path) if ep else 0+ try:+ req = parse_kinematics(meta, svc.spec["kinematics"])+ out = svc.kinematics(req); svc.kin_calls += 1+ except ValueError as exc:+ return self._json(400, {"error": str(exc)[:300]})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); return self._json(500, {"error": "kinematics error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ ep.call_end(cid, self.path)+ return self._json(200, out)+ with svc.lock:+ if E.get("exiting") or (self.path == "/submit" and E.get("done")):+ return self._json(409, {"error": "episode finished", "reason": E.get("reason")})+ cid = ep.call_begin(self.path, self.connection) if ep else 0+ rows0 = ep.rows if ep else 0+ out = blobs = err = None; stopped = None+ try:+ if self.path == "/submit":+ A = np.asarray(parts["actions"]["data"] if "actions" in parts else meta.get("actions", []), dtype=np.float64)+ out, blobs = svc.submit(meta, A)+ else:+ out, blobs = svc.observe(meta)+ except ValueError as exc:+ err = (400, {"error": str(exc)})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); E["error"] = repr(exc); svc.log({"ev": "error", "path": self.path, "error": repr(exc)})+ try:+ svc.on_submit_error(exc) # PROTOCOL §4.6: a simulator error ends the episode (reason "error")+ except Exception: # noqa: BLE001+ traceback.print_exc()+ err = (500, {"error": "simulator error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ stopped = ep.stop_reason+ if err is None or ep.rows != rows0:+ try:+ ep.checkpoint(E, svc.state_sha, svc.proprio)+ except Exception: # noqa: BLE001+ traceback.print_exc()+ ep.call_end(cid, self.path, **({"stopped": stopped} if stopped else {}))+ if err is not None:+ return self._json(*err)+ return self._rcb1({**out, "stopped": stopped}, blobs)+ return H+++def serve(svc: Service, port: int = 8000) -> None:+ """Check the spec, then serve forever (one request at a time, as every 2.x service)."""+ svc.spec.setdefault("on_service_error", ON_SERVICE_ERROR)+ if svc.episode is not None:+ svc.spec.setdefault("max_call_wall_s", svc.episode.max_call_wall_s)+ check_spec(svc.spec)+ HTTPServer(("0.0.0.0", port), make_handler(svc)).serve_forever()+++# ---------------------------------------------------------------- the collect hook's first half+def _alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ try: # a zombie (exited, not yet reaped) counts as gone+ with open(f"/proc/{pid}/stat") as f:+ return f.read().rsplit(")", 1)[-1].split()[0] != "Z"+ except OSError:+ return True+++def end_episode(data: str, timeout: float = 21600.0, wait_key: str | None = None, resend_s: float = 30.0) -> int:+ """Tell the service that the agent phase is over and wait until it has ended the episode. The service may be+ resuming after a crash (no PID file until it is ready again), so there is no fixed start-up wait, and a signal goes+ only to the process that wrote the newest line of startups.jsonl (its SIGUSR1 handler is installed by then).+ Returns 2: final.json already holds the verdict (the service gave up after crashes, or graded in-process; with+ `wait_key`, also waits for that final.json key, e.g. video_done): keep it, run no replays.+ Returns 0: the service dumped the episode (episode.json) and exited: the hook replays it next.+ Returns 1: timed out."""+ t0, sent = time.time(), 0.0+ f_pid, f_dump, f_starts = (os.path.join(data, n) for n in ("server.pid", "episode.json", "startups.jsonl"))+ while time.time() - t0 < timeout:+ fin = final_verdict(data)+ if fin is not None:+ if not wait_key or fin.get(wait_key) or fin.get("gave_up"):+ return 2+ time.sleep(2); continue+ try:+ with open(f_pid) as f:+ pid = int(f.read().strip())+ except (OSError, ValueError):+ pid = None+ try:+ with open(f_starts) as f:+ cur = json.loads([x for x in f if x.strip()][-1]).get("pid")+ except (OSError, ValueError, IndexError):+ cur = None # a service without Episode.startup(): signal what the PID file names+ if pid is not None and (cur is None or pid == cur):+ if not _alive(pid):+ if os.path.exists(f_dump):+ return 0+ elif time.time() - sent >= resend_s:+ try:+ os.kill(pid, signal.SIGUSR1); sent = time.time()+ except OSError:+ pass+ time.sleep(2)+ return 1+++if __name__ == "__main__":+ a = sys.argv[1:]+ if len(a) >= 2 and a[0] == "end":+ wk = a[a.index("--wait-key") + 1] if "--wait-key" in a else None+ to = float(a[a.index("--timeout") + 1]) if "--timeout" in a else 21600.0+ rc = end_episode(a[1], timeout=to, wait_key=wk)+ print({0: "[collect] episode dumped by the service", 1: "[collect] timed out waiting for the service",+ 2: "[collect] final.json already holds the verdict"}[rc], flush=True)+ sys.exit(rc)+ if len(a) == 2 and a[0] == "final-verdict":+ fin = final_verdict(a[1])+ print(json.dumps(fin) if fin else "no final verdict")+ sys.exit(0 if fin else 1)+ print("usage: rcb_limited.py end <data dir> [--wait-key KEY] [--timeout S] | final-verdict <data dir>")+ sys.exit(2)diff --git a/tasks/mujoco_playground_go1_footstand-standard/environment/sim/rcb_quadruped.py b/tasks/mujoco_playground_go1_footstand-standard/environment/sim/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/environment/sim/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_go1_footstand-standard/environment/sim/run.sh b/tasks/mujoco_playground_go1_footstand-standard/environment/sim/run.shnew file mode 100755index 0000000000..49d4d045d4--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/environment/sim/run.sh@@ -0,0 +1,22 @@+#!/bin/sh+# eai-standard/2.2 sidecar entrypoint: PID 1 of the `sim` container, shared by every 2.2 service+# (scripts/eai_standard/run.sh, copied unchanged into each standard task's environment/sim/).+# - The service crashed (a non-zero exit: an exception, a signal, the startup watchdog): exit with its code, so compose+# restarts the container (`restart: on-failure:6`) and the service resumes the same episode from its journal+# (rcb_limited.Episode). The container keeps its /data (or /out) across the restart.+# - The service exited cleanly (0: it dumped its episode on the collect hook's SIGUSR1 and released the simulator): keep+# the container up for the collect hook's fresh-process replays. If the service were PID 1 itself, that exit would+# stop the container and kill the hook with it (Harbor reports exit 137).+# - Everything the service prints also goes to $RCB_DATA/server.log (an artifact: Harbor keeps no sidecar output, and a+# simulator that dies while it loads leaves no other trace).+DATA="${RCB_DATA:-/data}"+mkdir -p "$DATA"+rm -f "$DATA/.service_rc"+{ python -u "${RCB_SERVER:-/srv/server.py}" 2>&1; echo "$?" > "$DATA/.service_rc"; } | tee -a "$DATA/server.log"+rc="$(cat "$DATA/.service_rc" 2>/dev/null)"; rc="${rc:-1}"+if [ "$rc" != 0 ]; then+ echo "[sim] service exited ($rc): leaving, so compose restarts the container (the service resumes the episode if one began)" | tee -a "$DATA/server.log"+ exit "$rc"+fi+echo "[sim] service exited (0); holding the container open for the collect hook" | tee -a "$DATA/server.log"+while true; do sleep 3600; donediff --git a/tasks/mujoco_playground_go1_footstand-standard/environment/sim/server.py b/tasks/mujoco_playground_go1_footstand-standard/environment/sim/server.pynew file mode 100644index 0000000000..b0c774b183--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/environment/sim/server.py@@ -0,0 +1,478 @@+"""eai-standard/2.2 sim service for MuJoCo Playground's quadruped tasks (docs/STANDARD_MODE_2_2.md): the adapter of the+shared layer rcb_limited.py; the simulator is rcb_quadruped.Session (plain MuJoCo on the CPU).+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to+/data/episode.jsonl.++The episode is the frozen instance's: one control step = 1/50 s. A joystick episode ends after the whole command schedule+(the horizon), when the robot meets Playground's termination rule (it falls over: a failure), when the agent submits+`done`, or when its time is over; success = the task's check on the steps executed. A getup episode ends the moment the+check holds (success), after the horizon, on `done` or on timeout.++Crash recovery (rcb_limited.Episode, resume class `exact`: MuJoCo on the CPU repeats bit for bit in a fresh process):+every executed row is journaled; after a crash the service rebuilds the episode and replays the journal. When the+episode ends the service writes /data/trajectory.npz + /data/episode.json; the collect hook (finalize.sh) makes it exit+and replays the trajectory in two fresh processes."""++import math+import os+import sys+import threading+import time+import traceback++import numpy as np++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import rcb_limited as L # noqa: E402++DATA = os.environ.get("RCB_DATA", "/data")+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.json"))+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "3600"))+MAX_CHUNK_S = float(os.environ.get("RCB_MAX_CHUNK_S", "10"))+MAX_WATCH_S = float(os.environ.get("RCB_MAX_WATCH_S", "30"))+CAM_W, CAM_H = 320, 240+LOCK = threading.Lock()+PID_FILE = os.path.join(DATA, "server.pid")+E = {"ready": False, "step": 0, "calls": 0, "done": False, "reason": None, "success": False, "t0": time.time(), "error": None}++os.environ["RCB_SESSION_LOG"] = ""+os.environ["RCB_AGENT_TRACE_DIR"] = ""+import rcb_quadruped as Q # noqa: E402 (first: it picks the rendering backend before mujoco loads)+import mujoco # noqa: E402++EP = L.Episode(DATA, dim=Q.N, resume="exact")+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()+S = Q.Session(INSTANCE)+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz+DT = S.control_dt # one control step of simulated time (Barkour: 10 ms, as Playground steps it)+CTRL_HZ = 1.0 / DT+SUBSTEPS = S.substeps+M = S.model+CAMS = list(S.cameras)+FEET = S.robot["feet"]+LIMITS = np.stack([S.lower, S.upper], axis=1)+GROUPS = [+ ("joint_pos", S.joint_names, "measured joint positions (rad), in the action's order"),+ ("joint_vel", [f"{j}_vel" for j in S.joint_names], "measured joint velocities (rad/s)"),+ ("joint_effort", [f"{j}_effort" for j in S.joint_names], "actuator torques of those joints (N m)"),+ ("gripper_opening", [], "none (no gripper)"),+ ("tcp_pose", [], "none (no gripper)"),+ ("imu_gyro", ["gyro_x", "gyro_y", "gyro_z"], "angular velocity of the trunk, IMU frame (rad/s)"),+ ("imu_accelerometer", ["acc_x", "acc_y", "acc_z"], "specific force at the IMU, IMU frame (m/s^2; +9.81 up at rest)"),+ ("imu_gravity", ["gravity_x", "gravity_y", "gravity_z"], "unit vector of gravity's direction in the IMU frame "+ "([0, 0, -1] when the trunk is level)"),+ ("imu_linvel", ["linvel_x", "linvel_y", "linvel_z"], "linear velocity of the trunk at the IMU, IMU frame (m/s; the "+ "IMU's velocimeter, what a state estimator gives)"),+ ("foot_contact", [f"{f}_contact" for f in FEET], "1 when the foot touches the ground, else 0"),+]+PROPRIO_LAYOUT = [n for _, names, _ in GROUPS for n in names]+PROPRIO_GROUPS, _i = {}, 0+for _g, _names, _meaning in GROUPS:+ PROPRIO_GROUPS[_g] = [_i, len(_names), _meaning]+ _i += len(_names)+++# ------------------------------------------------------------------------------------------------- cameras+def _intrinsic(cam: str) -> list:+ fovy = math.radians(float(M.cam_fovy[M.camera(cam).id]))+ f = 0.5 * CAM_H / math.tan(fovy / 2)+ return [[f, 0.0, CAM_W / 2], [0.0, f, CAM_H / 2], [0.0, 0.0, 1.0]]+++def camera_info(cam: str) -> dict:+ """World -> camera (OpenCV axes) and camera -> world (OpenGL axes) at the current state."""+ i = M.camera(cam).id+ R_gl = S.data.cam_xmat[i].reshape(3, 3) # camera axes (OpenGL: x right, y up, z back) in the world+ p = S.data.cam_xpos[i].copy()+ R_cv = R_gl @ np.diag([1.0, -1.0, -1.0])+ ext = np.zeros((3, 4))+ ext[:, :3] = R_cv.T+ ext[:, 3] = -R_cv.T @ p+ c2w = np.eye(4)+ c2w[:3, :3] = R_gl+ c2w[:3, 3] = p+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": ext.tolist(), "cam2world_gl": c2w.tolist(),+ "image_size": [CAM_W, CAM_H]}+++# ------------------------------------------------------------------------------------------------- kinematics+KD = mujoco.MjData(M) # kinematics only: the trunk at the origin, level; never stepped+_FOOT = {f: M.site(f).id for f in FEET}+_LEG_DOF = {f: [6 + 3 * k + j for j in range(3)] for k, f in enumerate(FEET)} # actuator order = leg order = FEET+++def _fk_kd(q) -> None:+ KD.qpos[:] = 0.0+ KD.qpos[3] = 1.0+ KD.qpos[7:] = q+ mujoco.mj_kinematics(M, KD)+++def _foot_pose(f: str) -> list:+ quat = np.zeros(4)+ mujoco.mju_mat2Quat(quat, KD.site_xmat[_FOOT[f]])+ return [*KD.site_xpos[_FOOT[f]].tolist(), *quat.tolist()]+++def do_kinematics(req: dict) -> dict:+ """Feet in the trunk frame (the trunk body's origin and axes; x forward, y left, z up). IK solves positions only, one+ leg (3 joints) per foot target, damped least squares within the joint ranges; a foot's orientation is ignored."""+ if req["op"] == "fk":+ _fk_kd(np.asarray(req["q"]))+ return L.fk_response({f: _foot_pose(f) for f in req["links"]}, "trunk")+ q = np.array(req["seed"] if req["seed"] is not None else S.data.qpos[7:], dtype=np.float64)+ errors = {}+ jac = np.zeros((3, M.nv))+ for f, pose in req["targets"].items():+ tgt = np.asarray(pose[:3])+ idx = _LEG_DOF[f]+ for _ in range(req["max_iters"]):+ _fk_kd(q)+ err = tgt - KD.site_xpos[_FOOT[f]]+ if np.linalg.norm(err) < req["tol_pos_m"]:+ break+ mujoco.mj_jacSite(M, KD, jac, None, _FOOT[f])+ J = jac[:, idx]+ dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(3), err)+ q[[i - 6 for i in idx]] = np.clip(q[[i - 6 for i in idx]] + dq, S.lower[[i - 6 for i in idx]],+ S.upper[[i - 6 for i in idx]])+ _fk_kd(q)+ errors[f] = (float(np.linalg.norm(tgt - KD.site_xpos[_FOOT[f]])), 0.0)+ ok = all(e[0] <= req["tol_pos_m"] for e in errors.values())+ return L.ik_response(q, ok, errors, "trunk", note="feet: position only (a foot is a sphere; its orientation is ignored)")+++# ------------------------------------------------------------------------------------------------- spec+def schedule_text() -> list:+ if S.commands is None:+ return []+ return [{"from_s": round(int(c["start_step"]) * DT, 2), "vx_mps": round(c["vx"], 4), "vy_mps": round(c["vy"], 4),+ "wz_radps": round(c["wz"], 4)} for c in S.inst["commands"]]+++TASK_EPISODE = {+ "joystick": f"one episode, no reset: it ends after {S.horizon} control steps (the {S.horizon * DT:g} s command "+ f"schedule), when the robot meets its termination rule ({S.spec.get('term_text')}: a failure), when you "+ "submit `done`, or when your time is over",+ "getup": f"one episode, no reset: it ends the moment the robot has stood upright for {Q.HOLD_STEPS} control steps in a "+ f"row (success), after {S.horizon} control steps, when you submit `done`, or when your time is over",+ "stand_on_two": f"one episode, no reset: it ends the moment the pose has been held for {Q.POSE_HOLD_STEPS} control steps "+ "in a row (success), when the robot meets the termination rule (a failure: its trunk's up axis below "+ f"-0.25, or {'a leg' if S.spec.get('hind_leg_contact') else 'a front leg'}'s thigh, calf or hip on the "+ f"floor), after {S.horizon} control steps, when you "+ "submit `done`, or when your time is over",+}[S.kind]+_ctl = {"type": "joint position actuators (PD)", "kp_nm_per_rad": float(M.actuator_gainprm[0, 0]),+ "kd_nms_per_rad": float(M.dof_damping[6] - M.actuator_biasprm[0, 2])}+SPEC = {+ "protocol": L.PROTOCOL,+ "protocol_compat": list(L.COMPAT),+ "simulator": "MuJoCo 3.3.7 (MuJoCo Playground's scene, plain MuJoCo on the CPU)",+ "robot": S.robot["name"],+ "task_text": S.inst["text"],+ "control_hz": CTRL_HZ,+ "physics_substeps": SUBSTEPS,+ "max_chunk_s": MAX_CHUNK_S,+ "max_watch_s": MAX_WATCH_S,+ "cameras": {c: {"rgb": True, "depth": True, "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),+ **({"mounted": "follows the robot", "mount": {"type": "link", "link": S.robot["root"], "note":+ "follows the robot's centre of mass at a fixed offset; it does not turn with the robot"}}+ if int(M.cam_mode[M.camera(c).id]) != 0 else+ {"mounted": "on the robot's head", "mount": {"type": "link", "link": M.body(M.cam_bodyid[M.camera(c).id]).name+ or S.robot["root"], "note": "fixed to the robot: moves and turns with it"}})}+ for c in CAMS},+ "default_cameras": ["track"],+ "action_types": {+ "joint_position": {+ "dim": Q.N,+ "layout": S.joint_names,+ "limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "units": "rad",+ "semantics": "absolute targets of the 12 joint position actuators, one per control step (1/50 s); rows `dt` "+ "apart (a multiple of the control period, at most 0.5 s), `hold` or `linear` between rows; values "+ "outside the limits are clipped and reported",+ },+ "done": {"dim": 0, "layout": [], "semantics": 'ends the episode now, in the current state (no physics); r.submit("done", [])'},+ "not_yet": ["joint_velocity", "joint_torque", "joint_delta"],+ },+ "proprio_layout": PROPRIO_LAYOUT,+ "proprio_groups": PROPRIO_GROUPS,+ "static": {},+ "world": {"frame": "z up; the robot starts where the episode puts it (no world coordinates are given)", "up": "+z",+ "units": {"length": "m", "angle": "rad", "time": "s"}, "quaternion_order": "wxyz",+ "camera_axes": "intrinsic_cv / extrinsic_cv: OpenCV camera axes (x right, y down, z forward); cam2world_gl: OpenGL axes"},+ "budget": {"reset": 0, "steps": None, "wall_clock_s": WALL_CLOCK_S},+ "max_control_steps": S.horizon,+ "episode": TASK_EPISODE,+ "command_schedule": schedule_text(),+ **({"gait": {k: S.gait[k] for k in ("name", "frequency_hz", "foot_height_m", "phase0", "phase_dt")} | {+ "feet": FEET, "rule": "foot i's target height at control step t is get_rz(wrap(phase0[i] + t * phase_dt)) with "+ "Playground's gait.get_rz (a cubic Bezier from 0 up to foot_height_m over the first half of the phase, then "+ "down); phases in rad, wrapped to [-pi, pi)"}} if S.gait else {}),+ "robot_spec": {"name": S.robot["name"], "joints": S.joint_names, "joint_limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "joint_order": S.robot["joint_text"], "home_pose": dict(zip(S.joint_names, S.home.tolist())),+ "feet": FEET, "controller": _ctl},+ "kinematics": {"endpoint": "/kinematics", "joint_names": S.joint_names, "frame": "trunk", "quaternion_order": "wxyz",+ "links": FEET, "tcp_frames": [], "ee_frames": FEET, "ik_targets": FEET,+ "ik": {"tol_pos_m": 0.002, "tol_rot_rad": 3.2, "max_iters": 100},+ "note": "poses of the feet in the trunk frame (x forward, y left, z up, metres) for joint positions q; "+ "ik: one leg per foot, positions only"},+ "depth": {"modes": list(L.DEPTH_MODES), "default": "none", "kind": "z-depth", "unit": "m", "invalid": 0,+ "max_m": L.DEPTH_MAX_M, "frames_encoding": "uint16 mm, zlib", "noise": L.DEPTH_NOISE},+}+L.check_spec(SPEC) # a spec that misses a 2.2 field or names a forbidden one never starts the episode+EP.scene_built()++_RENDER = {}+++def _renderer():+ if "r" not in _RENDER:+ _RENDER["r"] = mujoco.Renderer(M, CAM_H, CAM_W)+ return _RENDER["r"]+++def ctrl_steps() -> int:+ return S.steps+++def proprio_row() -> np.ndarray:+ d = S.data+ return np.concatenate([d.qpos[7:], d.qvel[6:], d.actuator_force, S.sensor("gyro"), S.sensor("accelerometer"), S.gravity(),+ S.sensor("local_linvel"), S.foot_contacts()]).astype(np.float32)+++def grab(cams, want_depth: bool):+ r = _renderer()+ rgb, dep = {}, {}+ for c in cams:+ r.update_scene(S.data, camera=c)+ rgb[c] = r.render().copy()+ if want_depth:+ r.enable_depth_rendering()+ r.update_scene(S.data, camera=c)+ dep[c] = r.render().astype(np.float32).copy()+ r.disable_depth_rendering()+ return rgb, dep+++def extrinsics(cams) -> dict:+ return {c: np.asarray(camera_info(c)["extrinsic_cv"], dtype=np.float64) for c in cams}+++def write_final() -> None:+ if L.final_verdict(DATA): # finalize.sh's verdict, or a give-up after crashes: never overwritten+ return+ L._write_json(os.path.join(DATA, "final.json"), {**summary(), "finalized": False, "live_sha": E.get("live_sha")})+++def summary() -> dict:+ n = int(E.get("episode_control_steps") or ctrl_steps())+ chk = E.get("check") or {}+ return {"success": bool(E["success"]), "steps": E["step"], "calls": E["calls"], "control_steps": n,+ "physics_steps": n * SUBSTEPS, "elapsed_s": round((E.get("t_end") or time.time()) - E["t0"], 1),+ "reason": E["reason"], "done": E["done"], "env": S.env, "protocol": L.PROTOCOL, "n_actions": len(ROWS),+ "fell_at": chk.get("fell_at"), "worst_lin_err": chk.get("worst_lin_err"), "worst_yaw_err": chk.get("worst_yaw_err"),+ "tilt_deg": chk.get("tilt_deg"), "imu_height": chk.get("imu_height"), "pose_angle_deg": chk.get("pose_angle_deg"),+ **EP.final_fields()}+++def finish(reason: str) -> None:+ """The episode is over: the task's check on the steps executed, then the record for the collect hook."""+ if E["done"]:+ return+ E["done"] = True+ E["reason"] = reason+ E["t_end"] = time.time()+ E["episode_control_steps"] = ctrl_steps()+ try:+ chk = S.check()+ E["check"] = {k: v for k, v in chk.items() if k != "segments"}+ E["success"] = bool(chk["success"])+ except Exception: # noqa: BLE001+ traceback.print_exc()+ EP.log({"ev": "end", "reason": reason, "step": E["step"], "control_steps": ctrl_steps(), "success": bool(E["success"])})+ dump()+++def dump() -> None:+ if E.get("dumped"):+ return+ E["dumped"] = True+ E["live_sha"] = S.state_sha()+ np.savez(os.path.join(DATA, "trajectory.npz"), actions=np.asarray(ROWS, dtype=np.float64).reshape(-1, Q.N),+ env=S.env, action_layout=",".join(S.joint_names))+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})+ write_final()+++def after_step() -> None:+ if S.kind in ("joystick", "stand_on_two") and S.fell_at is not None:+ finish("fell")+ elif S.kind in ("getup", "stand_on_two") and S.check()["success"]:+ finish("success")+ elif S.done:+ finish("horizon")+++def ctrl_step(a, rec) -> bool:+ """One executed control step, journaled. True when the call must stop here."""+ S.step(a)+ ROWS.append(np.asarray(a, dtype=np.float64))+ stop = EP.journal(a)+ rec.tick()+ after_step()+ return E["done"] or stop+++def recorder(cams, fps: int, meta: dict) -> L.Recorder:+ return L.Recorder(cams, max(1, int(round(CTRL_HZ / max(1, fps)))), grab, proprio_row, extrinsics, ctrl_steps,+ depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+++def video_fps(meta: dict) -> int:+ fps = meta.get("video_fps")+ if fps is None:+ return 10+ if isinstance(fps, bool) or not isinstance(fps, (int, float)) or not (1 <= fps <= 50):+ raise ValueError("video_fps must be in [1, 50]")+ return int(fps)+++def cameras_of(meta: dict) -> list:+ cams = meta.get("cameras") or ["track"]+ bad = [c for c in cams if c not in CAMS]+ if bad:+ raise ValueError(f"unknown cameras {bad}; cameras: {CAMS}")+ return list(cams)+++def meta_common(cams) -> dict:+ n = ctrl_steps()+ out = {"step": E["step"], "calls": E["calls"], "control_steps": n, "physics_steps": n * SUBSTEPS,+ "sim_time_s": round(n * DT, 3), "time_s": round(time.time() - E["t0"], 2),+ "time_left_s": max(0.0, round(WALL_CLOCK_S - (time.time() - E["t0"]), 1)),+ "proprio": {"layout": PROPRIO_LAYOUT, "now": proprio_row().tolist()}, "done": E["done"], "reason": E["reason"],+ "cameras": {c: camera_info(c) for c in cams}}+ if S.kind == "joystick":+ out["command_now"] = dict(zip(("vx_mps", "vy_mps", "wz_radps"), S.command_now().round(4).tolist()))+ return out+++def do_submit(meta: dict, A: np.ndarray):+ typ = meta.get("type")+ if typ == "done":+ rec = recorder(cameras_of(meta), 5, meta)+ rec.tick(force=True, last=True) # every response carries the last frames+ E["calls"] += 1+ finish("done")+ return {**meta_common(cameras_of(meta)), "chunk_id": E["calls"], "type": typ, "executed_rows": 0, "ok": True}, rec.parts("none", 5)+ if typ != "joint_position":+ raise ValueError(f"type must be joint_position or done (not yet: {SPEC['action_types']['not_yet']})")+ dt = float(meta.get("dt", DT))+ interp = meta.get("interpolate", "linear")+ video = meta.get("video", "mp4")+ cams, fps = cameras_of(meta), video_fps(meta)+ k = dt / DT+ if A.ndim != 2 or A.shape[1] != Q.N:+ raise ValueError(f"joint_position actions must be (T, {Q.N}), got {list(A.shape)}")+ if not np.all(np.isfinite(A)):+ raise ValueError("actions contain NaN/inf")+ if not (math.isfinite(dt) and dt <= 0.5 + 1e-9 and round(k) >= 1 and abs(k - round(k)) < 1e-6):+ raise ValueError(f"dt must be a whole multiple of the {DT:g} s control period and at most 0.5 s; got {dt}")+ if A.shape[0] * dt > MAX_CHUNK_S + 1e-9:+ raise ValueError(f"chunk longer than max_chunk_s={MAX_CHUNK_S}: {A.shape[0]} rows x {dt} s")+ if interp not in ("hold", "linear"):+ raise ValueError("interpolate must be hold|linear")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, clipped = recorder(cams, fps, meta), []+ E["calls"] += 1+ step0, before = E["step"], ctrl_steps()+ rec.tick(force=True)+ prev = S.targets.copy()+ for ri, row in enumerate(A):+ E["step"] += 1+ target = np.clip(row, LIMITS[:, 0], LIMITS[:, 1])+ for j in np.flatnonzero(target != row)[:20]:+ clipped.append({"row": ri, "index": int(j), "reason": f"{S.joint_names[j]} limit [{LIMITS[j, 0]:g}, {LIMITS[j, 1]:g}]"})+ n = int(round(k))+ stop = False+ for s in range(1, n + 1):+ a = target if interp == "hold" else prev + (target - prev) * (s / n)+ if ctrl_step(a, rec):+ stop = True+ break+ prev = target+ if stop:+ break+ rec.tick(force=True, last=True)+ out = {**meta_common(cams), "chunk_id": E["calls"], "type": typ, "executed_rows": E["step"] - step0,+ "control_steps_chunk": ctrl_steps() - before, "physics_steps_chunk": (ctrl_steps() - before) * SUBSTEPS,+ "clipped": clipped[:200], "n_clipped": len(clipped), "plan": [], "ok": True}+ EP.log({"ev": "submit", "call": E["calls"], "rows": E["step"] - step0, "dt": dt, "interpolate": interp, "cameras": cams,+ "control_steps": ctrl_steps() - before, "n_clipped": len(clipped), "note": (meta.get("note") or "")[:500],+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video, fps)+++def do_observe(meta: dict):+ cams, fps = cameras_of(meta), video_fps(meta)+ seconds = float(meta.get("seconds", 0))+ video = meta.get("video", "frames")+ if not math.isfinite(seconds) or seconds < 0 or seconds > MAX_WATCH_S:+ raise ValueError(f"seconds must be in [0, {MAX_WATCH_S}]")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, before = recorder(cams, fps, meta), ctrl_steps()+ if seconds > 0 and not E["done"]:+ rec.tick(force=True)+ hold = S.targets.copy()+ for _ in range(int(round(seconds / DT))):+ if ctrl_step(hold, rec):+ break+ rec.tick(force=True, last=True)+ E["calls"] += 1+ out = {**meta_common(cams), "obs_id": E["calls"], "seconds": seconds, "control_steps_watch": ctrl_steps() - before,+ "physics_steps_watch": (ctrl_steps() - before) * SUBSTEPS, "ok": True}+ EP.log({"ev": "observe", "call": E["calls"], "seconds": seconds, "cameras": cams, "control_steps": ctrl_steps() - before,+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video if seconds > 0 else ("frames" if video == "mp4" else video), fps)+++def status() -> dict:+ return {"step": E["step"], "calls": E["calls"], "control_steps": ctrl_steps(), "done": E["done"], "reason": E["reason"],+ "elapsed_s": round(time.time() - E["t0"], 1)}+++def end_from_signal() -> None:+ """The collect hook's SIGUSR1: end the episode (the agent's time is over), dump it, exit so the replays can start."""+ with LOCK:+ E["exiting"] = True+ if not E["done"]:+ finish("timeout")+ EP.log({"ev": "exit", "reason": "collect hook: episode dumped"})+ if not os.path.exists(PID_FILE):+ open(PID_FILE, "w").write(str(os.getpid()))+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(0)+++def replay_row(row) -> None:+ """A journaled row during a resume."""+ S.step(row)+ ROWS.append(np.asarray(row, dtype=np.float64))+++EP.begin(state=E, step=replay_row, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, on_end=end_from_signal,+ start_event={"env": S.env, "seed": S.inst.get("seed"), "cameras": CAMS})+if E["done"]:+ dump() # resumed after the episode had ended: the record is rewritten from the replay+E["ready"] = True+write_final()+open(PID_FILE, "w").write(str(os.getpid()))+print(f"{L.PROTOCOL} MuJoCo Playground quadruped sim ready ({S.env}; startup {EP.n_startups}, resumes {EP.resumes})", flush=True)+L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics, status=status,+ on_submit_error=lambda exc: finish("error"), log=EP.log, episode=EP, state_sha=S.state_sha,+ proprio=proprio_row), port=int(os.environ.get("RCB_PORT", "8000")))diff --git a/tasks/mujoco_playground_go1_footstand-standard/instruction.md b/tasks/mujoco_playground_go1_footstand-standard/instruction.mdnew file mode 100644index 0000000000..5e41bf2e30--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/instruction.md@@ -0,0 +1,46 @@+# MuJoCo Playground · Go1Footstand — STANDARD MODE (robot as a service, eai-standard/2.2)++**Task:** Make the Unitree Go1 stand up on its hind legs, nose up, front legs in the air, and balance there for 2 s.++You control the Unitree Go1 quadruped — **as if it were real hardware** — in one episode of MuJoCo Playground's+`Go1Footstand` environment (plain MuJoCo 3.3.7 with Playground's scene, commit 4057c14). The simulator runs in a service you+cannot open. You get one client and one episode.++## The episode+The robot starts standing at Playground's `home` pose with a random base velocity (Playground's reset). You have 500 control steps (10 s).++## Rules (real-robot rules)+- **No reset.** One episode. You see four cameras that follow the robot (RGB, depth if you ask) and the robot's own+ sensors: joint positions, velocities and torques, the IMU (gyro, accelerometer, gravity's direction, the trunk's+ velocity), foot contacts. No world positions, no success check.+- **The episode ends** the moment the pose has been held for 100 control steps in a row (success), when the robot meets the termination rule (the trunk's up axis below -0.25 (z component of the IMU frame's z axis), or any part of a front leg other than its foot (thigh, calf, hip) touching the floor (Playground's rule as its code reads it), or the same for a hind leg (the list its Footstand sets up but never reads; without it, sitting on a hind hip would count): a failure), after 500 control steps (`spec["max_control_steps"]`), when you submit `done`, or when your time is up.+- **Success** is 100 control steps in a row (2 s) with the trunk's forward axis (the IMU frame's x axis) within 30 deg of straight up, the IMU at least 0.4 m above the floor, and the front (FR, FL) feet off the ground, without a termination before; judged after every control step.+- Your wall-clock budget is 3600 s from your start. Simulated time only advances with your commands (and+ `get_obs(seconds=...)`, which holds the current targets).+- Nothing to hand in: the service records the episode and grades it. Leave your script at `/app/output/gen.py`.+- **If the service crashes**, a call fails with a connection error: it restarts and resumes the SAME episode (never a+ reset) in the state after the last call it completed. `r.wait_ready()` waits for it; then check `r.status()`.+- Nothing is put into your context automatically: images come back as arrays in Python objects.++## Client (`/opt/tools/rcb_client.py`)+```python+from rcb_client import Robot+r = Robot() # connects (waits while the service starts)+spec = r.spec() # action types, limits, cameras, robot_spec (home pose, gains), kinematics+obs = r.get_obs() # obs.last[cam] -> uint8 (240, 320, 3); obs.meta["proprio"] {"layout", "now"}+res = r.submit("joint_position", A, dt=0.02) # A: (T, 12) rows dt apart; res.proprio (one row per frame), res.meta+obs = r.get_obs(seconds=1.0, video="mp4") # hold the current targets and watch for 1 s (max 30)+r.fk(q); r.ik({"FR": [x, y, z, 1, 0, 0, 0]}, seed=q) # feet in the trunk frame <-> joints (no physics)+r.submit("done", []) # end the episode now+r.status() # calls, control steps, done, reason, elapsed time+```+Cameras: `track`, `side`, `back`, `top` (they follow the robot); `spec["cameras"]` gives each one's mounting and intrinsics, and every response carries its pose. Proprioception (`spec["proprio_groups"]`): `joint_pos`, `joint_vel`, `joint_effort` (12 each, action+order), `imu_gyro`, `imu_accelerometer`, `imu_gravity`, `imu_linvel` (3 each, IMU frame: x forward, y left, z up),+`foot_contact` (FR, FL, RR, RL).++### `joint_position` (12)+FR, FL, RR, RL legs, each hip (abduction), thigh (hip pitch), calf (knee): absolute targets of the joint position actuators (rad; kp = 35 N m/rad, joint damping 0.5 N m s/rad).+Rows are `dt` apart (a whole multiple of the 0.02 s control period, at most 0.5 s), `interpolate="linear"` (default) or+`"hold"` between rows; a chunk covers at most 10 s; values outside the limits+(`spec["action_types"]["joint_position"]["limits"]`) are clipped and listed in `res.meta["clipped"]`. Feedback control+means short chunks: each response tells you where the robot is now.diff --git a/tasks/mujoco_playground_go1_footstand-standard/solution/oracle.npy b/tasks/mujoco_playground_go1_footstand-standard/solution/oracle.npynew file mode 100644index 0000000000..32569d8ff9Binary files /dev/null and b/tasks/mujoco_playground_go1_footstand-standard/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_go1_footstand-standard/solution/oracle_replay.py b/tasks/mujoco_playground_go1_footstand-standard/solution/oracle_replay.pynew file mode 100644index 0000000000..b6a9824592--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/solution/oracle_replay.py@@ -0,0 +1,42 @@+"""Oracle (standard mode): streams the reference rows (one per 1/50 s control step, `hold`) as `joint_position` chunks+through the client, the same interface an agent has. Uses no privileged information at run time; the service's recorded+trajectory is then exactly the privileged reference. If the service crashes it resumes the same episode+(spec["on_service_error"]): the oracle waits until it answers again and goes on from the control step it reports."""+import os+import sys+import time++import numpy as np+import requests++sys.path.insert(0, "/opt/tools")+from rcb_client import EpisodeOver, Robot # noqa: E402++Q = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy")).astype(np.float64)+r = Robot()+spec = r.spec()+dt = 1.0 / float(spec["control_hz"])+per_chunk = max(1, int(spec.get("max_chunk_s", 10) / dt + 1e-9))+print("spec:", spec["protocol"], "rows:", len(Q), flush=True)+t0, i = time.time(), 0+while i < len(Q):+ chunk = Q[i:i + per_chunk]+ try:+ res = r.submit("joint_position", chunk, dt=dt, interpolate="hold", cameras=["track"], video="none", note=f"oracle rows {i}+")+ except EpisodeOver as e:+ print("episode over:", e)+ break+ except requests.exceptions.RequestException as e: # the service crashed: it restarts and resumes the same episode+ print("service unreachable:", repr(e)[:200], "- waiting for it to resume", flush=True)+ st = r.wait_ready()+ n = int(st["control_steps"])+ if not i <= n <= i + len(chunk):+ raise SystemExit(f"resumed at control step {n}: outside the chunk in flight (rows {i}..{i + len(chunk)})")+ i = n+ continue+ n = int(res.meta["control_steps"])+ print(f"rows {i}..{n}: clipped={res.meta['n_clipped']} done={res.meta['done']} reason={res.meta['reason']}", flush=True)+ if res.meta["done"] or n <= i:+ break+ i = n+print("status:", r.status(), "wall %.0fs" % (time.time() - t0))diff --git a/tasks/mujoco_playground_go1_footstand-standard/solution/solve.sh b/tasks/mujoco_playground_go1_footstand-standard/solution/solve.shnew file mode 100755index 0000000000..ecb1f6c954--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/solution/solve.sh@@ -0,0 +1,8 @@+#!/bin/bash+# Oracle (standard mode): streams the reference trajectory's joint targets (solution/oracle.npy, one row per control step)+# as `joint_position` chunks through the client. Uses no privileged information at run time (only the pre-recorded+# targets); the service's recorded trajectory is then exactly the privileged reference.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_go1_footstand-standard/task.toml b/tasks/mujoco_playground_go1_footstand-standard/task.tomlnew file mode 100644index 0000000000..397568b8cb--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/task.toml@@ -0,0 +1,54 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = [+ { source = "/data/final.json", service = "sim" },+ { source = "/data/episode.jsonl", service = "sim" },+ { source = "/data/trajectory.npz", service = "sim" },+ { source = "/data/replay.mp4", service = "sim" },+ { source = "/data/server.log", service = "sim" }, # the service's own output (Harbor keeps none)+ { source = "/data/journal.f64", service = "sim" }, # crash recovery: every executed control step (float64 rows)+ { source = "/data/startups.jsonl", service = "sim" }, # crash recovery: one line per service start+ { source = "/data/replay1.log", service = "sim" }, # the collect hook's two fresh-process replays+ { source = "/data/replay2.log", service = "sim" },+ { source = "/data/replay3.log", service = "sim" }, # and its third, which renders replay.mp4+ "/app/output/",+]++[task]+name = "robot-coding-bench/mujoco_playground_go1_footstand-standard"+description = "STANDARD MODE (robot as a service, eai-standard/2.2): MuJoCo Playground Go1Footstand (Unitree Go1) on the same frozen instance as mujoco_playground_go1_footstand-privileged: Make the Unitree Go1 stand up on its hind legs, nose up, front legs in the air, and balance there for 2 s. The agent only gets a client: four cameras that follow the robot (RGB, optional depth), the robot's joints and IMU, joint position chunks at 50 Hz, the feet's kinematics; one episode, no reset, no world state; the sim service records the episode, replays it in fresh processes and grades it."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "unitree-go1", "quadruped", "locomotion", "stand_on_two", "code-as-policy", "trajectory", "standard-mode"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "unitree-go1"+family = "mujoco_playground/Go1Footstand"+mode = "standard"+protocol = "eai-standard/2.2"+oracle = "full"+instance_seed = 0+expert_time_estimate_hours = 4.0++[verifier]+timeout_sec = 600.0+environment_mode = "separate"+network_mode = "no-network"++[[verifier.collect]]+service = "sim"+command = "sh /srv/finalize.sh" # end + dump + exit the service, replay twice in fresh processes, write final.json, video+timeout_sec = 1200++[agent]+timeout_sec = 3600.0+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_go1_footstand-standard/tests/Dockerfile b/tasks/mujoco_playground_go1_footstand-standard/tests/Dockerfilenew file mode 100644index 0000000000..26bc699ebe--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/tests/Dockerfile@@ -0,0 +1,5 @@+# Separate verifier sandbox: grades the sim service's own artifacts; needs nothing but python (the shared client base).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY test.sh /tests/test.sh+COPY grade.py /tests/grade.py+RUN chmod +x /tests/test.shdiff --git a/tasks/mujoco_playground_go1_footstand-standard/tests/grade.py b/tasks/mujoco_playground_go1_footstand-standard/tests/grade.pynew file mode 100644index 0000000000..5b990bf458--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/tests/grade.py@@ -0,0 +1,64 @@+"""Standard-mode verifier (MuJoCo Playground quadrupeds): reads what the sim service (which the agent could not touch) wrote:+/data/final.json (live success, two fresh-process replays of the recorded trajectory, determinism, crash-recovery+fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, the+replays having started in the instance's t = 0 state. Numeric-only reward.json."""++import json, os, shutil++LOG = "/logs/verifier"+os.makedirs(LOG, exist_ok=True)+++def write(ok, out):+ open(f"{LOG}/reward.txt", "w").write("1\n" if ok else "0\n")+ json.dump(out, open(f"{LOG}/reward.json", "w"))+ print(out)+++p = "/data/final.json"+if not os.path.exists(p):+ write(False, {"success": 0, "missing_log": 1, "grader_error": 0, "infra_error": 0})+ raise SystemExit+d = json.load(open(p))+for f in ("replay.mp4", "trajectory.npz", "episode.jsonl"):+ if os.path.exists(f"/data/{f}"):+ shutil.copy(f"/data/{f}", f"{LOG}/{f}")+ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic"))+ok = ok and not d.get("instance_mismatch")+num = lambda k: float(d.get(k) or 0) # noqa: E731+write(+ ok,+ {+ "success": int(ok),+ "live_success": int(bool(d.get("success"))),+ "replay_success": int(bool(d.get("replay_success"))),+ "deterministic": int(bool(d.get("deterministic"))),+ "live_matches_replay": int(bool(d.get("live_matches_replay"))),+ "finalized": int(bool(d.get("finalized"))),+ "n_actions": int(d.get("n_actions") or 0),+ "sim_steps": int(d.get("control_steps") or 0),+ "physics_steps": int(d.get("physics_steps") or 0),+ "steps": int(d.get("steps") or 0),+ "elapsed_s": float(d.get("elapsed_s") or 0),+ "video_rendered": int(bool(d.get("video"))),+ "fell": int(d.get("fell_at") is not None),+ "worst_lin_err": float(d["worst_lin_err"]) if d.get("worst_lin_err") is not None else -1.0,+ "worst_yaw_err": float(d["worst_yaw_err"]) if d.get("worst_yaw_err") is not None else -1.0,+ "end_tilt_deg": float(d["tilt_deg"]) if d.get("tilt_deg") is not None else -1.0,+ "end_imu_height": float(d["imu_height"]) if d.get("imu_height") is not None else -1.0,+ "end_pose_angle_deg": float(d["pose_angle_deg"]) if d.get("pose_angle_deg") is not None else -1.0,+ # a replay process gave no result, or the image no longer builds the frozen start: not the agent's 0+ "grader_error": int(bool(d.get("replay_failed") or d.get("instance_mismatch"))),+ "instance_mismatch": int(bool(d.get("instance_mismatch"))),+ # an infrastructure failure, not the agent's (PROTOCOL §2.6): a give-up after crashes between calls or a failed+ # resume (docs/STANDARD_MODE_2_2.md §13), the service not ending its episode for the collect hook, a replay+ # process that gave no result, replays that did not start in the instance's t = 0 state+ "infra_error": int(bool(d.get("infra_error"))),+ "gave_up": int(bool(d.get("gave_up"))),+ "sim_error": int(d.get("reason") == "error"),+ "sim_startups": int(d.get("sim_startups") or 0),+ "resumes": int(d.get("resumes") or 0),+ "resume_state_mismatch": int(d.get("resume_state_mismatch") or 0),+ "resume_max_joint_dev": num("resume_max_joint_dev"),+ },+)diff --git a/tasks/mujoco_playground_go1_footstand-standard/tests/test.sh b/tasks/mujoco_playground_go1_footstand-standard/tests/test.shnew file mode 100755index 0000000000..bc608aa8b9--- /dev/null+++ b/tasks/mujoco_playground_go1_footstand-standard/tests/test.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Verifier (separate sandbox): the sim sidecar's artifacts were uploaded to /data by Harbor.+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)+mkdir -p /logs/verifier+python /tests/grade.py 2> /logs/verifier/grade.logdiff --git a/tasks/mujoco_playground_go1_getup-privileged/README.md b/tasks/mujoco_playground_go1_getup-privileged/README.mdnew file mode 100644index 0000000000..53baaa9edd--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-privileged/README.md@@ -0,0 +1,42 @@+# mujoco_playground_go1_getup-privileged++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | privileged |+| Twin | `mujoco_playground_go1_getup-standard` |+| Simulator / robot | `mujoco` / `unitree-go1` |+| Family / instance | `mujoco_playground/Go1Getup` / seed 5 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `Go1Getup` (Unitree Go1), rebuilt in plain MuJoCo from Playground's scene files: The Unitree Go1 has fallen over. Make it get up and stand upright at its standing height.+It starts lying with its trunk tilted 110 deg (Playground's random drop, then a 0.5 s settle) and has 6 s to stand upright at its standing height. The deliverable is one replayable trajectory of joint position targets+(`/app/output/trajectory.npz`, `(T, 12)`, 1 <= T <= 300).++## Difficulty+Recovery from a fall: the robot lies on its side or back and has to turn itself over with its legs and then stand up within 6 s, with the trunk, thighs and calves all in contact with the floor (full collisions). The motion is whole-body and contact-rich, and a turn that fails leaves it on its back. A trained policy reaches a level crouch easily; standing up from it at the right moment is the rest.++## Reference solution+A policy trained here on Playground's Go1Getup reward (PPO on the CPU, `scripts/mujoco-playground/train/`, not in the image) turns the robot belly-down and level; then the joint targets go linearly to the `home` pose in 1 s and hold until the check completes (`scripts/mujoco-playground/oracle.py`): upright after 136 control steps, IMU at 0.257 m. Replayed by `solution/solve.sh` (`solution/oracle.npy`, 136 rows); the rows are float32-exact, so the+standard twin's client executes the same targets. Re-verified by `scripts/mujoco-playground/select_instances.py`: two+fresh-process replays succeed and end in the same state.++## Verification+`tests/grade.py` in a separate sandbox without network: two replays, each in a fresh process, from the verifier's own+copy of the instance (`tests/instance.json`; the start state is checked against its hash on every load); pass iff both+succeed and end in the same state (`deterministic`). Oracle: success after 136 control steps. `nop`: no trajectory, reward 0.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml`; MuJoCo Menagerie @ 1b86ece (`unitree_go1`); simulated in MuJoCo 3.3.7 on the CPU |+| Instance | Playground's `reset` with `jax.random.PRNGKey(5)` (a drop; the 0.5 s settle runs in the task's own MuJoCo); chosen by `scripts/mujoco-playground/select_instances.py` (seed 5; skipped 0: tilted less than 90 degrees after the settle; 1: tilted less than 90 degrees after the settle; 2: not dropped (starts standing); 3: tilted less than 90 degrees after the settle; 4: not dropped (starts standing)) |+| Actions | 12 joint position targets per control step (0.02 s of simulated time); kp = 35 N m/rad, joint damping 0.5 N m s/rad |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py` from `scripts/mujoco-playground/instances/Go1Getup.json`+(`make_instances.py`, `select_instances.py`) and `scripts/mujoco-playground/oracles/Go1Getup.npy` (`oracle.py`).diff --git a/tasks/mujoco_playground_go1_getup-privileged/environment/Dockerfile b/tasks/mujoco_playground_go1_getup-privileged/environment/Dockerfilenew file mode 100644index 0000000000..7bdd7d2938--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-privileged/environment/Dockerfile@@ -0,0 +1,8 @@+# MuJoCo Playground quadruped task (privileged): plain MuJoCo with Playground's and Menagerie's assets+# (images/mujoco/prepare_assets.sh), the task's tooling and its frozen instance.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY instance.json /app/instance.json+COPY rcb_quadruped.py /opt/tools/rcb_quadruped.py+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_go1_getup-privileged/environment/instance.json b/tasks/mujoco_playground_go1_getup-privileged/environment/instance.jsonnew file mode 100644index 0000000000..094f52130b--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-privileged/environment/instance.json@@ -0,0 +1,68 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1Getup",+ "seed": 5,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 0.5,+ -0.6548677086830139,+ 0.061879757791757584,+ 0.69452303647995,+ -0.2914724051952362,+ -0.6954456567764282,+ -0.038879625499248505,+ -2.5283195972442627,+ -0.7643543481826782,+ 1.2582777738571167,+ -1.5951141119003296,+ 0.12876635789871216,+ 4.084576606750488,+ -1.8947221040725708,+ 0.6868290305137634,+ 0.7969384789466858,+ -2.1358203887939453+ ],+ "qvel0": [+ -0.41757500171661377,+ 0.08125269412994385,+ 0.36997389793395996,+ -0.26620352268218994,+ 0.33868932723999023,+ -0.43405938148498535,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "dropped": true,+ "text": "The Unitree Go1 has fallen over. Make it get up and stand upright at its standing height.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": -312.0,+ "start_tilt_deg": 110.0,+ "start_imu_height_m": 0.295,+ "reference_rows": 136,+ "reference_tilt_deg": 2.34,+ "reference_imu_height": 0.2568+ },+ "state_sha": "c59d44064135",+ "horizon": 300,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.",+ "candidates_tried": 6+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_go1_getup-privileged/environment/rcb_quadruped.py b/tasks/mujoco_playground_go1_getup-privileged/environment/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-privileged/environment/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_go1_getup-privileged/instruction.md b/tasks/mujoco_playground_go1_getup-privileged/instruction.mdnew file mode 100644index 0000000000..2147f86609--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-privileged/instruction.md@@ -0,0 +1,48 @@+# MuJoCo Playground · Go1Getup — frozen episode++**Task:** The Unitree Go1 has fallen over. Make it get up and stand upright at its standing height.++You control the Unitree Go1 quadruped in one episode of MuJoCo Playground's `Go1Getup` environment, rebuilt in plain+MuJoCo 3.3.7 from Playground's own scene files (Apache-2.0, commit 4057c14) and the robot from MuJoCo Menagerie. The+episode is frozen: it starts the same way after every reset (Playground's `reset` with seed 5), and you may reset+as often as you like. Your deliverable is **one open-loop trajectory**, not a general policy.++## The episode+Playground's reset dropped the robot from 0.5 m in a random orientation with random joint angles and a random base velocity, then let it settle for 0.5 s with its joints held: at t = 0 it lies with its trunk tilted 110 deg from upright. You have 300 control steps (6 s).++## Success+Success iff the trajectory (at most 300 rows) ends with 25 control steps in a row (0.5 s) after each of which the trunk is upright, tilted at most 10 deg (the angle between the IMU frame's z axis and world z), and the IMU is at least 0.22 m above the floor (the Go1 stands at 0.255-0.26 m; lying down is below 0.15 m). End the trajectory once that holds. `s.check()` reports the last tilt, height and `success`.++## Deliverable+`/app/output/trajectory.npz` with `actions`: float64 (T, 12), one row per control step (0.02 s): absolute targets of+the 12 joint position actuators, in `s.joint_names` order (FR, FL, RR, RL legs, each hip (abduction), thigh (hip pitch), calf (knee)), in radians; 1 <= T <= 300. Values+outside the actuator ranges (`s.lower`, `s.upper`) are clipped. `s.save_trajectory(rows)` writes it. Also leave the+script that produced it at `/app/output/gen.py`. Save a working trajectory as soon as you have one and overwrite it as+you improve it: whatever is in `/app/output/` when your 3600 s are up is graded. The tooling logs your sessions and+resets (cost accounting, not graded).++## Tooling (installed; `python` from any directory)+```python+from rcb_quadruped import Session+s = Session("/app/instance.json") # the frozen episode at t = 0 (checked against the instance's state hash)+s.joint_names; s.lower; s.upper # the actuator order and ranges (rad)+s.home # Playground's standing pose (its `home` keyframe), in that order+s.step(row) # one control step: 12 joint targets, 5 physics steps of 0.004 s; returns s.check()+s.check() # the task's check on the steps so far (see Success)+s.state() # qpos, qvel, IMU (local_linvel, gyro, gravity, accelerometer, pose), feet, contacts+s.sensor(name); s.gravity() # one MuJoCo sensor; gravity's direction in the IMU frame+s.model, s.data # the live MuJoCo model and data (read them; changing them is not part of the replay)+s.render(cam); s.cameras # uint8 (240, 320, 3) from cameras that follow the robot: `track`, `side`, `back`, `top` (they follow the robot)+s.reset() # back to t = 0+s.replay(rows) # reset, run the rows, return the check and the final state's hash+s.render_video(rows, "/app/output/try.mp4")+s.save_trajectory(rows, "/app/output/trajectory.npz")+```+The grader runs exactly this CLI in two fresh processes, so run it to check yourself:+`python /opt/tools/rcb_quadruped.py replay --instance /app/instance.json --traj /app/output/trajectory.npz`++## Conventions+- Joint position actuators (PD): kp = 35 N m/rad, joint damping 0.5 N m s/rad, as Playground's environment sets them; the physics step is 0.004 s,+ the control step 0.02 s (5 physics steps); a row holds until the next one.+- World frame z up, metres; quaternions **wxyz**. The IMU frame is the trunk's: x forward, y left, z up.+- Physics is MuJoCo on the CPU: the same rows from the same start give the same result in every fresh process.diff --git a/tasks/mujoco_playground_go1_getup-privileged/solution/oracle.npy b/tasks/mujoco_playground_go1_getup-privileged/solution/oracle.npynew file mode 100644index 0000000000..dc3c74e7b0Binary files /dev/null and b/tasks/mujoco_playground_go1_getup-privileged/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_go1_getup-privileged/solution/oracle_replay.py b/tasks/mujoco_playground_go1_getup-privileged/solution/oracle_replay.pynew file mode 100644index 0000000000..46987df1d0--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-privileged/solution/oracle_replay.py@@ -0,0 +1,15 @@+"""Oracle (privileged): replay the reference rows in the tooling, check them, and save them as the deliverable."""+import json+import os+import sys++import numpy as np++sys.path.insert(0, "/opt/tools")+from rcb_quadruped import Session # noqa: E402++rows = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy"))+s = Session("/app/instance.json")+r = s.replay(rows)+s.save_trajectory(rows, "/app/output/trajectory.npz", meta={"source": "reference trajectory (solution/oracle.npy)"})+print(json.dumps({k: v for k, v in r.items() if k != "segments"}))diff --git a/tasks/mujoco_playground_go1_getup-privileged/solution/solve.sh b/tasks/mujoco_playground_go1_getup-privileged/solution/solve.shnew file mode 100755index 0000000000..430ffb6017--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-privileged/solution/solve.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Oracle (privileged): write the reference trajectory frozen at generation time (solution/oracle.npy; how it was made:+# scripts/mujoco-playground/oracle.py) as the deliverable.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_go1_getup-privileged/task.toml b/tasks/mujoco_playground_go1_getup-privileged/task.tomlnew file mode 100644index 0000000000..bdfa783b62--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-privileged/task.toml@@ -0,0 +1,43 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = ["/app/output/", "/logs/agent/rcb/"]++[task]+name = "robot-coding-bench/mujoco_playground_go1_getup-privileged"+description = "MuJoCo Playground Go1Getup in plain MuJoCo (Unitree Go1, joint position control every 0.02 s): The Unitree Go1 has fallen over. Make it get up and stand upright at its standing height. Produce one replayable trajectory of joint position targets on a frozen instance (Playground's reset with seed 5); graded by an upright stance held for the trajectory's last 0.5 s (two fresh-process replays)."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "unitree-go1", "quadruped", "locomotion", "getup", "code-as-policy", "trajectory", "privileged"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "unitree-go1"+family = "mujoco_playground/Go1Getup"+mode = "privileged"+oracle = "full"+instance_seed = 5 # the PRNGKey of Playground's reset (and, for the joystick tasks, its command process)+expert_time_estimate_hours = 2.0++[verifier]+timeout_sec = 1200.0+environment_mode = "separate"+network_mode = "no-network"++[verifier.environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192++[agent]+timeout_sec = 3600.0+# MuJoCo Playground's trained policies are public upstream, so the agent reaches the model APIs and nothing else+# (scripts/set_agent_egress.py HOSTS).+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_go1_getup-privileged/tests/Dockerfile b/tasks/mujoco_playground_go1_getup-privileged/tests/Dockerfilenew file mode 100644index 0000000000..f49c79154d--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-privileged/tests/Dockerfile@@ -0,0 +1,7 @@+# Separate verifier sandbox (PROTOCOL §4): the same image with the verifier's own copies of the tooling and the frozen+# instance. Nothing the agent did in its container reaches this one: Harbor uploads only the declared artifacts.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY grade.py instance.json rcb_quadruped.py test.sh /tests/+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier+ENV PYTHONPATH=/tests+WORKDIR /testsdiff --git a/tasks/mujoco_playground_go1_getup-privileged/tests/grade.py b/tasks/mujoco_playground_go1_getup-privileged/tests/grade.pynew file mode 100644index 0000000000..e5668de85f--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-privileged/tests/grade.py@@ -0,0 +1,126 @@+"""Verifier (privileged): replay /app/output/trajectory.npz from the frozen instance and write Harbor's rewards.++ python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz++Two replays, each in its own fresh process (`rcb_quadruped.py replay`: the frozen start, one control step per row, the+task's success check on the whole trajectory). success = both replays succeed and end in the same state. Writes+/logs/verifier/reward.txt (1/0) and reward.json (numbers only); then a third replay renders replay.mp4, after the+verdict is on disk (it never changes it).+"""+import argparse+import json+import os+import subprocess+import sys+import tempfile+import traceback++import numpy as np++LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")+TOOL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_quadruped.py")+REPLAY_TIMEOUT_S = 300 # a 1000-step replay takes a few seconds; the video replay renders 4 views every 2nd step+++def write(ok: bool, out: dict) -> None:+ os.makedirs(LOG_DIR, exist_ok=True)+ open(os.path.join(LOG_DIR, "reward.txt"), "w").write("1\n" if ok else "0\n")+ json.dump(out, open(os.path.join(LOG_DIR, "reward.json"), "w"))+ print(json.dumps(out), flush=True)+++def agent_cost() -> dict:+ """Self-reported cost from the tooling's log in the agent's container (accounting, not evidence)."""+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_replays": 0, "agent_cost_self_reported": 1}+ for path in ("/logs/agent/rcb/rcb_session_log.jsonl", "/app/output/rcb_session_log.jsonl"):+ if not os.path.exists(path):+ continue+ try:+ with open(path) as f:+ for i, line in enumerate(f):+ if i > 200_000 or len(line) > 10_000:+ break+ try:+ e = json.loads(line)+ ev = e.get("ev") if isinstance(e, dict) else None+ if ev == "session_start":+ cost["agent_sessions"] += 1+ elif ev == "reset":+ cost["agent_resets"] += 1+ elif ev == "replay":+ cost["agent_replays"] += 1+ elif ev == "session_end":+ cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)+ except Exception: # noqa: BLE001 -- one bad line must not sink the verdict+ continue+ except OSError:+ pass+ break+ return cost+++def replay(instance: str, traj: str, video: str | None) -> dict:+ """One replay in a fresh process; its result (`--out`), or {"error": ...}."""+ with tempfile.NamedTemporaryFile(suffix=".json") as out:+ cmd = [sys.executable, TOOL, "replay", "--instance", instance, "--traj", traj, "--out", out.name]+ try:+ p = subprocess.run(cmd + (["--video", video] if video else []), stdout=subprocess.DEVNULL, stderr=sys.stderr,+ timeout=REPLAY_TIMEOUT_S, env={**os.environ, "RCB_SESSION_LOG": "", "RCB_AGENT_TRACE_DIR": ""})+ except subprocess.TimeoutExpired:+ return {"error": f"replay took over {REPLAY_TIMEOUT_S} s"}+ try:+ return json.load(open(out.name))+ except ValueError:+ return {"error": f"replay process rc={p.returncode}"}+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--instance", required=True)+ ap.add_argument("--traj", default="/app/output/trajectory.npz")+ a = ap.parse_args()+ cost = agent_cost()+ if not os.path.isfile(a.traj):+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost})+ return 0+ try:+ horizon = int(json.load(open(a.instance))["horizon"])+ d = np.load(a.traj, allow_pickle=False)+ acts = np.asarray(d["actions"], dtype=np.float64) if "actions" in d.files else np.zeros((0, 0))+ if acts.ndim != 2 or acts.shape[1] != 12 or len(acts) > horizon or not np.all(np.isfinite(acts)):+ write(False, {"success": 0, "bad_trajectory": 1, "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0,+ "grader_error": 0, **cost})+ return 0+ runs = [replay(a.instance, a.traj, None), replay(a.instance, a.traj, None)]+ if any("error" in r and not r.get("bad_trajectory") for r in runs):+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ if not all(r.get("instance_ok") for r in runs): # the image no longer builds the frozen start: not the agent's 0+ write(False, {"success": 0, "grader_error": 1, "instance_mismatch": 1, **cost})+ return 0+ all_success = all(bool(r.get("success")) for r in runs)+ deterministic = runs[0].get("state_sha") == runs[1].get("state_sha")+ ok = all_success and deterministic+ r = runs[0]+ num = lambda k: float(r.get(k) if r.get(k) is not None else -1) # noqa: E731+ out = {"success": int(ok), "replay_success": int(all_success), "deterministic": int(deterministic),+ "n_actions": int(len(acts)), "horizon": horizon, "fell": int(r.get("fell_at") is not None),+ "fell_at_step": num("fell_at"), "worst_lin_err": num("worst_lin_err"), "worst_yaw_err": num("worst_yaw_err"),+ "end_tilt_deg": num("tilt_deg"), "end_imu_height": num("imu_height"), "end_pose_angle_deg": num("pose_angle_deg"),+ "grader_error": 0,+ "video_rendered": 0, **cost}+ write(ok, out) # the verdict, before any video+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ try: # the video, for humans: it never changes the verdict+ if replay(a.instance, a.traj, os.path.join(LOG_DIR, "replay.mp4")).get("video"):+ write(ok, {**out, "video_rendered": 1})+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/mujoco_playground_go1_getup-privileged/tests/instance.json b/tasks/mujoco_playground_go1_getup-privileged/tests/instance.jsonnew file mode 100644index 0000000000..094f52130b--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-privileged/tests/instance.json@@ -0,0 +1,68 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1Getup",+ "seed": 5,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 0.5,+ -0.6548677086830139,+ 0.061879757791757584,+ 0.69452303647995,+ -0.2914724051952362,+ -0.6954456567764282,+ -0.038879625499248505,+ -2.5283195972442627,+ -0.7643543481826782,+ 1.2582777738571167,+ -1.5951141119003296,+ 0.12876635789871216,+ 4.084576606750488,+ -1.8947221040725708,+ 0.6868290305137634,+ 0.7969384789466858,+ -2.1358203887939453+ ],+ "qvel0": [+ -0.41757500171661377,+ 0.08125269412994385,+ 0.36997389793395996,+ -0.26620352268218994,+ 0.33868932723999023,+ -0.43405938148498535,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "dropped": true,+ "text": "The Unitree Go1 has fallen over. Make it get up and stand upright at its standing height.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": -312.0,+ "start_tilt_deg": 110.0,+ "start_imu_height_m": 0.295,+ "reference_rows": 136,+ "reference_tilt_deg": 2.34,+ "reference_imu_height": 0.2568+ },+ "state_sha": "c59d44064135",+ "horizon": 300,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.",+ "candidates_tried": 6+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_go1_getup-privileged/tests/rcb_quadruped.py b/tasks/mujoco_playground_go1_getup-privileged/tests/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-privileged/tests/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_go1_getup-privileged/tests/test.sh b/tasks/mujoco_playground_go1_getup-privileged/tests/test.shnew file mode 100755index 0000000000..1c3d2f767b--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-privileged/tests/test.sh@@ -0,0 +1,9 @@+#!/bin/bash+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in two fresh processes (the+# verdict), then a third that renders replay.mp4.+# Writes /logs/verifier/reward.txt (1/0) and reward.json (numeric fields, docs/PROTOCOL.md §2.6).+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/*+mkdir -p /logs/verifier+python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz 2> /logs/verifier/grade.logdiff --git a/tasks/mujoco_playground_go1_getup-standard/README.md b/tasks/mujoco_playground_go1_getup-standard/README.mdnew file mode 100644index 0000000000..4ceb0682c5--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/README.md@@ -0,0 +1,44 @@+# mujoco_playground_go1_getup-standard++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | standard (`eai-standard/2.2`) |+| Twin | `mujoco_playground_go1_getup-privileged` |+| Simulator / robot | `mujoco` / `unitree-go1` |+| Family / instance | `mujoco_playground/Go1Getup` / seed 5 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `Go1Getup` (Unitree Go1) on the same frozen instance as `mujoco_playground_go1_getup-privileged`: The Unitree Go1 has fallen over. Make it get up and stand upright at its standing height.+It starts lying with its trunk tilted 110 deg (Playground's random drop, then a 0.5 s settle) and has 6 s to stand upright at its standing height. Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with only+the robot's own sensors and four cameras that follow it.++## Difficulty+Same instance and success check as `mujoco_playground_go1_getup-privileged`. In standard mode the agent loses resets, the simulator and+the world state: it sees camera images and proprioception (joints, IMU, foot contacts), acts in joint position chunks,+and gets one episode, so it has to close the loop on the robot's own sensors and recover from its own mistakes without+starting over.++## Reference solution+`solution/oracle_replay.py` streams the privileged reference's rows (`solution/oracle.npy`, 136 rows, float32-exact)+through the client in `hold` chunks; it uses no privileged information at run time. The service's recorded trajectory+is then exactly the privileged reference, and the episode ends with success after 136 control steps.++## Verification+The sim service judges the episode live and records every executed control step; the collect hook+(`environment/sim/finalize.sh`) ends the service, replays the recorded trajectory in two fresh processes and writes+`final.json`; `tests/grade.py` (separate sandbox, no network) passes iff the live check succeeded, both replays succeed,+and they end in the same state. Oracle: success after 136 control steps.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml`; MuJoCo Menagerie @ 1b86ece (`unitree_go1`); MuJoCo 3.3.7 on the CPU |+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); cameras `track`, `side`, `back`, `top` (they follow the robot) (320 x 240), the feet's kinematics in the trunk frame |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py`, as its privileged twin.diff --git a/tasks/mujoco_playground_go1_getup-standard/environment/Dockerfile b/tasks/mujoco_playground_go1_getup-standard/environment/Dockerfilenew file mode 100644index 0000000000..ed5eee3703--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/environment/Dockerfile@@ -0,0 +1,9 @@+# Standard mode: the agent container has NO simulator and no Playground code, only Python and the client, on the shared+# pinned client base with the shared pins (scripts/eai_standard/client.env, client-requirements.txt).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY client-requirements.txt /tmp/client-requirements.txt+RUN pip install --no-cache-dir -r /tmp/client-requirements.txt+COPY rcb_client.py rcb1.py /opt/tools/+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_go1_getup-standard/environment/client-requirements.txt b/tasks/mujoco_playground_go1_getup-standard/environment/client-requirements.txtnew file mode 100644index 0000000000..8aa73a968f--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/environment/client-requirements.txt@@ -0,0 +1,11 @@+# Exact pins for what the standard agent container installs (and a verifier, if it installs anything): the closure of+# `pip install requests numpy pillow scipy`, the unpinned line of every standard task at 9eb18edf, resolved on+# 2026-10-01 in CLIENT_IMAGE (client.env: Python 3.12.14, pip 25.0.1). A change here is a shared-files PR.+certifi==2026.7.22+charset-normalizer==3.5.2+idna==3.20+numpy==2.5.3+pillow==12.3.0+requests==2.34.2+scipy==1.18.1+urllib3==2.8.0diff --git a/tasks/mujoco_playground_go1_getup-standard/environment/docker-compose.yaml b/tasks/mujoco_playground_go1_getup-standard/environment/docker-compose.yamlnew file mode 100644index 0000000000..8ec63c582e--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/environment/docker-compose.yaml@@ -0,0 +1,23 @@+# Standard mode: the simulator runs in the `sim` sidecar (the agent cannot open it); the agent only reaches port 8000.+# No `expose`/`ports` on sim: under Harbor's egress control it shares main's network namespace (localhost:8000).+# CPU only: MuJoCo physics and rendering (EGL when a GPU is there, else OSMesa); no GPU reservation.+# Crash recovery (docs/STANDARD_MODE_2_2.md §13): run.sh exits non-zero when the service crashes, compose restarts the+# container (same container, same /data) and the service replays its journal into the same episode, never a reset.+services:+ main:+ depends_on: [sim]+ sim:+ image: ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+ volumes:+ - ./sim:/srv:ro+ working_dir: /tmp+ command: sh /srv/run.sh+ restart: on-failure:6 # N >= 3 (PROTOCOL §4.1); a resume continues the episode+ environment:+ RCB_INSTANCE: /srv/instance.json+ RCB_TOOL: /srv/rcb_quadruped.py+ RCB_DATA: /data+ RCB_WALL_CLOCK_S: "3600"+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in about a second+ PYTHONPATH: /srv+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction logdiff --git a/tasks/mujoco_playground_go1_getup-standard/environment/rcb1.py b/tasks/mujoco_playground_go1_getup-standard/environment/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/environment/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_go1_getup-standard/environment/rcb_client.py b/tasks/mujoco_playground_go1_getup-standard/environment/rcb_client.pynew file mode 100644index 0000000000..aa25b0e050--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/environment/rcb_client.py@@ -0,0 +1,211 @@+"""eai-standard/2.2 client (formerly rcb-limited/2.x) — the only thing a standard-mode agent gets (installed at+/opt/tools/rcb_client.py).++ from rcb_client import Robot+ r = Robot() # finds the service (sim:8000, then localhost:8000), waits for warm-up+ spec = r.spec() # actions, cameras (+ intrinsics, mounting), robot_spec, world, budget, kinematics+ obs = r.get_obs() # current frames: obs.last[cam] -> uint8 (H,W,3); obs.meta["proprio"]+ obs = r.get_obs(depth=True) # + obs.last_depth[cam] -> float32 (H,W) z-depth in metres, 0 = no reading+ res = r.submit("joint_position", A, dt=0.1) # A: (T, dim) rows dt apart; returns the execution video+ res = r.submit("ee_pose", P) # (T, dim) end-effector targets (see spec()["action_types"])+ res.video[cam] -> mp4 bytes res.frames[cam] -> uint8 (N,H,W,3) if video="frames"/"both" res.last[cam]+ res.proprio -> float32 (N, D), one row per frame (names: spec()["proprio_layout"]; res.group("tcp_pose"))+ res.frame_step -> int64 (N,) control step of each frame res.frame_time_s -> float64 (N,) simulated time+ res.extrinsic_cv[cam] -> float64 (N,3,4) world->camera per frame (res.meta["cameras"]: intrinsics + the last frame's pose)+ res = r.submit(..., depth="frames") # + res.depth[cam] -> float32 (N,H,W) metres, one per frame (1 mm steps)+ r.fk(q) # {"ok", "poses": {frame: [x,y,z, quaternion]}}: forward kinematics, no physics+ r.ik({frame: pose}, seed=q) # {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}: inverse kinematics+ res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, frames/<cam>/NNN.jpg, proprio.npy, depth, frame_meta.npz+ obs = r.get_obs(seconds=3, video="both") # hold the last command, let physics run 3 s, return the video+ r.status() # calls, control steps, done, reason, elapsed time++Nothing is put into your context automatically: what you look at, and where you store it, is your code's decision.++If a call fails with a connection error or a 5xx, the service may have crashed; it restarts and resumes the SAME episode+(never a reset) in the state after the last call it completed, which you may not have received. r.wait_ready() waits+until it answers again (resuming replays the episode so far: long episodes can take minutes); then check r.status()+before you continue (spec()["on_service_error"]).+"""+from __future__ import annotations+import json, os, pathlib, sys, time, zlib+import numpy as np+import requests+import rcb1++PROTOCOL = "eai-standard/2.2" # also talks to 2.0 / 2.1 services (they ignore depth and send no frame metadata)+ACCEPTED = ("eai-standard/2.", "rcb-limited/2.") # every 2.x service, under the protocol's current and former name+++class EpisodeOver(RuntimeError):+ pass+++def _decode_depth_frames(p: dict) -> np.ndarray:+ a = np.frombuffer(zlib.decompress(p["data"]), dtype="<u2").reshape(p["shape"])+ return a.astype(np.float32) / 1000.0+++class Result:+ """Decoded RCB1 response: meta (dict), video (cam -> mp4 bytes), frames (cam -> uint8 (N,H,W,3)), last (cam -> uint8+ (H,W,3)), last_depth (cam -> float32 (H,W) m), depth (cam -> float32 (N,H,W) m, one per frame), proprio (float32 (N,D)),+ frame_step (int64 (N,)), frame_time_s (float64 (N,)), extrinsic_cv (cam -> float64 (N,3,4)). save(dir) writes it out;+ show(cam, k) returns one frame; group(name) the proprio columns of one spec()["proprio_groups"] group. stopped: None,+ or why the service stopped the call early ("max_call_wall_s": it ran longer than spec()["max_call_wall_s"]); then+ meta["executed_rows"] < the rows sent, and meta["proprio"]["now"] is where the robot is."""+ def __init__(self, meta: dict, parts: dict, spec: dict | None = None):+ self.meta = meta; self.raw = parts; self._spec = spec or {}; self.stopped = meta.get("stopped")+ self.video, self.frames, self.last, self.last_depth, self.depth, self.extrinsic_cv = {}, {}, {}, {}, {}, {}+ self.proprio = None; self.frame_step = None; self.frame_time_s = None+ for name, p in parts.items():+ kind, data = p["kind"], p["data"]+ if name.startswith("video/") and kind == "mp4": self.video[name[6:]] = data+ elif name.startswith("frames/") and kind == "array": self.frames[name[7:]] = data+ elif name.startswith("last/") and kind == "array": self.last[name[5:]] = data+ elif name.startswith("last_depth/") and kind == "array": self.last_depth[name[11:]] = np.asarray(data, dtype=np.float32)+ elif name.startswith("depth_frames/") and p.get("codec") == "zlib": self.depth[name[13:]] = _decode_depth_frames(p)+ elif name.startswith("depth/") and kind == "array": self.depth[name[6:]] = np.asarray(data, dtype=np.float32) # 2.1 form+ elif name.startswith("extrinsic_cv/") and kind == "array": self.extrinsic_cv[name[13:]] = data+ elif name == "proprio": self.proprio = data+ elif name == "frame_step": self.frame_step = data+ elif name == "frame_time_s": self.frame_time_s = data++ @property+ def done(self) -> bool: return bool(self.meta.get("done"))++ def show(self, camera: str, k: int = -1) -> np.ndarray:+ if camera in self.frames: return self.frames[camera][k]+ return self.last[camera]++ def group(self, name: str, now: bool = False) -> np.ndarray:+ """Columns of proprio group `name` (spec()["proprio_groups"]): (N, n) over the frames, or (n,) of meta["proprio"]["now"]."""+ first, n = self._spec["proprio_groups"][name][:2]+ if now: return np.asarray(self.meta["proprio"]["now"], dtype=np.float64)[first:first + n]+ return self.proprio[:, first:first + n]++ def save(self, out_dir: str) -> str:+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ (out / "meta.json").write_text(json.dumps(self.meta, indent=1))+ for cam, b in self.video.items(): (out / f"{cam}.mp4").write_bytes(b)+ try:+ from PIL import Image+ for cam, img in self.last.items():+ (out / "last").mkdir(exist_ok=True); Image.fromarray(np.ascontiguousarray(img)).save(out / "last" / f"{cam}.jpg", quality=90)+ for cam, arr in self.frames.items():+ d = out / "frames" / cam; d.mkdir(parents=True, exist_ok=True)+ for i, f in enumerate(arr): Image.fromarray(np.ascontiguousarray(f)).save(d / f"{i:03d}.jpg", quality=85)+ except ImportError:+ for cam, img in self.last.items(): np.save(out / f"last_{cam}.npy", img)+ for cam, arr in self.frames.items(): np.save(out / f"frames_{cam}.npy", arr)+ for cam, arr in self.last_depth.items(): np.save(out / f"last_depth_{cam}.npy", arr)+ for cam, arr in self.depth.items(): np.savez_compressed(out / f"depth_{cam}.npz", depth_mm=np.rint(arr * 1000).astype(np.uint16))+ if self.proprio is not None: np.save(out / "proprio.npy", self.proprio)+ if self.frame_step is not None:+ np.savez(out / "frame_meta.npz", frame_step=self.frame_step, frame_time_s=self.frame_time_s,+ **{f"extrinsic_cv/{c}": e for c, e in self.extrinsic_cv.items()})+ return str(out)+++class Robot:+ def __init__(self, base: str | None = None, timeout: float = 600.0):+ cands = [base or os.environ.get("SIM_URL"), "http://sim:8000", "http://localhost:8000"]+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ for b in [c for c in cands if c]:+ try:+ r = requests.get(b + "/spec", timeout=(5, 30))+ if r.status_code == 503: last = "warming up"; break+ r.raise_for_status(); self.base = b; self._spec = r.json()+ if not str(self._spec.get("protocol", "")).startswith(ACCEPTED):+ raise RuntimeError(f"not a 2.x service: protocol {self._spec.get('protocol')!r}")+ return+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(2)+ raise RuntimeError(f"sim service unavailable: {last}")++ def spec(self) -> dict:+ return self._spec++ def _post(self, path: str, meta: dict, parts: list, timeout: float) -> Result:+ body = rcb1.encode(meta, parts)+ r = requests.post(self.base + path, data=body, headers={"Content-Type": "application/x-rcb1"}, timeout=(5, timeout))+ if r.status_code == 409:+ raise EpisodeOver(r.json().get("reason") if r.headers.get("Content-Type", "").startswith("application/json") else "episode finished")+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ m, p = rcb1.decode(r.content); return Result(m, p, self._spec)++ def _common(self, cameras, video_fps, depth, include_depth) -> dict:+ cams = list(cameras) if cameras is not None else self._spec.get("default_cameras")+ if depth is None or depth is False: depth = "frames" if include_depth else "none"+ elif depth is True: depth = "last"+ m = {"cameras": cams, "video_fps": None if video_fps is None else int(video_fps), "depth": depth}+ return {k: v for k, v in m.items() if v is not None}++ def submit(self, action_type: str, actions, dt: float | None = None, interpolate: str = "linear", cameras=None,+ video_fps: int | None = None, video: str = "mp4", depth=None, include_depth: bool = False, note: str = "") -> Result:+ """Execute a chunk of low-level actions (T, dim); see spec()['action_types'] for dims, layouts, limits and semantics.+ dt defaults to one control period, cameras to spec()['default_cameras']; depth: None | True (= "last") | "frames"."""+ a = np.asarray(actions, dtype=np.float32)+ if a.ndim == 1: a = a[None, :]+ if dt is None and self._spec.get("control_hz"): dt = 1.0 / float(self._spec["control_hz"])+ meta = {"type": action_type, "interpolate": interpolate, "video": video, "note": note,+ **({} if dt is None else {"dt": float(dt)}), **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/submit", meta, [rcb1.array_part("actions", a)], timeout=1800)+ if res.stopped:+ print(f"[rcb_client] the service stopped this call early ({res.stopped}): {res.meta.get('executed_rows')} of {len(a)} rows "+ "executed; meta['proprio']['now'] is where the robot is", file=sys.stderr)+ return res++ def get_obs(self, cameras=None, seconds: float = 0.0, video_fps: int | None = None, depth=None, include_depth: bool = False,+ video: str = "frames") -> Result:+ """Current frames (seconds=0, free) or hold the last command and watch for `seconds` (returns the video).+ depth: None | True (= "last": the last frame's depth) | "frames" (one depth map per frame)."""+ meta = {"seconds": float(seconds), "video": video, **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/observe", meta, [], timeout=600)+ if res.stopped:+ print(f"[rcb_client] the service stopped this watch early ({res.stopped}) after {res.meta.get('control_steps_watch')} control "+ "steps", file=sys.stderr)+ return res++ def status(self) -> dict:+ r = requests.get(self.base + "/status", timeout=(5, 60)); r.raise_for_status(); return r.json()++ def wait_ready(self, timeout: float = 3600.0) -> dict:+ """After a connection error: wait until the service answers GET /status again (it resumes the same episode after a+ crash), then return the status. Raises RuntimeError after `timeout` seconds."""+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ try:+ return self.status()+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(5)+ raise RuntimeError(f"sim service did not come back within {timeout:.0f} s: {last}")++ def kinematics(self, body: dict) -> dict:+ """POST /kinematics (stateless: never moves the robot, never advances time). Raises ValueError on a bad request."""+ r = requests.post(self.base + "/kinematics", json=body, timeout=(5, 120))+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ return r.json()++ def fk(self, q, links=None, base_pose=None) -> dict:+ """Forward kinematics: q in spec()['kinematics']['joint_names'] order -> {"ok", "frame", "poses": {link: [x,y,z, quat]}}+ (quaternion order spec()['world']['quaternion_order']; a mobile robot answers in its base frame unless base_pose is given)."""+ body = {"op": "fk", "q": [float(v) for v in np.asarray(q).reshape(-1)]}+ if links is not None: body["links"] = list(links)+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)++ def ik(self, targets: dict, seed=None, base_pose=None, **opts) -> dict:+ """Inverse kinematics: {frame: [x,y,z, quat]} (frames from spec()['kinematics']['ik_targets']) and an optional seed q ->+ {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}. opts: tol_pos_m, tol_rot_rad, max_iters."""+ body = {"op": "ik", "targets": {k: [float(v) for v in p] for k, p in targets.items()}, **opts}+ if seed is not None: body["seed"] = [float(v) for v in np.asarray(seed).reshape(-1)]+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)diff --git a/tasks/mujoco_playground_go1_getup-standard/environment/sim/finalize.sh b/tasks/mujoco_playground_go1_getup-standard/environment/sim/finalize.shnew file mode 100755index 0000000000..02048ddc74--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/environment/sim/finalize.sh@@ -0,0 +1,80 @@+#!/bin/sh+# [[verifier.collect]] hook, run inside the `sim` sidecar once Harbor has stopped the agent's container.+# 1. `rcb_limited.py end` (docs/STANDARD_MODE_2_2.md §13.3): SIGUSR1 to the service, which ends the episode if the+# agent had not (reason "timeout"), writes trajectory.npz + episode.json (live verdict, final-state hash) and exits.+# It exits 2 when final.json already holds the verdict (the service gave up after crashes): that verdict stays.+# 2. replay the trajectory from the frozen instance in TWO fresh processes (`rcb_quadruped.py replay`, the privileged+# verifier's replay): determinism = fresh process == fresh process; live_matches_replay = live == replay.+# 3. merge everything into final.json, the only thing the verifier sandbox grades;+# 4. a third replay renders replay.mp4, after the verdict is on disk (it never changes it).+set -u+DATA="${RCB_DATA:-/data}"; TOOL="${RCB_TOOL:?}"; INSTANCE="${RCB_INSTANCE:?}"+python /srv/rcb_limited.py end "$DATA" --timeout "${RCB_COLLECT_END_TIMEOUT_S:-900}"; rc=$?+if [ "$rc" = 2 ]; then+ echo "[finalize] final.json already holds the verdict; no replay"; exit 0+fi+if [ "$rc" != 0 ]; then+ echo "[finalize] the service did not end and dump the episode in time (rc $rc): an infrastructure failure"+ python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data"); p = os.path.join(d, "final.json")+try:+ out = json.load(open(p))+except Exception:+ out = {}+out.update({"finalized": True, "success": False, "replay_success": False, "deterministic": False, "infra_error": 1,+ "error": "collect hook: the sim service did not end and dump the episode in time"})+json.dump(out, open(p, "w"))+print(json.dumps(out))+PY+ exit 0+fi+replay() { # <n> [--video FILE]: one replay in a fresh process, its result in $DATA/replay<n>.json+ n=$1; shift+ RCB_SESSION_LOG= python "$TOOL" replay --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --out "$DATA/replay$n.json" \+ "$@" > /dev/null 2> "$DATA/replay$n.log"+ echo "[finalize] replay $n exit $?"+}+echo "[finalize] episode dumped; replaying twice in fresh processes"+rm -f "$DATA/replay1.json" "$DATA/replay2.json" "$DATA/replay3.json"+replay 1+replay 2+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+def result(name):+ try:+ v = json.load(open(os.path.join(d, name)))+ except (OSError, ValueError):+ return {}+ return v if isinstance(v, dict) else {}+out = {"replay_success": False, "deterministic": False, "video": False}+try:+ out.update(json.load(open(os.path.join(d, "episode.json"))))+except Exception as exc:+ out["error"] = f"no episode.json: {exc!r}"+a, b = result("replay1.json"), result("replay2.json")+out["replay_success"] = bool(a.get("success")) and bool(b.get("success"))+out["replay_sha"], out["replay_sha2"] = a.get("state_sha"), b.get("state_sha")+out["deterministic"] = bool(a.get("state_sha")) and a.get("state_sha") == b.get("state_sha")+out["live_matches_replay"] = bool(a.get("state_sha")) and a.get("state_sha") == out.get("live_sha")+if not (a.get("state_sha") and b.get("state_sha")): # a replay process died (it crashed or timed out): not the agent's 0+ out.update({"replay_failed": 1, "infra_error": 1,+ "error": "a replay process gave no result (replay1.log / replay2.log)"})+elif not (a.get("instance_ok") and b.get("instance_ok")): # the image no longer builds the frozen start: not the agent's 0+ out.update({"instance_mismatch": 1, "infra_error": 1, "error": "a replay did not start in the instance's t = 0 state"})+out["finalized"] = True+json.dump(out, open(os.path.join(d, "final.json"), "w"))+print(json.dumps(out))+PY+replay 3 --video "$DATA/replay.mp4"+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+try:+ shown = json.load(open(os.path.join(d, "replay3.json"))).get("video")+except (OSError, ValueError):+ shown = False+if shown:+ p = os.path.join(d, "final.json"); out = json.load(open(p)); out["video"] = True; json.dump(out, open(p, "w"))+PYdiff --git a/tasks/mujoco_playground_go1_getup-standard/environment/sim/instance.json b/tasks/mujoco_playground_go1_getup-standard/environment/sim/instance.jsonnew file mode 100644index 0000000000..094f52130b--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/environment/sim/instance.json@@ -0,0 +1,68 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1Getup",+ "seed": 5,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 0.5,+ -0.6548677086830139,+ 0.061879757791757584,+ 0.69452303647995,+ -0.2914724051952362,+ -0.6954456567764282,+ -0.038879625499248505,+ -2.5283195972442627,+ -0.7643543481826782,+ 1.2582777738571167,+ -1.5951141119003296,+ 0.12876635789871216,+ 4.084576606750488,+ -1.8947221040725708,+ 0.6868290305137634,+ 0.7969384789466858,+ -2.1358203887939453+ ],+ "qvel0": [+ -0.41757500171661377,+ 0.08125269412994385,+ 0.36997389793395996,+ -0.26620352268218994,+ 0.33868932723999023,+ -0.43405938148498535,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "dropped": true,+ "text": "The Unitree Go1 has fallen over. Make it get up and stand upright at its standing height.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": -312.0,+ "start_tilt_deg": 110.0,+ "start_imu_height_m": 0.295,+ "reference_rows": 136,+ "reference_tilt_deg": 2.34,+ "reference_imu_height": 0.2568+ },+ "state_sha": "c59d44064135",+ "horizon": 300,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.",+ "candidates_tried": 6+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_go1_getup-standard/environment/sim/rcb1.py b/tasks/mujoco_playground_go1_getup-standard/environment/sim/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/environment/sim/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_go1_getup-standard/environment/sim/rcb_limited.py b/tasks/mujoco_playground_go1_getup-standard/environment/sim/rcb_limited.pynew file mode 100644index 0000000000..1ce1171787--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/environment/sim/rcb_limited.py@@ -0,0 +1,930 @@+"""eai-standard/2.2 (formerly rcb-limited/2.2): the HTTP layer, the protocol helpers and the crash recovery that every+2.2 sim service shares (docs/STANDARD_MODE_2_2.md; the 2.1 base is docs/LIMITED_MODE_PROTOCOL.md).++The source is scripts/eai_standard/rcb_limited.py; the generators copy it unchanged into every standard task's+environment/sim/ (ci_checks/check-tooling-identity.sh). A service keeps its simulator to itself (scene, action+execution, cameras, kinematic model) and hands this module plain callables:++ import rcb_limited as L+ EP = L.Episode(DATA, dim=N, resume="exact") # before the scene is built; "approx" for a nondeterministic simulator+ EP.startup() # start count, back-off after failed starts, startup watchdog+ S = <build the scene>; EP.scene_built() # the watchdog stands down+ def ctrl_step(a, rec): # every executed control step+ S.step(a); stop = EP.journal(a); rec.tick(); return E["done"] or stop+ rec = L.Recorder(cams, every, grab, proprio_row, extrinsics, clock, depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+ rec.tick(force=True) # first frame (before the chunk / watch)+ ...; rec.tick(); ... # after every control step: a frame every `every` steps+ rec.tick(force=True, last=True) # last frame (+ its depth)+ parts = rec.parts(video, fps) # RCB1 parts: video/ frames/ last/ extrinsic_cv/ last_depth/ depth_frames/ depth/ proprio frame_*+ S.record_start()+ EP.begin(state=E, step=S.step, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, start_event={...}, on_end=end_fn)+ L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics,+ status=status, on_submit_error=lambda exc: finish("error"), log=EP.log,+ episode=EP, state_sha=S.state_sha, proprio=proprio_row))++ grab(cams, want_depth) -> ({cam: uint8 (H,W,3)}, {cam: float32 (H,W) z-depth in metres, 0 = no reading})+ extrinsics(cams) -> {cam: (3,4) world -> camera, OpenCV axes (x right, y down, z forward)}+ proprio_row() -> float32 (len(spec["proprio_layout"]),)+ clock() -> int, control steps since the episode start (the frame's step index)+ do_kinematics(req) -> dict; `req` is parse_kinematics(body, spec["kinematics"]); it must never step physics++None of the callables may step physics. check_spec(SPEC) runs in serve(): a service whose /spec misses a 2.2 field, or+carries a field the protocol forbids (segmentation, object identities or sizes, physical parameters), does not start.+Crash recovery (class Episode; PROTOCOL §4.7): every executed control step is journaled, every completed call+checkpointed (rows, state hash, the robot's proprio row); after a crash compose restarts the container and the service+replays the journal and continues the SAME episode, never a reset. `python rcb_limited.py end <data dir>` is the shared+first half of a collect hook."""+from __future__ import annotations+import faulthandler, json, math, os, re, select, signal, socket, sys, tempfile, threading, time, traceback, zlib+from http.server import BaseHTTPRequestHandler, HTTPServer+from typing import Any, Callable++import numpy as np++import rcb1++PROTOCOL = "eai-standard/2.2"+COMPAT = ["rcb-limited/2.0", "rcb-limited/2.1", "eai-standard/2.1"] # requests written for these are served unchanged+MAX_BODY = 64 * 1024 * 1024+MAX_RESP = 256 * 1024 * 1024+DEPTH_MODES = ("none", "last", "frames")+DEPTH_MAX_M = 65.535 # uint16 millimetres; a farther surface reads 0 (no reading)+DEPTH_NOISE = os.environ.get("RCB_DEPTH_NOISE", "off").strip().lower() # off | realsense (as rcb-limited/2.1)+_RNG = np.random.default_rng(int(os.environ.get("RCB_DEPTH_NOISE_SEED", "0")))+PROPRIO_GROUPS_REQUIRED = ("joint_pos", "joint_vel", "gripper_opening", "tcp_pose", "joint_effort")+PART_PREFIXES = ("video/", "frames/", "last/", "last_depth/", "depth_frames/", "depth/", "extrinsic_cv/")+PART_NAMES = ("proprio", "frame_step", "frame_time_s")+++# ---------------------------------------------------------------- depth+def depth_mode(meta: dict) -> str:+ """The request's depth mode: "none" | "last" | "frames" (2.2 field `depth`), or "legacy" for a 2.0/2.1 request that+ sets `include_depth: true` and no `depth` (answered as 2.1 did: `depth/<cam>` float16 (N,H,W) metres)."""+ d = meta.get("depth")+ if d is None or d is False:+ return "legacy" if meta.get("include_depth") is True else "none"+ if d is True:+ return "last"+ if isinstance(d, str) and d in DEPTH_MODES:+ return d+ raise ValueError(f"depth must be one of {'|'.join(DEPTH_MODES)} (got {d!r})")+++def clean_depth(z) -> np.ndarray:+ """float32 z-depth in metres: non-finite, negative and beyond-range pixels read 0 (no reading); the optional+ RCB_DEPTH_NOISE=realsense model (sigma = 2 mm + 2.5 mm * z^2, 1 % dropouts) is applied here, after rendering, so it+ never touches physics."""+ z = np.asarray(z, dtype=np.float32).copy()+ if z.ndim == 3 and z.shape[-1] == 1:+ z = z[..., 0]+ bad = ~np.isfinite(z) | (z <= 0) | (z > DEPTH_MAX_M)+ z[bad] = 0.0+ if DEPTH_NOISE == "realsense":+ valid = z > 0+ z = z + _RNG.normal(0.0, 1.0, z.shape).astype(np.float32) * (0.002 + 0.0025 * z * z)+ z[_RNG.random(z.shape) < 0.01] = 0.0+ z[~valid] = 0.0+ z[(z < 0) | (z > DEPTH_MAX_M)] = 0.0+ return z.astype(np.float32)+++def depth_frames_part(name: str, stack: np.ndarray) -> tuple[str, str, bytes, dict]:+ """(N,H,W) metres -> an RCB1 "bytes" part: zlib of C-order uint16 millimetres (0 = no reading). Clients that do not+ know it keep the raw bytes and ignore it; rcb_client decodes it back to float32 metres."""+ mm = np.rint(np.asarray(stack, dtype=np.float64) * 1000.0)+ mm[(mm < 0) | (mm > 65535)] = 0+ a = np.ascontiguousarray(mm.astype("<u2"))+ return (name, "bytes", zlib.compress(a.tobytes(), 1), {"codec": "zlib", "dtype": "uint16", "shape": list(a.shape), "unit": "mm"})+++def encode_mp4(frames: np.ndarray, fps: int) -> bytes:+ """H.264 mp4 (yuv420p, faststart) of uint8 (N,H,W,3) frames: the same encoding every 2.0 service used."""+ import imageio.v2 as imageio+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tf:+ path = tf.name+ try:+ with imageio.get_writer(path, format="FFMPEG", mode="I", fps=fps, codec="libx264", macro_block_size=1,+ output_params=["-movflags", "+faststart", "-pix_fmt", "yuv420p"]) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ return open(path, "rb").read()+ finally:+ try:+ os.unlink(path)+ except OSError:+ pass+++# ---------------------------------------------------------------- recording what the cameras see during one call+class Recorder:+ """Frames of the requested cameras every `every` clock ticks, plus forced first/last frames; for every frame the+ proprio row, the clock (step index), each camera's extrinsics and, if asked, its depth. All arrays share one frame+ axis N: frames/<cam>, the mp4's frames, proprio, frame_step, frame_time_s, extrinsic_cv/<cam>, depth_frames/<cam>."""++ def __init__(self, cameras, every: int, grab: Callable, proprio_row: Callable, extrinsics: Callable, clock: Callable,+ depth: str = "none", clock_hz: float = 1.0):+ if depth not in DEPTH_MODES + ("legacy",):+ raise ValueError(f"bad depth mode {depth!r}")+ self.cams = list(cameras); self.every = max(1, int(every)); self.mode = depth; self.hz = float(clock_hz)+ self._grab, self._prop, self._ext, self._clock = grab, proprio_row, extrinsics, clock+ self.frames: dict = {c: [] for c in self.cams}; self.depth: dict = {c: [] for c in self.cams}+ self.ext: dict = {c: [] for c in self.cams}; self.last_depth: dict = {}+ self.prop: list = []; self.steps: list = []; self.n = 0; self.missing = 0++ def tick(self, force: bool = False, last: bool = False) -> None:+ if force or last or self.n % self.every == 0:+ self._capture(last)+ self.n += 1++ def _capture(self, last: bool) -> None:+ want = self.mode in ("frames", "legacy") or (last and self.mode == "last")+ rgb, dep = self._grab(self.cams, want)+ ext = self._ext(self.cams)+ for c in self.cams:+ img = rgb.get(c)+ if img is not None:+ img = np.ascontiguousarray(np.asarray(img)[..., :3].astype(np.uint8))+ else: # a camera that failed to render: a black frame (sized in parts()) keeps one frame axis+ self.missing += 1+ self.frames[c].append(img)+ e = ext.get(c)+ self.ext[c].append(np.full((3, 4), np.nan) if e is None else np.asarray(e, dtype=np.float64).reshape(3, 4))+ if want:+ d = dep.get(c)+ if d is None:+ d = np.zeros(img.shape[:2] if img is not None else (1, 1), np.float32)+ else:+ d = clean_depth(d)+ if img is not None and d.shape != img.shape[:2]:+ raise RuntimeError(f"depth of {c} is {d.shape}, its RGB {img.shape[:2]}: they must be pixel-aligned")+ if self.mode in ("frames", "legacy"):+ self.depth[c].append(d)+ if last or self.mode == "frames":+ self.last_depth[c] = d+ self.prop.append(np.asarray(self._prop(), dtype=np.float32).reshape(-1))+ self.steps.append(int(self._clock()))++ def parts(self, video: str, fps: int) -> list:+ if self.mode == "last" and not self.last_depth and self.prop: # no last=True tick: the state has not moved since+ _, dep = self._grab(self.cams, True)+ self.last_depth = {c: clean_depth(dep[c]) for c in self.cams if c in dep}+ out = []+ for c in self.cams:+ good = [f for f in self.frames[c] if f is not None]+ hw = good[-1].shape[:2] if good else (1, 1)+ if len(good) < len(self.frames[c]):+ self.frames[c] = [f if f is not None else np.zeros(hw + (3,), np.uint8) for f in self.frames[c]]+ self.depth[c] = [d if d.shape == hw else np.zeros(hw, np.float32) for d in self.depth[c]]+ if c in self.last_depth and self.last_depth[c].shape != hw:+ self.last_depth[c] = np.zeros(hw, np.float32)+ fr = np.stack(self.frames[c]) if self.frames[c] else np.zeros((0, 1, 1, 3), np.uint8)+ if video in ("mp4", "both") and len(fr):+ out.append((f"video/{c}", "mp4", encode_mp4(fr, fps), {"fps": fps, "n": int(len(fr))}))+ if video in ("frames", "both"):+ out.append(rcb1.array_part(f"frames/{c}", fr))+ if len(fr):+ out.append(rcb1.array_part(f"last/{c}", fr[-1]))+ out.append(rcb1.array_part(f"extrinsic_cv/{c}", np.stack(self.ext[c]) if self.ext[c] else np.zeros((0, 3, 4))))+ if self.mode in ("last", "frames") and c in self.last_depth:+ out.append(rcb1.array_part(f"last_depth/{c}", self.last_depth[c]))+ if self.mode == "frames" and self.depth[c]:+ out.append(depth_frames_part(f"depth_frames/{c}", np.stack(self.depth[c])))+ if self.mode == "legacy" and self.depth[c]:+ out.append(rcb1.array_part(f"depth/{c}", np.stack(self.depth[c]).astype(np.float16)))+ out.append(rcb1.array_part("proprio", np.stack(self.prop) if self.prop else np.zeros((0, 0), np.float32)))+ st = np.asarray(self.steps, dtype=np.int64)+ out.append(rcb1.array_part("frame_step", st))+ out.append(rcb1.array_part("frame_time_s", st.astype(np.float64) / self.hz))+ return out+++def encode_response(meta: dict, parts: list, max_bytes: int = MAX_RESP) -> bytes:+ """The RCB1 body; over `max_bytes` the per-frame depth goes first, then the raw frames (mp4, last frames, last+ depth, proprio and the per-frame arrays always stay), and meta["degraded"] says what was dropped."""+ body = rcb1.encode(meta, parts)+ dropped = []+ for prefixes in (("depth_frames/", "depth/"), ("frames/",)):+ if len(body) <= max_bytes:+ break+ keep = [p for p in parts if not p[0].startswith(prefixes)]+ if len(keep) < len(parts):+ parts = keep; dropped += [x.rstrip("/") for x in prefixes]+ body = rcb1.encode({**meta, "degraded": f"response over {max_bytes} bytes: {', '.join(dropped)} dropped"}, parts)+ return body+++# ---------------------------------------------------------------- kinematics+def _vec(x, n: int, what: str) -> list:+ a = np.asarray(x, dtype=np.float64).reshape(-1) if x is not None else None+ if a is None or a.size != n or not np.all(np.isfinite(a)):+ raise ValueError(f"{what} must be {n} finite numbers")+ return a.tolist()+++def _pose(x, what: str) -> list:+ p = _vec(x, 7, what)+ nq = math.sqrt(sum(v * v for v in p[3:]))+ if nq < 1e-6:+ raise ValueError(f"{what}: quaternion has zero norm")+ return p[:3] + [v / nq for v in p[3:]]+++def parse_kinematics(body: dict, kin: dict) -> dict:+ """Validate a /kinematics request against spec["kinematics"] (ValueError -> 400). Returns+ {"op": "fk", "q", "links", "base_pose"} or {"op": "ik", "targets": {frame: pose7}, "seed", "base_pose", "tol_pos_m",+ "tol_rot_rad", "max_iters"}; poses are x y z + a unit quaternion in the spec's order; q follows kin["joint_names"]."""+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object")+ op = body.get("op"); n = len(kin["joint_names"])+ base = None+ if body.get("base_pose") is not None:+ if kin.get("frame") != "base":+ raise ValueError("base_pose is only accepted by a mobile robot (spec kinematics.frame == 'base')")+ base = _pose(body["base_pose"], "base_pose")+ if op == "fk":+ links = body.get("links") or list(kin["links"])+ if not isinstance(links, list) or any(l not in kin["links"] for l in links):+ raise ValueError(f"links must be a list of names from spec kinematics.links: {kin['links']}")+ return {"op": "fk", "q": _vec(body.get("q"), n, "q"), "links": links, "base_pose": base}+ if op == "ik":+ tg = body.get("targets")+ if not isinstance(tg, dict) or not tg or any(k not in kin["ik_targets"] for k in tg):+ raise ValueError(f"targets must map frames from spec kinematics.ik_targets {kin['ik_targets']} to poses")+ ik = kin.get("ik", {})+ seed = None if body.get("seed") is None else _vec(body["seed"], n, "seed")+ tol_p = float(body.get("tol_pos_m", ik.get("tol_pos_m", 0.005)))+ tol_r = float(body.get("tol_rot_rad", ik.get("tol_rot_rad", 0.05)))+ it = int(body.get("max_iters", ik.get("max_iters", 200)))+ if not (1e-5 <= tol_p <= 0.5 and 1e-4 <= tol_r <= 3.2 and 1 <= it <= 5000):+ raise ValueError("tol_pos_m in [1e-5, 0.5], tol_rot_rad in [1e-4, 3.2], max_iters in [1, 5000]")+ return {"op": "ik", "targets": {k: _pose(v, f"targets[{k}]") for k, v in tg.items()}, "seed": seed, "base_pose": base,+ "tol_pos_m": tol_p, "tol_rot_rad": tol_r, "max_iters": it}+ raise ValueError("op must be 'fk' or 'ik'")+++def fk_response(poses: dict, frame: str) -> dict:+ return {"ok": True, "op": "fk", "frame": frame, "poses": {k: [float(v) for v in np.asarray(p, dtype=np.float64).reshape(7)] for k, p in poses.items()}}+++def ik_response(q, ok: bool, errors: dict, frame: str, note: str | None = None) -> dict:+ """errors: {frame: (position error m, rotation error rad)} of the returned q (None / non-finite -> null: no solution)."""+ fin = lambda v: float(v) if v is not None and math.isfinite(float(v)) else None # noqa: E731+ out = {"ok": bool(ok), "op": "ik", "frame": frame, "q": None if q is None else [float(v) for v in np.asarray(q).reshape(-1)],+ "error": {k: {"pos_m": fin(e[0]), "rot_rad": fin(e[1])} for k, e in errors.items()}}+ if note:+ out["note"] = note+ return out+++def quat_angle(q1, q2) -> float:+ """Rotation angle (rad) between two unit quaternions of the same order."""+ d = abs(float(np.dot(np.asarray(q1, dtype=np.float64), np.asarray(q2, dtype=np.float64))))+ return 2.0 * math.acos(min(1.0, d))+++# ---------------------------------------------------------------- /spec self-check+FORBIDDEN_KEY = re.compile(r"mask|segment|semantic(?!s$)|instance_?id|bbox|bounding|categor|object|\bobj_|label|mass|friction|"+ r"restitution|inertia|density|damping|stiffness", re.I)+GAIN_PATHS = ("robot_spec.controller",) # joint drive gains (stiffness, damping) are the robot's own, and allowed there+POSITION_KEY = re.compile(r"(?:^|_)(?:pos|position|positions|pose|poses|origin|location|coords?|coordinates|world|translation)(?:_|$)|"+ r"(?:^|_)cent(?:er|re)s?(?:_|$)|(?:^|_)xyz?$|(?:^|_)(?:top|surface|floor|table|plane|height|elevation)?_?z$", re.I)+WORLD_TEXT = re.compile(r"\bworld\s+[xyz]\s*=", re.I)+COORDS = re.compile(r"\(\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*(?:,\s*-?\d+(?:\.\d+)?\s*)?\)")+++def world_text(s: str) -> bool:+ """A text that gives a world coordinate: a pixel-to-world formula, or a coordinate tuple with a decimal point that is+ not the robot's own pose ("robot base at (0, 0, 1.08)" stays)."""+ return bool(WORLD_TEXT.search(s)) or any("." in m.group(0) and not re.search(r"base|robot|origin", s[max(0, m.start() - 40):m.start()], re.I)+ for m in COORDS.finditer(s))+CONVENTIONS = {"static.floor_z": 0.0} # BEHAVIOR: the floor is the plane z = 0 (the world frame's definition)+++def static_positions(obj: Any, path: str = "static") -> list[str]:+ """Paths in /spec static that say WHERE something is (keys naming positions, heights, centres; texts with world+ coordinates). Names, inventories, sizes and colours may stay in static; positions never (docs § Never provided)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}"+ if POSITION_KEY.search(str(k)) and CONVENTIONS.get(p, object()) != v:+ out.append(p)+ else:+ out += static_positions(v, p)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += static_positions(v, f"{path}[{i}]")+ elif isinstance(obj, str) and world_text(obj):+ out.append(path)+ return out+++SPEC_REQUIRED = ("protocol", "protocol_compat", "simulator", "robot", "task_text", "control_hz", "cameras", "default_cameras",+ "action_types", "proprio_layout", "proprio_groups", "static", "world", "budget", "robot_spec", "kinematics", "depth")+++def forbidden_keys(obj: Any, path: str = "", skip: tuple = ()) -> list[str]:+ """Key paths that name something the protocol never provides (key paths in `skip` are not searched)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}" if path else str(k)+ if p in skip:+ continue+ if FORBIDDEN_KEY.search(str(k)) and not (re.search(r"damping|stiffness", str(k), re.I) and p.startswith(GAIN_PATHS)):+ out.append(p)+ out += forbidden_keys(v, p, skip)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += forbidden_keys(v, f"{path}[{i}]", skip)+ return out+++def check_spec(spec: dict) -> None:+ """Raise if /spec is not a complete 2.2 spec or names anything forbidden (run at startup, before binding :8000)."""+ miss = [k for k in SPEC_REQUIRED if k not in spec]+ if miss:+ raise RuntimeError(f"/spec misses {miss}")+ if spec["protocol"] != PROTOCOL:+ raise RuntimeError(f"/spec protocol {spec['protocol']!r} != {PROTOCOL}")+ bad = forbidden_keys(spec, skip=())+ if bad:+ raise RuntimeError(f"/spec names forbidden fields: {bad}")+ pos = static_positions(spec["static"])+ if pos:+ raise RuntimeError(f"/spec static says where things are (never provided): {pos}")+ lay = spec["proprio_layout"]+ if len(set(lay)) != len(lay):+ raise RuntimeError("proprio_layout names are not unique")+ for g in PROPRIO_GROUPS_REQUIRED:+ if g not in spec["proprio_groups"]:+ raise RuntimeError(f"proprio_groups misses {g}")+ for g, (first, n, _meaning) in spec["proprio_groups"].items():+ if not (0 <= first and first + n <= len(lay)):+ raise RuntimeError(f"proprio group {g} [{first}, +{n}) outside the {len(lay)} columns")+ kin = spec["kinematics"]+ for k in ("endpoint", "joint_names", "frame", "quaternion_order", "links", "tcp_frames", "ee_frames", "ik_targets"):+ if k not in kin:+ raise RuntimeError(f"kinematics misses {k}")+ if any(j not in lay for j in kin["joint_names"]):+ raise RuntimeError("kinematics.joint_names must be proprio_layout columns (the measured joint positions)")+ if any(f not in kin["links"] for f in list(kin["tcp_frames"]) + list(kin["ee_frames"]) + list(kin["ik_targets"])):+ raise RuntimeError("kinematics tcp_frames / ee_frames / ik_targets must be listed in kinematics.links")+ if spec["proprio_groups"]["tcp_pose"][1] != 7 * len(kin["tcp_frames"]):+ raise RuntimeError("proprio group tcp_pose must hold 7 columns per kinematics.tcp_frames entry")+ for c, cam in spec["cameras"].items():+ for k in ("rgb", "depth", "mounted", "resolution", "intrinsic_cv", "mount"):+ if k not in cam:+ raise RuntimeError(f"cameras.{c} misses {k}")+ if cam["mount"].get("type") not in ("static", "link"):+ raise RuntimeError(f"cameras.{c}.mount.type must be static|link")+ if any(c not in spec["cameras"] for c in spec["default_cameras"]):+ raise RuntimeError("default_cameras must be cameras")+++# ---------------------------------------------------------------- crash recovery (PROTOCOL §4.7; docs/STANDARD_MODE_2_2.md)+MAX_RESUMES = int(os.environ.get("RCB_MAX_RESUMES", "2"))+STARTUP_TIMEOUT_S = float(os.environ.get("RCB_STARTUP_TIMEOUT_S", "900")) # a task with a slower scene build sets more+MAX_CALL_WALL_S = float(os.environ.get("RCB_MAX_CALL_WALL_S", "900")) # < the client's 1800 s /submit read timeout+RESUME_MAX_DEV_M = float(os.environ.get("RCB_RESUME_MAX_DEV_M", "0.05")) # approx resumes: the gross-divergence guard+ON_SERVICE_ERROR = ("a connection error means the service crashed: it restarts and resumes the SAME episode (never a reset) "+ "in the state after the last call it completed, which you may not have received. Wait until GET /status "+ "answers again (rcb_client: Robot.wait_ready(); resuming replays the episode so far, which can take "+ "minutes in a long episode, and the wall clock keeps running), then check calls and control_steps "+ "before you continue. A 500 means the simulator failed: the episode is over (reason \"error\"). A call "+ "that runs longer than max_call_wall_s seconds stops at the next control step and returns what it "+ "executed (meta.stopped, executed_rows).")+++def _jsonable(v: Any) -> Any:+ if isinstance(v, np.ndarray):+ return v.tolist()+ if isinstance(v, (np.floating, np.integer, np.bool_)):+ return v.item()+ if isinstance(v, (list, tuple)):+ return [_jsonable(x) for x in v]+ if isinstance(v, dict):+ return {str(k): _jsonable(x) for k, x in v.items()}+ return v+++def _peer_closed(sock) -> bool:+ """True when the client of an HTTP request has closed its connection (it gave up on the call): the socket reads as+ end-of-file. A client never sends anything while it waits for the response, so readable means closed."""+ try:+ r, _, _ = select.select([sock], [], [], 0)+ return bool(r) and sock.recv(1, socket.MSG_PEEK) == b""+ except (OSError, ValueError):+ return True+++def _read_json(path: str) -> dict:+ try:+ with open(path) as f:+ d = json.load(f)+ return d if isinstance(d, dict) else {}+ except (OSError, ValueError):+ return {}+++def _write_json(path: str, obj: dict) -> None:+ tmp = f"{path}.{os.getpid()}.tmp"+ with open(tmp, "w") as f:+ json.dump(obj, f)+ os.replace(tmp, path)+++def final_verdict(data: str) -> dict | None:+ """final.json if it already holds a verdict that nothing may overwrite: the grading result (finalized, with+ `deterministic`) or the end of an episode the service gave up after crashes (`gave_up`)."""+ fin = _read_json(os.path.join(data, "final.json"))+ if fin.get("finalized") and (fin.get("gave_up") or fin.get("deterministic") is not None):+ return fin+ return None+++class Episode:+ """Crash-safe episode bookkeeping, the same rules as the RoboTwin and MuJoCo services (PROTOCOL §4.7):++ - startup(): before the scene is built. One line in startups.jsonl; a back-off of min(120, 20 (n - 1)) s when the+ earlier starts never began an episode (they crashed while building, e.g. GPU memory taken by other trials); the+ startup watchdog (faulthandler, a C thread: it fires even when a native scene build holds the GIL) dumps every+ thread's traceback and exits 1 after RCB_STARTUP_TIMEOUT_S, so compose restarts the build. Until begin() a SIGUSR1+ (the collect hook's "the agent phase is over") is only remembered.+ - journal(row): every executed control step (the exact row given to the simulator's step) goes to journal.f64.+ - checkpoint(): after every completed call (the HTTP layer calls it): the journal is flushed, then the call's+ checkpoint is logged in episode.jsonl (rows, control steps, state hash, the robot's proprio row, `persist` keys).+ - begin(): a fresh episode, or after a crash (run.sh exits non-zero, compose restarts the container, `restart:+ on-failure:N`) the SAME episode resumed: the journal is replayed up to the last checkpoint, the journal truncated+ there (the call that was in flight is lost as a whole: its caller got an error, not a result), the state hash+ compared, the service's counters restored; the wall clock keeps running from the first start.+ - Resume check, by the simulator's determinism class: `exact` (bit-exact in a fresh process): the hash must match,+ else the episode ends `resume_failed` (infra_error). `approx` (a simulator declared nondeterministic): a+ mismatch is recorded (resume_state_mismatch, and the robot's deviation from its checkpointed proprio: joint_pos and+ tcp_pose) and the episode continues, unless a TCP is more than RCB_RESUME_MAX_DEV_M from where it was+ (resume_failed, infra_error). The verdict never comes from the live state but from fresh replays of the complete+ recorded trajectory, so continuing cannot raise a score.+ - More than RCB_MAX_RESUMES crashes end the episode: `sim_crashed_on_call` if every crash happened while a call was+ being served (the agent's failure), else `sim_crashed` (infra_error = 1). A verdict already on disk is never+ overwritten; the service then idles with its PID file for the collect hook.+ - Per call, two bounds keep one call from holding the single-threaded service: a call that runs longer than+ max_call_wall_s, or whose client has hung up, stops at the next control step and returns what it executed+ (journal() returns True; meta.stopped says why). Neither bounds the episode: the wall clock is its only budget."""++ def __init__(self, data: str, dim: int, resume: str = "exact", persist: tuple = ()):+ if resume not in ("exact", "approx"):+ raise ValueError("resume must be 'exact' or 'approx'")+ self.data, self.dim, self.resume_class, self.persist = data, int(dim), resume, tuple(persist)+ os.makedirs(data, exist_ok=True)+ p = lambda n: os.path.join(data, n) # noqa: E731+ self.f_events, self.f_journal, self.f_final, self.f_pid, self.f_startups = (+ p("episode.jsonl"), p("journal.f64"), p("final.json"), p("server.pid"), p("startups.jsonl"))+ self.rows = 0 # control steps executed in this episode (journaled)+ self.max_call_wall_s = MAX_CALL_WALL_S+ self.n_startups = 0; self.resumes = 0; self.mismatches = 0; self.max_tcp_dev = 0.0; self.max_joint_dev = 0.0+ self._jf = None; self._call: dict | None = None; self._ids = 0; self._ck: tuple | None = None+ self._on_end: Callable | None = None; self._end_pending = False++ # ---- startup+ def startup(self) -> None:+ signal.signal(signal.SIGUSR1, self._usr1)+ try:+ os.remove(self.f_pid) # a PID file from before a crash would send the collect hook to a dead process+ except OSError:+ pass+ with open(self.f_startups, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid()}) + "\n")+ with open(self.f_startups) as f:+ self.n_startups = sum(1 for line in f if line.strip())+ if self.n_startups > 1 and not any(e.get("ev") == "start" for e in self.events()):+ time.sleep(min(120.0, 20.0 * (self.n_startups - 1)))+ faulthandler.dump_traceback_later(STARTUP_TIMEOUT_S, exit=True)++ def scene_built(self) -> None:+ faulthandler.cancel_dump_traceback_later() # the scene exists: a resume replay may take long, it is not a hang++ def _usr1(self, *_):+ if self._on_end is None:+ self._end_pending = True+ else:+ threading.Thread(target=self._on_end, daemon=True).start()++ # ---- the record+ def log(self, ev: dict) -> None:+ with open(self.f_events, "a") as f:+ f.write(json.dumps(_jsonable({"ts": time.time(), **ev})) + "\n")++ def events(self) -> list:+ out = []+ try:+ with open(self.f_events) as f:+ for line in f:+ try:+ out.append(json.loads(line))+ except ValueError: # a line cut by a crash+ pass+ except OSError:+ pass+ return [e for e in out if isinstance(e, dict)]++ def journal(self, row) -> bool:+ """One executed control step. True: the call in progress must stop at this step boundary (meta.stopped)."""+ a = np.asarray(row, dtype=np.float64).reshape(-1)+ if a.size != self.dim:+ raise ValueError(f"journal rows have {self.dim} entries, got {a.size}")+ if self._jf is None:+ self._jf = open(self.f_journal, "ab")+ self._jf.write(a.tobytes()); self.rows += 1+ c = self._call+ if c is None:+ return False+ if c["stopped"] is None:+ now = time.monotonic()+ if now - c["t0"] > self.max_call_wall_s:+ c["stopped"] = "max_call_wall_s"+ elif c["sock"] is not None and now - c["polled"] >= 0.2:+ c["polled"] = now+ if _peer_closed(c["sock"]):+ c["stopped"] = "client_disconnected"+ return c["stopped"] is not None++ @property+ def stopping(self) -> bool:+ """The call in progress must stop (adapters whose loops test E["done"] test this too)."""+ return bool(self._call and self._call["stopped"])++ @property+ def stop_reason(self) -> str | None:+ return self._call["stopped"] if self._call else None++ def call_begin(self, path: str, sock=None) -> int:+ self._ids += 1+ if path != "/kinematics":+ self._call = {"id": self._ids, "t0": time.monotonic(), "sock": sock, "polled": 0.0, "stopped": None}+ self.log({"ev": "call_begin", "id": self._ids, "path": path})+ return self._ids++ def call_end(self, cid: int, path: str, **extra) -> None:+ self.log({"ev": "call_end", "id": cid, "path": path, **extra})+ if path != "/kinematics":+ self._call = None++ def checkpoint(self, state: dict, state_sha: Callable | None, proprio: Callable | None) -> None:+ if self._jf is not None:+ self._jf.flush() # the rows reach the file before the checkpoint that counts them+ if self._ck is not None and self._ck[0] == self.rows:+ sha, pr = self._ck[1], self._ck[2] # no physics since the last checkpoint+ else:+ try:+ sha = state_sha() if state_sha else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); sha = None+ pr = self._proprio_row(proprio)+ self._ck = (self.rows, sha, pr)+ self.log({"ev": "checkpoint", "call": int(state.get("calls") or 0), "step": int(state.get("step") or 0),+ "control_steps": self.rows, "success": bool(state.get("success")), "done": bool(state.get("done")),+ "reason": state.get("reason"), "state_sha": sha, "proprio": pr,+ **({"persist": {k: state.get(k) for k in self.persist}} if self.persist else {})})++ @staticmethod+ def _proprio_row(proprio: Callable | None) -> list | None:+ try:+ return [round(float(v), 6) for v in np.asarray(proprio(), dtype=np.float64).reshape(-1)] if proprio else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); return None++ def final_fields(self) -> dict:+ """Crash-recovery fields for final.json / episode.json (all numeric, for reward.json)."""+ return {"sim_startups": self.n_startups, "resumes": self.resumes, "resume_state_mismatch": int(self.mismatches > 0),+ "resume_max_tcp_dev_m": round(self.max_tcp_dev, 6), "resume_max_joint_dev": round(self.max_joint_dev, 6)}++ # ---- start or resume+ def begin(self, *, state: dict, step: Callable, state_sha: Callable, proprio: Callable, spec: dict,+ start_event: dict | None = None, on_end: Callable | None = None) -> bool:+ """Start the episode, or resume it after a crash. `step(row)` executes one journaled row on the simulator (the+ recorder on, no rendering needed); `on_end` is what the collect hook's SIGUSR1 runs (in a thread). Returns True+ if the episode was resumed."""+ try: # a line cut by the crash must not swallow the next record+ with open(self.f_events, "rb+") as f:+ f.seek(0, os.SEEK_END)+ if f.tell():+ f.seek(-1, os.SEEK_END)+ if f.read(1) != b"\n":+ f.write(b"\n")+ except OSError:+ pass+ ev = self.events()+ starts = [e for e in ev if e.get("ev") == "start"]+ if not starts:+ try:+ os.remove(self.f_journal)+ except OSError:+ pass+ sha = state_sha()+ self._ck = (0, sha, self._proprio_row(proprio))+ self.log({**(start_event or {}), "ev": "start", "state_sha": sha, "protocol": PROTOCOL, "resume": self.resume_class,+ "journal_dim": self.dim})+ state["t0"] = time.time()+ self._arm(on_end)+ return False+ tries = [e for e in ev if e.get("ev") == "resuming"] # earlier resumes (a crash during one counts too)+ resumed = [e for e in ev if e.get("ev") == "resumed"]+ self.resumes = len(tries) # the record so far, also for a give-up below (final_fields)+ self.mismatches = sum(1 for e in resumed if e.get("exact") is False)+ self.max_tcp_dev = max([float(e.get("tcp_dev_m") or 0) for e in resumed] + [0.0])+ self.max_joint_dev = max([float(e.get("joint_dev") or 0) for e in resumed] + [0.0])+ if final_verdict(self.data):+ self.give_up("restarted after finalize", infra=False)+ k = max(i for i, e in enumerate(ev) if e.get("ev") in ("start", "resuming", "resumed"))+ tail = ev[k + 1:]+ in_call = bool({e.get("id") for e in tail if e.get("ev") == "call_begin"} - {e.get("id") for e in tail if e.get("ev") == "call_end"})+ if len(tries) >= MAX_RESUMES:+ agent = sum(1 for e in tries if e.get("crashed_in_call")) + int(in_call) == len(tries) + 1+ self.give_up("sim_crashed_on_call" if agent else "sim_crashed", infra=not agent)+ self.log({"ev": "resuming", "attempt": len(tries) + 1, "crashed_in_call": in_call,+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self.resumes = len(tries) + 1 # this attempt counts, whether or not it succeeds+ cps = [e for e in ev if e.get("ev") == "checkpoint"]+ last = cps[-1] if cps else {"call": 0, "step": 0, "control_steps": 0, "success": False, "state_sha": starts[0].get("state_sha")}+ n = int(last.get("control_steps") or 0)+ try:+ R = np.fromfile(self.f_journal, dtype=np.float64)+ except (OSError, ValueError):+ R = np.zeros(0)+ if R.size < n * self.dim:+ self.give_up("resume_failed: journal shorter than the log", infra=True)+ R = R[: n * self.dim].reshape(n, self.dim)+ t = time.time()+ for row in R:+ step(row)+ replay_s = time.time() - t+ R.tofile(self.f_journal) # drop the rows of the call that was in flight+ self.rows = n+ sha = state_sha(); want = last.get("state_sha")+ exact = None if want is None else sha == want+ dev = self._deviation(last.get("proprio"), proprio, spec)+ if exact is False: # recorded first: a give-up below reports it too+ self.mismatches += 1+ self.max_tcp_dev = max(self.max_tcp_dev, dev.get("tcp_m") or 0.0)+ self.max_joint_dev = max(self.max_joint_dev, dev.get("joint") or 0.0)+ if self.resume_class == "exact":+ self.give_up("resume_failed: replayed state differs from the logged one", infra=True)+ if dev.get("tcp_m") is not None and dev["tcp_m"] > RESUME_MAX_DEV_M:+ self.give_up(f"resume_failed: a replayed TCP is {dev['tcp_m']:.3f} m from its checkpoint (> {RESUME_MAX_DEV_M} m)", infra=True)+ state["calls"] = int(last.get("call") or 0); state["step"] = int(last.get("step") or 0)+ if "success" in state:+ state["success"] = bool(last.get("success"))+ for key, v in (last.get("persist") or {}).items():+ state[key] = v+ state["t0"] = float(starts[0]["ts"])+ ended = [e for e in ev if e.get("ev") == "end" and int(e.get("control_steps") or 0) <= n] # not the lost call's+ if ended:+ state["done"] = True; state["reason"] = ended[-1].get("reason"); state["t_end"] = float(ended[-1]["ts"])+ state["episode_control_steps"] = int(ended[-1].get("control_steps") or n)+ self._ck = (n, sha, self._proprio_row(proprio)) # the replayed state's row (it may differ under approx)+ self.log({"ev": "resumed", "attempt": self.resumes, "control_steps": n, "calls": state["calls"], "state_sha": sha,+ "logged_sha": want, "exact": exact, "class": self.resume_class, "tcp_dev_m": dev.get("tcp_m"),+ "joint_dev": dev.get("joint"), "crashed_in_call": in_call, "replay_s": round(replay_s, 1),+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self._arm(on_end)+ return True++ @staticmethod+ def _deviation(ref, proprio: Callable, spec: dict) -> dict:+ """The replayed robot against its checkpointed proprio row: max |joint_pos| difference (rad or m) and the largest+ TCP position error (m) over the tcp_pose frames (7 columns each: x y z + quaternion)."""+ if ref is None:+ return {}+ try:+ now = np.asarray(proprio(), dtype=np.float64).reshape(-1); ref = np.asarray(ref, dtype=np.float64).reshape(-1)+ except Exception: # noqa: BLE001+ return {}+ if now.shape != ref.shape:+ return {}+ g, out = spec.get("proprio_groups") or {}, {}+ if "joint_pos" in g:+ f, n = int(g["joint_pos"][0]), int(g["joint_pos"][1])+ out["joint"] = float(np.max(np.abs(now[f:f + n] - ref[f:f + n]))) if n else 0.0+ if "tcp_pose" in g:+ f, n = int(g["tcp_pose"][0]), int(g["tcp_pose"][1]); m = n // 7+ d = (now[f:f + 7 * m] - ref[f:f + 7 * m]).reshape(m, 7)[:, :3]+ out["tcp_m"] = float(np.max(np.linalg.norm(d, axis=1))) if m else 0.0+ return out++ def _arm(self, on_end: Callable | None) -> None:+ self._on_end = on_end+ signal.signal(signal.SIGUSR1, self._usr1)+ if on_end is not None and self._end_pending:+ self._end_pending = False+ threading.Thread(target=on_end, daemon=True).start()++ def give_up(self, reason: str, infra: bool) -> None:+ """End the trial's episode without a new one (never a reset): log it, write the verdict unless one is on disk,+ leave the PID file for the collect hook, and idle until the container is removed."""+ faulthandler.cancel_dump_traceback_later()+ self.log({"ev": "restart_refused", "reason": reason})+ if not final_verdict(self.data):+ fin = _read_json(self.f_final)+ fin.update({"success": False, "done": True, "reason": reason, "finalized": True, "gave_up": True, "protocol": PROTOCOL,+ **self.final_fields(), **({"infra_error": 1} if infra else {})})+ _write_json(self.f_final, fin)+ with open(self.f_pid, "w") as f:+ f.write(str(os.getpid()))+ signal.signal(signal.SIGUSR1, lambda *_: None)+ print(f"[{PROTOCOL}] restart refused: {reason}", flush=True)+ while True:+ time.sleep(3600)+++# ---------------------------------------------------------------- the HTTP layer+class Service:+ """What a sim service hands to serve(): spec (dict), lock, state (the service's E dict: done, reason, exiting, error),+ submit(meta, actions) and observe(meta) -> (meta_out, rcb1 parts), kinematics(req) -> dict, status() -> dict,+ on_submit_error(exc) (a simulator error in /submit or /observe: it ends the episode, reason "error"), log(event dict),+ and for crash recovery the Episode with the simulator's state_sha() and proprio row()."""++ def __init__(self, *, spec: dict, lock, state: dict, submit: Callable, observe: Callable, kinematics: Callable,+ status: Callable, on_submit_error: Callable, log: Callable, max_resp: int = MAX_RESP,+ episode: Episode | None = None, state_sha: Callable | None = None, proprio: Callable | None = None):+ self.spec, self.lock, self.state, self.submit, self.observe = spec, lock, state, submit, observe+ self.kinematics, self.status, self.on_submit_error, self.log, self.max_resp = kinematics, status, on_submit_error, log, max_resp+ self.episode, self.state_sha, self.proprio = episode, state_sha, proprio+ self.kin_calls = 0+++def make_handler(svc: Service):+ class H(BaseHTTPRequestHandler):+ def _send(self, code: int, ctype: str, body: bytes) -> None:+ try:+ self.send_response(code); self.send_header("Content-Type", ctype); self.send_header("Content-Length", str(len(body)))+ self.end_headers(); self.wfile.write(body)+ except (BrokenPipeError, ConnectionResetError): # the client hung up (its call was abandoned)+ pass++ def _json(self, code: int, obj: dict) -> None:+ self._send(code, "application/json", json.dumps(obj).encode())++ def _rcb1(self, meta: dict, parts: list) -> None:+ self._send(200, "application/x-rcb1", encode_response(meta, parts, svc.max_resp))++ def log_message(self, *a):+ pass++ def _body(self):+ try:+ n = int(self.headers.get("Content-Length", 0))+ except ValueError:+ raise ValueError("bad Content-Length")+ if n > MAX_BODY:+ raise ValueError("request too large")+ raw = self.rfile.read(n) if n else b""+ if raw[:4] == rcb1.MAGIC:+ return rcb1.decode(raw)+ body = json.loads(raw or b"{}")+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object or an RCB1 frame")+ return body, {}++ def do_GET(self):+ if self.path == "/spec":+ return self._json(200, svc.spec)+ if self.path == "/status":+ st = svc.status()+ return self._json(200, {**st, "resumes": svc.episode.resumes} if svc.episode else st)+ return self._json(404, {"error": "no such endpoint"})++ def do_POST(self):+ if self.path not in ("/submit", "/observe", "/kinematics"):+ return self._json(404, {"error": "no such endpoint"})+ try:+ meta, parts = self._body()+ except Exception as exc: # noqa: BLE001+ return self._json(413 if "too large" in str(exc) else 400, {"error": str(exc)[:200]})+ E, ep = svc.state, svc.episode+ if self.path == "/kinematics": # stateless: never steps physics, never waits for the episode lock+ cid = ep.call_begin(self.path) if ep else 0+ try:+ req = parse_kinematics(meta, svc.spec["kinematics"])+ out = svc.kinematics(req); svc.kin_calls += 1+ except ValueError as exc:+ return self._json(400, {"error": str(exc)[:300]})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); return self._json(500, {"error": "kinematics error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ ep.call_end(cid, self.path)+ return self._json(200, out)+ with svc.lock:+ if E.get("exiting") or (self.path == "/submit" and E.get("done")):+ return self._json(409, {"error": "episode finished", "reason": E.get("reason")})+ cid = ep.call_begin(self.path, self.connection) if ep else 0+ rows0 = ep.rows if ep else 0+ out = blobs = err = None; stopped = None+ try:+ if self.path == "/submit":+ A = np.asarray(parts["actions"]["data"] if "actions" in parts else meta.get("actions", []), dtype=np.float64)+ out, blobs = svc.submit(meta, A)+ else:+ out, blobs = svc.observe(meta)+ except ValueError as exc:+ err = (400, {"error": str(exc)})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); E["error"] = repr(exc); svc.log({"ev": "error", "path": self.path, "error": repr(exc)})+ try:+ svc.on_submit_error(exc) # PROTOCOL §4.6: a simulator error ends the episode (reason "error")+ except Exception: # noqa: BLE001+ traceback.print_exc()+ err = (500, {"error": "simulator error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ stopped = ep.stop_reason+ if err is None or ep.rows != rows0:+ try:+ ep.checkpoint(E, svc.state_sha, svc.proprio)+ except Exception: # noqa: BLE001+ traceback.print_exc()+ ep.call_end(cid, self.path, **({"stopped": stopped} if stopped else {}))+ if err is not None:+ return self._json(*err)+ return self._rcb1({**out, "stopped": stopped}, blobs)+ return H+++def serve(svc: Service, port: int = 8000) -> None:+ """Check the spec, then serve forever (one request at a time, as every 2.x service)."""+ svc.spec.setdefault("on_service_error", ON_SERVICE_ERROR)+ if svc.episode is not None:+ svc.spec.setdefault("max_call_wall_s", svc.episode.max_call_wall_s)+ check_spec(svc.spec)+ HTTPServer(("0.0.0.0", port), make_handler(svc)).serve_forever()+++# ---------------------------------------------------------------- the collect hook's first half+def _alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ try: # a zombie (exited, not yet reaped) counts as gone+ with open(f"/proc/{pid}/stat") as f:+ return f.read().rsplit(")", 1)[-1].split()[0] != "Z"+ except OSError:+ return True+++def end_episode(data: str, timeout: float = 21600.0, wait_key: str | None = None, resend_s: float = 30.0) -> int:+ """Tell the service that the agent phase is over and wait until it has ended the episode. The service may be+ resuming after a crash (no PID file until it is ready again), so there is no fixed start-up wait, and a signal goes+ only to the process that wrote the newest line of startups.jsonl (its SIGUSR1 handler is installed by then).+ Returns 2: final.json already holds the verdict (the service gave up after crashes, or graded in-process; with+ `wait_key`, also waits for that final.json key, e.g. video_done): keep it, run no replays.+ Returns 0: the service dumped the episode (episode.json) and exited: the hook replays it next.+ Returns 1: timed out."""+ t0, sent = time.time(), 0.0+ f_pid, f_dump, f_starts = (os.path.join(data, n) for n in ("server.pid", "episode.json", "startups.jsonl"))+ while time.time() - t0 < timeout:+ fin = final_verdict(data)+ if fin is not None:+ if not wait_key or fin.get(wait_key) or fin.get("gave_up"):+ return 2+ time.sleep(2); continue+ try:+ with open(f_pid) as f:+ pid = int(f.read().strip())+ except (OSError, ValueError):+ pid = None+ try:+ with open(f_starts) as f:+ cur = json.loads([x for x in f if x.strip()][-1]).get("pid")+ except (OSError, ValueError, IndexError):+ cur = None # a service without Episode.startup(): signal what the PID file names+ if pid is not None and (cur is None or pid == cur):+ if not _alive(pid):+ if os.path.exists(f_dump):+ return 0+ elif time.time() - sent >= resend_s:+ try:+ os.kill(pid, signal.SIGUSR1); sent = time.time()+ except OSError:+ pass+ time.sleep(2)+ return 1+++if __name__ == "__main__":+ a = sys.argv[1:]+ if len(a) >= 2 and a[0] == "end":+ wk = a[a.index("--wait-key") + 1] if "--wait-key" in a else None+ to = float(a[a.index("--timeout") + 1]) if "--timeout" in a else 21600.0+ rc = end_episode(a[1], timeout=to, wait_key=wk)+ print({0: "[collect] episode dumped by the service", 1: "[collect] timed out waiting for the service",+ 2: "[collect] final.json already holds the verdict"}[rc], flush=True)+ sys.exit(rc)+ if len(a) == 2 and a[0] == "final-verdict":+ fin = final_verdict(a[1])+ print(json.dumps(fin) if fin else "no final verdict")+ sys.exit(0 if fin else 1)+ print("usage: rcb_limited.py end <data dir> [--wait-key KEY] [--timeout S] | final-verdict <data dir>")+ sys.exit(2)diff --git a/tasks/mujoco_playground_go1_getup-standard/environment/sim/rcb_quadruped.py b/tasks/mujoco_playground_go1_getup-standard/environment/sim/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/environment/sim/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_go1_getup-standard/environment/sim/run.sh b/tasks/mujoco_playground_go1_getup-standard/environment/sim/run.shnew file mode 100755index 0000000000..49d4d045d4--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/environment/sim/run.sh@@ -0,0 +1,22 @@+#!/bin/sh+# eai-standard/2.2 sidecar entrypoint: PID 1 of the `sim` container, shared by every 2.2 service+# (scripts/eai_standard/run.sh, copied unchanged into each standard task's environment/sim/).+# - The service crashed (a non-zero exit: an exception, a signal, the startup watchdog): exit with its code, so compose+# restarts the container (`restart: on-failure:6`) and the service resumes the same episode from its journal+# (rcb_limited.Episode). The container keeps its /data (or /out) across the restart.+# - The service exited cleanly (0: it dumped its episode on the collect hook's SIGUSR1 and released the simulator): keep+# the container up for the collect hook's fresh-process replays. If the service were PID 1 itself, that exit would+# stop the container and kill the hook with it (Harbor reports exit 137).+# - Everything the service prints also goes to $RCB_DATA/server.log (an artifact: Harbor keeps no sidecar output, and a+# simulator that dies while it loads leaves no other trace).+DATA="${RCB_DATA:-/data}"+mkdir -p "$DATA"+rm -f "$DATA/.service_rc"+{ python -u "${RCB_SERVER:-/srv/server.py}" 2>&1; echo "$?" > "$DATA/.service_rc"; } | tee -a "$DATA/server.log"+rc="$(cat "$DATA/.service_rc" 2>/dev/null)"; rc="${rc:-1}"+if [ "$rc" != 0 ]; then+ echo "[sim] service exited ($rc): leaving, so compose restarts the container (the service resumes the episode if one began)" | tee -a "$DATA/server.log"+ exit "$rc"+fi+echo "[sim] service exited (0); holding the container open for the collect hook" | tee -a "$DATA/server.log"+while true; do sleep 3600; donediff --git a/tasks/mujoco_playground_go1_getup-standard/environment/sim/server.py b/tasks/mujoco_playground_go1_getup-standard/environment/sim/server.pynew file mode 100644index 0000000000..b0c774b183--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/environment/sim/server.py@@ -0,0 +1,478 @@+"""eai-standard/2.2 sim service for MuJoCo Playground's quadruped tasks (docs/STANDARD_MODE_2_2.md): the adapter of the+shared layer rcb_limited.py; the simulator is rcb_quadruped.Session (plain MuJoCo on the CPU).+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to+/data/episode.jsonl.++The episode is the frozen instance's: one control step = 1/50 s. A joystick episode ends after the whole command schedule+(the horizon), when the robot meets Playground's termination rule (it falls over: a failure), when the agent submits+`done`, or when its time is over; success = the task's check on the steps executed. A getup episode ends the moment the+check holds (success), after the horizon, on `done` or on timeout.++Crash recovery (rcb_limited.Episode, resume class `exact`: MuJoCo on the CPU repeats bit for bit in a fresh process):+every executed row is journaled; after a crash the service rebuilds the episode and replays the journal. When the+episode ends the service writes /data/trajectory.npz + /data/episode.json; the collect hook (finalize.sh) makes it exit+and replays the trajectory in two fresh processes."""++import math+import os+import sys+import threading+import time+import traceback++import numpy as np++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import rcb_limited as L # noqa: E402++DATA = os.environ.get("RCB_DATA", "/data")+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.json"))+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "3600"))+MAX_CHUNK_S = float(os.environ.get("RCB_MAX_CHUNK_S", "10"))+MAX_WATCH_S = float(os.environ.get("RCB_MAX_WATCH_S", "30"))+CAM_W, CAM_H = 320, 240+LOCK = threading.Lock()+PID_FILE = os.path.join(DATA, "server.pid")+E = {"ready": False, "step": 0, "calls": 0, "done": False, "reason": None, "success": False, "t0": time.time(), "error": None}++os.environ["RCB_SESSION_LOG"] = ""+os.environ["RCB_AGENT_TRACE_DIR"] = ""+import rcb_quadruped as Q # noqa: E402 (first: it picks the rendering backend before mujoco loads)+import mujoco # noqa: E402++EP = L.Episode(DATA, dim=Q.N, resume="exact")+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()+S = Q.Session(INSTANCE)+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz+DT = S.control_dt # one control step of simulated time (Barkour: 10 ms, as Playground steps it)+CTRL_HZ = 1.0 / DT+SUBSTEPS = S.substeps+M = S.model+CAMS = list(S.cameras)+FEET = S.robot["feet"]+LIMITS = np.stack([S.lower, S.upper], axis=1)+GROUPS = [+ ("joint_pos", S.joint_names, "measured joint positions (rad), in the action's order"),+ ("joint_vel", [f"{j}_vel" for j in S.joint_names], "measured joint velocities (rad/s)"),+ ("joint_effort", [f"{j}_effort" for j in S.joint_names], "actuator torques of those joints (N m)"),+ ("gripper_opening", [], "none (no gripper)"),+ ("tcp_pose", [], "none (no gripper)"),+ ("imu_gyro", ["gyro_x", "gyro_y", "gyro_z"], "angular velocity of the trunk, IMU frame (rad/s)"),+ ("imu_accelerometer", ["acc_x", "acc_y", "acc_z"], "specific force at the IMU, IMU frame (m/s^2; +9.81 up at rest)"),+ ("imu_gravity", ["gravity_x", "gravity_y", "gravity_z"], "unit vector of gravity's direction in the IMU frame "+ "([0, 0, -1] when the trunk is level)"),+ ("imu_linvel", ["linvel_x", "linvel_y", "linvel_z"], "linear velocity of the trunk at the IMU, IMU frame (m/s; the "+ "IMU's velocimeter, what a state estimator gives)"),+ ("foot_contact", [f"{f}_contact" for f in FEET], "1 when the foot touches the ground, else 0"),+]+PROPRIO_LAYOUT = [n for _, names, _ in GROUPS for n in names]+PROPRIO_GROUPS, _i = {}, 0+for _g, _names, _meaning in GROUPS:+ PROPRIO_GROUPS[_g] = [_i, len(_names), _meaning]+ _i += len(_names)+++# ------------------------------------------------------------------------------------------------- cameras+def _intrinsic(cam: str) -> list:+ fovy = math.radians(float(M.cam_fovy[M.camera(cam).id]))+ f = 0.5 * CAM_H / math.tan(fovy / 2)+ return [[f, 0.0, CAM_W / 2], [0.0, f, CAM_H / 2], [0.0, 0.0, 1.0]]+++def camera_info(cam: str) -> dict:+ """World -> camera (OpenCV axes) and camera -> world (OpenGL axes) at the current state."""+ i = M.camera(cam).id+ R_gl = S.data.cam_xmat[i].reshape(3, 3) # camera axes (OpenGL: x right, y up, z back) in the world+ p = S.data.cam_xpos[i].copy()+ R_cv = R_gl @ np.diag([1.0, -1.0, -1.0])+ ext = np.zeros((3, 4))+ ext[:, :3] = R_cv.T+ ext[:, 3] = -R_cv.T @ p+ c2w = np.eye(4)+ c2w[:3, :3] = R_gl+ c2w[:3, 3] = p+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": ext.tolist(), "cam2world_gl": c2w.tolist(),+ "image_size": [CAM_W, CAM_H]}+++# ------------------------------------------------------------------------------------------------- kinematics+KD = mujoco.MjData(M) # kinematics only: the trunk at the origin, level; never stepped+_FOOT = {f: M.site(f).id for f in FEET}+_LEG_DOF = {f: [6 + 3 * k + j for j in range(3)] for k, f in enumerate(FEET)} # actuator order = leg order = FEET+++def _fk_kd(q) -> None:+ KD.qpos[:] = 0.0+ KD.qpos[3] = 1.0+ KD.qpos[7:] = q+ mujoco.mj_kinematics(M, KD)+++def _foot_pose(f: str) -> list:+ quat = np.zeros(4)+ mujoco.mju_mat2Quat(quat, KD.site_xmat[_FOOT[f]])+ return [*KD.site_xpos[_FOOT[f]].tolist(), *quat.tolist()]+++def do_kinematics(req: dict) -> dict:+ """Feet in the trunk frame (the trunk body's origin and axes; x forward, y left, z up). IK solves positions only, one+ leg (3 joints) per foot target, damped least squares within the joint ranges; a foot's orientation is ignored."""+ if req["op"] == "fk":+ _fk_kd(np.asarray(req["q"]))+ return L.fk_response({f: _foot_pose(f) for f in req["links"]}, "trunk")+ q = np.array(req["seed"] if req["seed"] is not None else S.data.qpos[7:], dtype=np.float64)+ errors = {}+ jac = np.zeros((3, M.nv))+ for f, pose in req["targets"].items():+ tgt = np.asarray(pose[:3])+ idx = _LEG_DOF[f]+ for _ in range(req["max_iters"]):+ _fk_kd(q)+ err = tgt - KD.site_xpos[_FOOT[f]]+ if np.linalg.norm(err) < req["tol_pos_m"]:+ break+ mujoco.mj_jacSite(M, KD, jac, None, _FOOT[f])+ J = jac[:, idx]+ dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(3), err)+ q[[i - 6 for i in idx]] = np.clip(q[[i - 6 for i in idx]] + dq, S.lower[[i - 6 for i in idx]],+ S.upper[[i - 6 for i in idx]])+ _fk_kd(q)+ errors[f] = (float(np.linalg.norm(tgt - KD.site_xpos[_FOOT[f]])), 0.0)+ ok = all(e[0] <= req["tol_pos_m"] for e in errors.values())+ return L.ik_response(q, ok, errors, "trunk", note="feet: position only (a foot is a sphere; its orientation is ignored)")+++# ------------------------------------------------------------------------------------------------- spec+def schedule_text() -> list:+ if S.commands is None:+ return []+ return [{"from_s": round(int(c["start_step"]) * DT, 2), "vx_mps": round(c["vx"], 4), "vy_mps": round(c["vy"], 4),+ "wz_radps": round(c["wz"], 4)} for c in S.inst["commands"]]+++TASK_EPISODE = {+ "joystick": f"one episode, no reset: it ends after {S.horizon} control steps (the {S.horizon * DT:g} s command "+ f"schedule), when the robot meets its termination rule ({S.spec.get('term_text')}: a failure), when you "+ "submit `done`, or when your time is over",+ "getup": f"one episode, no reset: it ends the moment the robot has stood upright for {Q.HOLD_STEPS} control steps in a "+ f"row (success), after {S.horizon} control steps, when you submit `done`, or when your time is over",+ "stand_on_two": f"one episode, no reset: it ends the moment the pose has been held for {Q.POSE_HOLD_STEPS} control steps "+ "in a row (success), when the robot meets the termination rule (a failure: its trunk's up axis below "+ f"-0.25, or {'a leg' if S.spec.get('hind_leg_contact') else 'a front leg'}'s thigh, calf or hip on the "+ f"floor), after {S.horizon} control steps, when you "+ "submit `done`, or when your time is over",+}[S.kind]+_ctl = {"type": "joint position actuators (PD)", "kp_nm_per_rad": float(M.actuator_gainprm[0, 0]),+ "kd_nms_per_rad": float(M.dof_damping[6] - M.actuator_biasprm[0, 2])}+SPEC = {+ "protocol": L.PROTOCOL,+ "protocol_compat": list(L.COMPAT),+ "simulator": "MuJoCo 3.3.7 (MuJoCo Playground's scene, plain MuJoCo on the CPU)",+ "robot": S.robot["name"],+ "task_text": S.inst["text"],+ "control_hz": CTRL_HZ,+ "physics_substeps": SUBSTEPS,+ "max_chunk_s": MAX_CHUNK_S,+ "max_watch_s": MAX_WATCH_S,+ "cameras": {c: {"rgb": True, "depth": True, "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),+ **({"mounted": "follows the robot", "mount": {"type": "link", "link": S.robot["root"], "note":+ "follows the robot's centre of mass at a fixed offset; it does not turn with the robot"}}+ if int(M.cam_mode[M.camera(c).id]) != 0 else+ {"mounted": "on the robot's head", "mount": {"type": "link", "link": M.body(M.cam_bodyid[M.camera(c).id]).name+ or S.robot["root"], "note": "fixed to the robot: moves and turns with it"}})}+ for c in CAMS},+ "default_cameras": ["track"],+ "action_types": {+ "joint_position": {+ "dim": Q.N,+ "layout": S.joint_names,+ "limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "units": "rad",+ "semantics": "absolute targets of the 12 joint position actuators, one per control step (1/50 s); rows `dt` "+ "apart (a multiple of the control period, at most 0.5 s), `hold` or `linear` between rows; values "+ "outside the limits are clipped and reported",+ },+ "done": {"dim": 0, "layout": [], "semantics": 'ends the episode now, in the current state (no physics); r.submit("done", [])'},+ "not_yet": ["joint_velocity", "joint_torque", "joint_delta"],+ },+ "proprio_layout": PROPRIO_LAYOUT,+ "proprio_groups": PROPRIO_GROUPS,+ "static": {},+ "world": {"frame": "z up; the robot starts where the episode puts it (no world coordinates are given)", "up": "+z",+ "units": {"length": "m", "angle": "rad", "time": "s"}, "quaternion_order": "wxyz",+ "camera_axes": "intrinsic_cv / extrinsic_cv: OpenCV camera axes (x right, y down, z forward); cam2world_gl: OpenGL axes"},+ "budget": {"reset": 0, "steps": None, "wall_clock_s": WALL_CLOCK_S},+ "max_control_steps": S.horizon,+ "episode": TASK_EPISODE,+ "command_schedule": schedule_text(),+ **({"gait": {k: S.gait[k] for k in ("name", "frequency_hz", "foot_height_m", "phase0", "phase_dt")} | {+ "feet": FEET, "rule": "foot i's target height at control step t is get_rz(wrap(phase0[i] + t * phase_dt)) with "+ "Playground's gait.get_rz (a cubic Bezier from 0 up to foot_height_m over the first half of the phase, then "+ "down); phases in rad, wrapped to [-pi, pi)"}} if S.gait else {}),+ "robot_spec": {"name": S.robot["name"], "joints": S.joint_names, "joint_limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "joint_order": S.robot["joint_text"], "home_pose": dict(zip(S.joint_names, S.home.tolist())),+ "feet": FEET, "controller": _ctl},+ "kinematics": {"endpoint": "/kinematics", "joint_names": S.joint_names, "frame": "trunk", "quaternion_order": "wxyz",+ "links": FEET, "tcp_frames": [], "ee_frames": FEET, "ik_targets": FEET,+ "ik": {"tol_pos_m": 0.002, "tol_rot_rad": 3.2, "max_iters": 100},+ "note": "poses of the feet in the trunk frame (x forward, y left, z up, metres) for joint positions q; "+ "ik: one leg per foot, positions only"},+ "depth": {"modes": list(L.DEPTH_MODES), "default": "none", "kind": "z-depth", "unit": "m", "invalid": 0,+ "max_m": L.DEPTH_MAX_M, "frames_encoding": "uint16 mm, zlib", "noise": L.DEPTH_NOISE},+}+L.check_spec(SPEC) # a spec that misses a 2.2 field or names a forbidden one never starts the episode+EP.scene_built()++_RENDER = {}+++def _renderer():+ if "r" not in _RENDER:+ _RENDER["r"] = mujoco.Renderer(M, CAM_H, CAM_W)+ return _RENDER["r"]+++def ctrl_steps() -> int:+ return S.steps+++def proprio_row() -> np.ndarray:+ d = S.data+ return np.concatenate([d.qpos[7:], d.qvel[6:], d.actuator_force, S.sensor("gyro"), S.sensor("accelerometer"), S.gravity(),+ S.sensor("local_linvel"), S.foot_contacts()]).astype(np.float32)+++def grab(cams, want_depth: bool):+ r = _renderer()+ rgb, dep = {}, {}+ for c in cams:+ r.update_scene(S.data, camera=c)+ rgb[c] = r.render().copy()+ if want_depth:+ r.enable_depth_rendering()+ r.update_scene(S.data, camera=c)+ dep[c] = r.render().astype(np.float32).copy()+ r.disable_depth_rendering()+ return rgb, dep+++def extrinsics(cams) -> dict:+ return {c: np.asarray(camera_info(c)["extrinsic_cv"], dtype=np.float64) for c in cams}+++def write_final() -> None:+ if L.final_verdict(DATA): # finalize.sh's verdict, or a give-up after crashes: never overwritten+ return+ L._write_json(os.path.join(DATA, "final.json"), {**summary(), "finalized": False, "live_sha": E.get("live_sha")})+++def summary() -> dict:+ n = int(E.get("episode_control_steps") or ctrl_steps())+ chk = E.get("check") or {}+ return {"success": bool(E["success"]), "steps": E["step"], "calls": E["calls"], "control_steps": n,+ "physics_steps": n * SUBSTEPS, "elapsed_s": round((E.get("t_end") or time.time()) - E["t0"], 1),+ "reason": E["reason"], "done": E["done"], "env": S.env, "protocol": L.PROTOCOL, "n_actions": len(ROWS),+ "fell_at": chk.get("fell_at"), "worst_lin_err": chk.get("worst_lin_err"), "worst_yaw_err": chk.get("worst_yaw_err"),+ "tilt_deg": chk.get("tilt_deg"), "imu_height": chk.get("imu_height"), "pose_angle_deg": chk.get("pose_angle_deg"),+ **EP.final_fields()}+++def finish(reason: str) -> None:+ """The episode is over: the task's check on the steps executed, then the record for the collect hook."""+ if E["done"]:+ return+ E["done"] = True+ E["reason"] = reason+ E["t_end"] = time.time()+ E["episode_control_steps"] = ctrl_steps()+ try:+ chk = S.check()+ E["check"] = {k: v for k, v in chk.items() if k != "segments"}+ E["success"] = bool(chk["success"])+ except Exception: # noqa: BLE001+ traceback.print_exc()+ EP.log({"ev": "end", "reason": reason, "step": E["step"], "control_steps": ctrl_steps(), "success": bool(E["success"])})+ dump()+++def dump() -> None:+ if E.get("dumped"):+ return+ E["dumped"] = True+ E["live_sha"] = S.state_sha()+ np.savez(os.path.join(DATA, "trajectory.npz"), actions=np.asarray(ROWS, dtype=np.float64).reshape(-1, Q.N),+ env=S.env, action_layout=",".join(S.joint_names))+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})+ write_final()+++def after_step() -> None:+ if S.kind in ("joystick", "stand_on_two") and S.fell_at is not None:+ finish("fell")+ elif S.kind in ("getup", "stand_on_two") and S.check()["success"]:+ finish("success")+ elif S.done:+ finish("horizon")+++def ctrl_step(a, rec) -> bool:+ """One executed control step, journaled. True when the call must stop here."""+ S.step(a)+ ROWS.append(np.asarray(a, dtype=np.float64))+ stop = EP.journal(a)+ rec.tick()+ after_step()+ return E["done"] or stop+++def recorder(cams, fps: int, meta: dict) -> L.Recorder:+ return L.Recorder(cams, max(1, int(round(CTRL_HZ / max(1, fps)))), grab, proprio_row, extrinsics, ctrl_steps,+ depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+++def video_fps(meta: dict) -> int:+ fps = meta.get("video_fps")+ if fps is None:+ return 10+ if isinstance(fps, bool) or not isinstance(fps, (int, float)) or not (1 <= fps <= 50):+ raise ValueError("video_fps must be in [1, 50]")+ return int(fps)+++def cameras_of(meta: dict) -> list:+ cams = meta.get("cameras") or ["track"]+ bad = [c for c in cams if c not in CAMS]+ if bad:+ raise ValueError(f"unknown cameras {bad}; cameras: {CAMS}")+ return list(cams)+++def meta_common(cams) -> dict:+ n = ctrl_steps()+ out = {"step": E["step"], "calls": E["calls"], "control_steps": n, "physics_steps": n * SUBSTEPS,+ "sim_time_s": round(n * DT, 3), "time_s": round(time.time() - E["t0"], 2),+ "time_left_s": max(0.0, round(WALL_CLOCK_S - (time.time() - E["t0"]), 1)),+ "proprio": {"layout": PROPRIO_LAYOUT, "now": proprio_row().tolist()}, "done": E["done"], "reason": E["reason"],+ "cameras": {c: camera_info(c) for c in cams}}+ if S.kind == "joystick":+ out["command_now"] = dict(zip(("vx_mps", "vy_mps", "wz_radps"), S.command_now().round(4).tolist()))+ return out+++def do_submit(meta: dict, A: np.ndarray):+ typ = meta.get("type")+ if typ == "done":+ rec = recorder(cameras_of(meta), 5, meta)+ rec.tick(force=True, last=True) # every response carries the last frames+ E["calls"] += 1+ finish("done")+ return {**meta_common(cameras_of(meta)), "chunk_id": E["calls"], "type": typ, "executed_rows": 0, "ok": True}, rec.parts("none", 5)+ if typ != "joint_position":+ raise ValueError(f"type must be joint_position or done (not yet: {SPEC['action_types']['not_yet']})")+ dt = float(meta.get("dt", DT))+ interp = meta.get("interpolate", "linear")+ video = meta.get("video", "mp4")+ cams, fps = cameras_of(meta), video_fps(meta)+ k = dt / DT+ if A.ndim != 2 or A.shape[1] != Q.N:+ raise ValueError(f"joint_position actions must be (T, {Q.N}), got {list(A.shape)}")+ if not np.all(np.isfinite(A)):+ raise ValueError("actions contain NaN/inf")+ if not (math.isfinite(dt) and dt <= 0.5 + 1e-9 and round(k) >= 1 and abs(k - round(k)) < 1e-6):+ raise ValueError(f"dt must be a whole multiple of the {DT:g} s control period and at most 0.5 s; got {dt}")+ if A.shape[0] * dt > MAX_CHUNK_S + 1e-9:+ raise ValueError(f"chunk longer than max_chunk_s={MAX_CHUNK_S}: {A.shape[0]} rows x {dt} s")+ if interp not in ("hold", "linear"):+ raise ValueError("interpolate must be hold|linear")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, clipped = recorder(cams, fps, meta), []+ E["calls"] += 1+ step0, before = E["step"], ctrl_steps()+ rec.tick(force=True)+ prev = S.targets.copy()+ for ri, row in enumerate(A):+ E["step"] += 1+ target = np.clip(row, LIMITS[:, 0], LIMITS[:, 1])+ for j in np.flatnonzero(target != row)[:20]:+ clipped.append({"row": ri, "index": int(j), "reason": f"{S.joint_names[j]} limit [{LIMITS[j, 0]:g}, {LIMITS[j, 1]:g}]"})+ n = int(round(k))+ stop = False+ for s in range(1, n + 1):+ a = target if interp == "hold" else prev + (target - prev) * (s / n)+ if ctrl_step(a, rec):+ stop = True+ break+ prev = target+ if stop:+ break+ rec.tick(force=True, last=True)+ out = {**meta_common(cams), "chunk_id": E["calls"], "type": typ, "executed_rows": E["step"] - step0,+ "control_steps_chunk": ctrl_steps() - before, "physics_steps_chunk": (ctrl_steps() - before) * SUBSTEPS,+ "clipped": clipped[:200], "n_clipped": len(clipped), "plan": [], "ok": True}+ EP.log({"ev": "submit", "call": E["calls"], "rows": E["step"] - step0, "dt": dt, "interpolate": interp, "cameras": cams,+ "control_steps": ctrl_steps() - before, "n_clipped": len(clipped), "note": (meta.get("note") or "")[:500],+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video, fps)+++def do_observe(meta: dict):+ cams, fps = cameras_of(meta), video_fps(meta)+ seconds = float(meta.get("seconds", 0))+ video = meta.get("video", "frames")+ if not math.isfinite(seconds) or seconds < 0 or seconds > MAX_WATCH_S:+ raise ValueError(f"seconds must be in [0, {MAX_WATCH_S}]")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, before = recorder(cams, fps, meta), ctrl_steps()+ if seconds > 0 and not E["done"]:+ rec.tick(force=True)+ hold = S.targets.copy()+ for _ in range(int(round(seconds / DT))):+ if ctrl_step(hold, rec):+ break+ rec.tick(force=True, last=True)+ E["calls"] += 1+ out = {**meta_common(cams), "obs_id": E["calls"], "seconds": seconds, "control_steps_watch": ctrl_steps() - before,+ "physics_steps_watch": (ctrl_steps() - before) * SUBSTEPS, "ok": True}+ EP.log({"ev": "observe", "call": E["calls"], "seconds": seconds, "cameras": cams, "control_steps": ctrl_steps() - before,+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video if seconds > 0 else ("frames" if video == "mp4" else video), fps)+++def status() -> dict:+ return {"step": E["step"], "calls": E["calls"], "control_steps": ctrl_steps(), "done": E["done"], "reason": E["reason"],+ "elapsed_s": round(time.time() - E["t0"], 1)}+++def end_from_signal() -> None:+ """The collect hook's SIGUSR1: end the episode (the agent's time is over), dump it, exit so the replays can start."""+ with LOCK:+ E["exiting"] = True+ if not E["done"]:+ finish("timeout")+ EP.log({"ev": "exit", "reason": "collect hook: episode dumped"})+ if not os.path.exists(PID_FILE):+ open(PID_FILE, "w").write(str(os.getpid()))+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(0)+++def replay_row(row) -> None:+ """A journaled row during a resume."""+ S.step(row)+ ROWS.append(np.asarray(row, dtype=np.float64))+++EP.begin(state=E, step=replay_row, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, on_end=end_from_signal,+ start_event={"env": S.env, "seed": S.inst.get("seed"), "cameras": CAMS})+if E["done"]:+ dump() # resumed after the episode had ended: the record is rewritten from the replay+E["ready"] = True+write_final()+open(PID_FILE, "w").write(str(os.getpid()))+print(f"{L.PROTOCOL} MuJoCo Playground quadruped sim ready ({S.env}; startup {EP.n_startups}, resumes {EP.resumes})", flush=True)+L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics, status=status,+ on_submit_error=lambda exc: finish("error"), log=EP.log, episode=EP, state_sha=S.state_sha,+ proprio=proprio_row), port=int(os.environ.get("RCB_PORT", "8000")))diff --git a/tasks/mujoco_playground_go1_getup-standard/instruction.md b/tasks/mujoco_playground_go1_getup-standard/instruction.mdnew file mode 100644index 0000000000..3f6d326af5--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/instruction.md@@ -0,0 +1,46 @@+# MuJoCo Playground · Go1Getup — STANDARD MODE (robot as a service, eai-standard/2.2)++**Task:** The Unitree Go1 has fallen over. Make it get up and stand upright at its standing height.++You control the Unitree Go1 quadruped — **as if it were real hardware** — in one episode of MuJoCo Playground's+`Go1Getup` environment (plain MuJoCo 3.3.7 with Playground's scene, commit 4057c14). The simulator runs in a service you+cannot open. You get one client and one episode.++## The episode+The robot was dropped from 0.5 m in a random orientation with random joint angles and a random base velocity and settled for 0.5 s with its joints held: at the start it lies with its trunk tilted 110 deg from upright. You have 300 control steps (6 s).++## Rules (real-robot rules)+- **No reset.** One episode. You see four cameras that follow the robot (RGB, depth if you ask) and the robot's own+ sensors: joint positions, velocities and torques, the IMU (gyro, accelerometer, gravity's direction, the trunk's+ velocity), foot contacts. No world positions, no success check.+- **The episode ends** the moment the robot has been upright for 25 control steps in a row (success), after 300 control steps (`spec["max_control_steps"]`, counted by `meta["control_steps"]`), when you submit `done`, or when your time is up.+- **Success** is 25 control steps in a row with the trunk within 10 deg of upright and the IMU at least 0.22 m above the floor (the Go1 stands at 0.255-0.26 m), judged after every control step; when the episode ends otherwise, it is judged on its last control steps.+- Your wall-clock budget is 3600 s from your start. Simulated time only advances with your commands (and+ `get_obs(seconds=...)`, which holds the current targets).+- Nothing to hand in: the service records the episode and grades it. Leave your script at `/app/output/gen.py`.+- **If the service crashes**, a call fails with a connection error: it restarts and resumes the SAME episode (never a+ reset) in the state after the last call it completed. `r.wait_ready()` waits for it; then check `r.status()`.+- Nothing is put into your context automatically: images come back as arrays in Python objects.++## Client (`/opt/tools/rcb_client.py`)+```python+from rcb_client import Robot+r = Robot() # connects (waits while the service starts)+spec = r.spec() # action types, limits, cameras, robot_spec (home pose, gains), kinematics+obs = r.get_obs() # obs.last[cam] -> uint8 (240, 320, 3); obs.meta["proprio"] {"layout", "now"}+res = r.submit("joint_position", A, dt=0.02) # A: (T, 12) rows dt apart; res.proprio (one row per frame), res.meta+obs = r.get_obs(seconds=1.0, video="mp4") # hold the current targets and watch for 1 s (max 30)+r.fk(q); r.ik({"FR": [x, y, z, 1, 0, 0, 0]}, seed=q) # feet in the trunk frame <-> joints (no physics)+r.submit("done", []) # end the episode now+r.status() # calls, control steps, done, reason, elapsed time+```+Cameras: `track`, `side`, `back`, `top` (they follow the robot); `spec["cameras"]` gives each one's mounting and intrinsics, and every response carries its pose. Proprioception (`spec["proprio_groups"]`): `joint_pos`, `joint_vel`, `joint_effort` (12 each, action+order), `imu_gyro`, `imu_accelerometer`, `imu_gravity`, `imu_linvel` (3 each, IMU frame: x forward, y left, z up),+`foot_contact` (FR, FL, RR, RL).++### `joint_position` (12)+FR, FL, RR, RL legs, each hip (abduction), thigh (hip pitch), calf (knee): absolute targets of the joint position actuators (rad; kp = 35 N m/rad, joint damping 0.5 N m s/rad).+Rows are `dt` apart (a whole multiple of the 0.02 s control period, at most 0.5 s), `interpolate="linear"` (default) or+`"hold"` between rows; a chunk covers at most 10 s; values outside the limits+(`spec["action_types"]["joint_position"]["limits"]`) are clipped and listed in `res.meta["clipped"]`. Feedback control+means short chunks: each response tells you where the robot is now.diff --git a/tasks/mujoco_playground_go1_getup-standard/solution/oracle.npy b/tasks/mujoco_playground_go1_getup-standard/solution/oracle.npynew file mode 100644index 0000000000..dc3c74e7b0Binary files /dev/null and b/tasks/mujoco_playground_go1_getup-standard/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_go1_getup-standard/solution/oracle_replay.py b/tasks/mujoco_playground_go1_getup-standard/solution/oracle_replay.pynew file mode 100644index 0000000000..b6a9824592--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/solution/oracle_replay.py@@ -0,0 +1,42 @@+"""Oracle (standard mode): streams the reference rows (one per 1/50 s control step, `hold`) as `joint_position` chunks+through the client, the same interface an agent has. Uses no privileged information at run time; the service's recorded+trajectory is then exactly the privileged reference. If the service crashes it resumes the same episode+(spec["on_service_error"]): the oracle waits until it answers again and goes on from the control step it reports."""+import os+import sys+import time++import numpy as np+import requests++sys.path.insert(0, "/opt/tools")+from rcb_client import EpisodeOver, Robot # noqa: E402++Q = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy")).astype(np.float64)+r = Robot()+spec = r.spec()+dt = 1.0 / float(spec["control_hz"])+per_chunk = max(1, int(spec.get("max_chunk_s", 10) / dt + 1e-9))+print("spec:", spec["protocol"], "rows:", len(Q), flush=True)+t0, i = time.time(), 0+while i < len(Q):+ chunk = Q[i:i + per_chunk]+ try:+ res = r.submit("joint_position", chunk, dt=dt, interpolate="hold", cameras=["track"], video="none", note=f"oracle rows {i}+")+ except EpisodeOver as e:+ print("episode over:", e)+ break+ except requests.exceptions.RequestException as e: # the service crashed: it restarts and resumes the same episode+ print("service unreachable:", repr(e)[:200], "- waiting for it to resume", flush=True)+ st = r.wait_ready()+ n = int(st["control_steps"])+ if not i <= n <= i + len(chunk):+ raise SystemExit(f"resumed at control step {n}: outside the chunk in flight (rows {i}..{i + len(chunk)})")+ i = n+ continue+ n = int(res.meta["control_steps"])+ print(f"rows {i}..{n}: clipped={res.meta['n_clipped']} done={res.meta['done']} reason={res.meta['reason']}", flush=True)+ if res.meta["done"] or n <= i:+ break+ i = n+print("status:", r.status(), "wall %.0fs" % (time.time() - t0))diff --git a/tasks/mujoco_playground_go1_getup-standard/solution/solve.sh b/tasks/mujoco_playground_go1_getup-standard/solution/solve.shnew file mode 100755index 0000000000..ecb1f6c954--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/solution/solve.sh@@ -0,0 +1,8 @@+#!/bin/bash+# Oracle (standard mode): streams the reference trajectory's joint targets (solution/oracle.npy, one row per control step)+# as `joint_position` chunks through the client. Uses no privileged information at run time (only the pre-recorded+# targets); the service's recorded trajectory is then exactly the privileged reference.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_go1_getup-standard/task.toml b/tasks/mujoco_playground_go1_getup-standard/task.tomlnew file mode 100644index 0000000000..56a7843753--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/task.toml@@ -0,0 +1,54 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = [+ { source = "/data/final.json", service = "sim" },+ { source = "/data/episode.jsonl", service = "sim" },+ { source = "/data/trajectory.npz", service = "sim" },+ { source = "/data/replay.mp4", service = "sim" },+ { source = "/data/server.log", service = "sim" }, # the service's own output (Harbor keeps none)+ { source = "/data/journal.f64", service = "sim" }, # crash recovery: every executed control step (float64 rows)+ { source = "/data/startups.jsonl", service = "sim" }, # crash recovery: one line per service start+ { source = "/data/replay1.log", service = "sim" }, # the collect hook's two fresh-process replays+ { source = "/data/replay2.log", service = "sim" },+ { source = "/data/replay3.log", service = "sim" }, # and its third, which renders replay.mp4+ "/app/output/",+]++[task]+name = "robot-coding-bench/mujoco_playground_go1_getup-standard"+description = "STANDARD MODE (robot as a service, eai-standard/2.2): MuJoCo Playground Go1Getup (Unitree Go1) on the same frozen instance as mujoco_playground_go1_getup-privileged: The Unitree Go1 has fallen over. Make it get up and stand upright at its standing height. The agent only gets a client: four cameras that follow the robot (RGB, optional depth), the robot's joints and IMU, joint position chunks at 50 Hz, the feet's kinematics; one episode, no reset, no world state; the sim service records the episode, replays it in fresh processes and grades it."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "unitree-go1", "quadruped", "locomotion", "getup", "code-as-policy", "trajectory", "standard-mode"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "unitree-go1"+family = "mujoco_playground/Go1Getup"+mode = "standard"+protocol = "eai-standard/2.2"+oracle = "full"+instance_seed = 5+expert_time_estimate_hours = 3.0++[verifier]+timeout_sec = 600.0+environment_mode = "separate"+network_mode = "no-network"++[[verifier.collect]]+service = "sim"+command = "sh /srv/finalize.sh" # end + dump + exit the service, replay twice in fresh processes, write final.json, video+timeout_sec = 1200++[agent]+timeout_sec = 3600.0+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_go1_getup-standard/tests/Dockerfile b/tasks/mujoco_playground_go1_getup-standard/tests/Dockerfilenew file mode 100644index 0000000000..26bc699ebe--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/tests/Dockerfile@@ -0,0 +1,5 @@+# Separate verifier sandbox: grades the sim service's own artifacts; needs nothing but python (the shared client base).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY test.sh /tests/test.sh+COPY grade.py /tests/grade.py+RUN chmod +x /tests/test.shdiff --git a/tasks/mujoco_playground_go1_getup-standard/tests/grade.py b/tasks/mujoco_playground_go1_getup-standard/tests/grade.pynew file mode 100644index 0000000000..5b990bf458--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/tests/grade.py@@ -0,0 +1,64 @@+"""Standard-mode verifier (MuJoCo Playground quadrupeds): reads what the sim service (which the agent could not touch) wrote:+/data/final.json (live success, two fresh-process replays of the recorded trajectory, determinism, crash-recovery+fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, the+replays having started in the instance's t = 0 state. Numeric-only reward.json."""++import json, os, shutil++LOG = "/logs/verifier"+os.makedirs(LOG, exist_ok=True)+++def write(ok, out):+ open(f"{LOG}/reward.txt", "w").write("1\n" if ok else "0\n")+ json.dump(out, open(f"{LOG}/reward.json", "w"))+ print(out)+++p = "/data/final.json"+if not os.path.exists(p):+ write(False, {"success": 0, "missing_log": 1, "grader_error": 0, "infra_error": 0})+ raise SystemExit+d = json.load(open(p))+for f in ("replay.mp4", "trajectory.npz", "episode.jsonl"):+ if os.path.exists(f"/data/{f}"):+ shutil.copy(f"/data/{f}", f"{LOG}/{f}")+ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic"))+ok = ok and not d.get("instance_mismatch")+num = lambda k: float(d.get(k) or 0) # noqa: E731+write(+ ok,+ {+ "success": int(ok),+ "live_success": int(bool(d.get("success"))),+ "replay_success": int(bool(d.get("replay_success"))),+ "deterministic": int(bool(d.get("deterministic"))),+ "live_matches_replay": int(bool(d.get("live_matches_replay"))),+ "finalized": int(bool(d.get("finalized"))),+ "n_actions": int(d.get("n_actions") or 0),+ "sim_steps": int(d.get("control_steps") or 0),+ "physics_steps": int(d.get("physics_steps") or 0),+ "steps": int(d.get("steps") or 0),+ "elapsed_s": float(d.get("elapsed_s") or 0),+ "video_rendered": int(bool(d.get("video"))),+ "fell": int(d.get("fell_at") is not None),+ "worst_lin_err": float(d["worst_lin_err"]) if d.get("worst_lin_err") is not None else -1.0,+ "worst_yaw_err": float(d["worst_yaw_err"]) if d.get("worst_yaw_err") is not None else -1.0,+ "end_tilt_deg": float(d["tilt_deg"]) if d.get("tilt_deg") is not None else -1.0,+ "end_imu_height": float(d["imu_height"]) if d.get("imu_height") is not None else -1.0,+ "end_pose_angle_deg": float(d["pose_angle_deg"]) if d.get("pose_angle_deg") is not None else -1.0,+ # a replay process gave no result, or the image no longer builds the frozen start: not the agent's 0+ "grader_error": int(bool(d.get("replay_failed") or d.get("instance_mismatch"))),+ "instance_mismatch": int(bool(d.get("instance_mismatch"))),+ # an infrastructure failure, not the agent's (PROTOCOL §2.6): a give-up after crashes between calls or a failed+ # resume (docs/STANDARD_MODE_2_2.md §13), the service not ending its episode for the collect hook, a replay+ # process that gave no result, replays that did not start in the instance's t = 0 state+ "infra_error": int(bool(d.get("infra_error"))),+ "gave_up": int(bool(d.get("gave_up"))),+ "sim_error": int(d.get("reason") == "error"),+ "sim_startups": int(d.get("sim_startups") or 0),+ "resumes": int(d.get("resumes") or 0),+ "resume_state_mismatch": int(d.get("resume_state_mismatch") or 0),+ "resume_max_joint_dev": num("resume_max_joint_dev"),+ },+)diff --git a/tasks/mujoco_playground_go1_getup-standard/tests/test.sh b/tasks/mujoco_playground_go1_getup-standard/tests/test.shnew file mode 100755index 0000000000..bc608aa8b9--- /dev/null+++ b/tasks/mujoco_playground_go1_getup-standard/tests/test.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Verifier (separate sandbox): the sim sidecar's artifacts were uploaded to /data by Harbor.+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)+mkdir -p /logs/verifier+python /tests/grade.py 2> /logs/verifier/grade.logdiff --git a/tasks/mujoco_playground_go1_handstand-privileged/README.md b/tasks/mujoco_playground_go1_handstand-privileged/README.mdnew file mode 100644index 0000000000..07121f9263--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-privileged/README.md@@ -0,0 +1,42 @@+# mujoco_playground_go1_handstand-privileged++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | privileged |+| Twin | `mujoco_playground_go1_handstand-standard` |+| Simulator / robot | `mujoco` / `unitree-go1` |+| Family / instance | `mujoco_playground/Go1Handstand` / seed 0 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `Go1Handstand` (Unitree Go1), rebuilt in plain MuJoCo from Playground's scene files: Make the Unitree Go1 do a handstand: balance on its front legs, nose down, hind legs in the air, for 2 s.+From standing, it has 10 s to get into a handstand on its front legs and hold it for 2 s (Playground's handstand reward aims at the IMU 0.55 m high). The deliverable is one replayable trajectory of joint position targets+(`/app/output/trajectory.npz`, `(T, 12)`, 1 <= T <= 500).++## Difficulty+Dynamic balance on two legs: the robot has to throw its weight onto its front legs, lift the other pair and then balance an inverted, top-heavy body on two small feet with 35 N m/rad position drives, correcting continuously; a front leg touching the floor or a tip-over ends it. Playground's handstand is trained with 100 M steps of PPO.++## Reference solution+A policy trained here on Playground's Go1Handstand reward (PPO on the CPU, `scripts/mujoco-playground/train/`, not in the image), run closed loop with Playground's action semantics (targets accumulate) until the hold completes (`scripts/mujoco-playground/oracle.py`): 115 control steps, pose angle 13.8 deg and IMU at 0.531 m at the end. Replayed by `solution/solve.sh` (`solution/oracle.npy`, 115 rows); the rows are float32-exact, so the+standard twin's client executes the same targets. Re-verified by `scripts/mujoco-playground/select_instances.py`: two+fresh-process replays succeed and end in the same state.++## Verification+`tests/grade.py` in a separate sandbox without network: two replays, each in a fresh process, from the verifier's own+copy of the instance (`tests/instance.json`; the start state is checked against its hash on every load); pass iff both+succeed and end in the same state (`deterministic`). Oracle: success after 115 control steps. `nop`: no trajectory, reward 0.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `locomotion/go1/xmls/scene_mjx_flat_terrain.xml`; MuJoCo Menagerie @ 1b86ece (`unitree_go1`); simulated in MuJoCo 3.3.7 on the CPU |+| Instance | Playground's `reset` with `jax.random.PRNGKey(0)` (xy, yaw and base velocity); chosen by `scripts/mujoco-playground/select_instances.py` (seed 0; the first candidate) |+| Actions | 12 joint position targets per control step (0.02 s of simulated time); kp = 35 N m/rad, joint damping 0.5 N m s/rad |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py` from `scripts/mujoco-playground/instances/Go1Handstand.json`+(`make_instances.py`, `select_instances.py`) and `scripts/mujoco-playground/oracles/Go1Handstand.npy` (`oracle.py`).diff --git a/tasks/mujoco_playground_go1_handstand-privileged/environment/Dockerfile b/tasks/mujoco_playground_go1_handstand-privileged/environment/Dockerfilenew file mode 100644index 0000000000..7bdd7d2938--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-privileged/environment/Dockerfile@@ -0,0 +1,8 @@+# MuJoCo Playground quadruped task (privileged): plain MuJoCo with Playground's and Menagerie's assets+# (images/mujoco/prepare_assets.sh), the task's tooling and its frozen instance.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY instance.json /app/instance.json+COPY rcb_quadruped.py /opt/tools/rcb_quadruped.py+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_go1_handstand-privileged/environment/instance.json b/tasks/mujoco_playground_go1_handstand-privileged/environment/instance.jsonnew file mode 100644index 0000000000..253a2a549f--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-privileged/environment/instance.json@@ -0,0 +1,67 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1Handstand",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ -0.3957096338272095,+ -0.1560124158859253,+ 0.27799999713897705,+ 0.2572470009326935,+ 0.0,+ 0.0,+ -0.9663457870483398,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842+ ],+ "qvel0": [+ -0.4893399477005005,+ 0.021045565605163574,+ 0.45396435260772705,+ -0.16251015663146973,+ -0.030068635940551758,+ -0.1645064353942871,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "text": "Make the Unitree Go1 do a handstand: balance on its front legs, nose down, hind legs in the air, for 2 s.",+ "facts": {+ "start_xy_m": [+ -0.396,+ -0.156+ ],+ "start_yaw_deg": -150.2,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.272,+ "reference_rows": 115,+ "reference_imu_height": 0.5314,+ "reference_pose_angle_deg": 13.82+ },+ "state_sha": "edd665f20ded",+ "horizon": 500,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_go1_handstand-privileged/environment/rcb_quadruped.py b/tasks/mujoco_playground_go1_handstand-privileged/environment/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-privileged/environment/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_go1_handstand-privileged/instruction.md b/tasks/mujoco_playground_go1_handstand-privileged/instruction.mdnew file mode 100644index 0000000000..c267d71f5b--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-privileged/instruction.md@@ -0,0 +1,48 @@+# MuJoCo Playground · Go1Handstand — frozen episode++**Task:** Make the Unitree Go1 do a handstand: balance on its front legs, nose down, hind legs in the air, for 2 s.++You control the Unitree Go1 quadruped in one episode of MuJoCo Playground's `Go1Handstand` environment, rebuilt in plain+MuJoCo 3.3.7 from Playground's own scene files (Apache-2.0, commit 4057c14) and the robot from MuJoCo Menagerie. The+episode is frozen: it starts the same way after every reset (Playground's `reset` with seed 0), and you may reset+as often as you like. Your deliverable is **one open-loop trajectory**, not a general policy.++## The episode+The robot starts at Playground's `home` pose, its base moved to (-0.396, -0.156) m, turned to a yaw of -150.2 deg, with a random base velocity (Playground's reset). You have 500 control steps (10 s).++## Success+Success iff the trajectory (at most 500 rows) ends with 100 control steps in a row (2 s) after each of which the trunk's forward axis (the IMU frame's x axis) is within 30 deg of straight down, the IMU is at least 0.4 m above the floor and the hind (RR, RL) feet are off the ground; and no control step before its end meets Playground's termination rule: the trunk's up axis below -0.25 (z component of the IMU frame's z axis), or any part of a front leg other than its foot (thigh, calf, hip) touching the floor. End the trajectory once the hold is complete. `s.check()` reports `fell_at`, the last pose angle and height, and `success`.++## Deliverable+`/app/output/trajectory.npz` with `actions`: float64 (T, 12), one row per control step (0.02 s): absolute targets of+the 12 joint position actuators, in `s.joint_names` order (FR, FL, RR, RL legs, each hip (abduction), thigh (hip pitch), calf (knee)), in radians; 1 <= T <= 500. Values+outside the actuator ranges (`s.lower`, `s.upper`) are clipped. `s.save_trajectory(rows)` writes it. Also leave the+script that produced it at `/app/output/gen.py`. Save a working trajectory as soon as you have one and overwrite it as+you improve it: whatever is in `/app/output/` when your 3600 s are up is graded. The tooling logs your sessions and+resets (cost accounting, not graded).++## Tooling (installed; `python` from any directory)+```python+from rcb_quadruped import Session+s = Session("/app/instance.json") # the frozen episode at t = 0 (checked against the instance's state hash)+s.joint_names; s.lower; s.upper # the actuator order and ranges (rad)+s.home # Playground's standing pose (its `home` keyframe), in that order+s.step(row) # one control step: 12 joint targets, 5 physics steps of 0.004 s; returns s.check()+s.check() # the task's check on the steps so far (see Success)+s.state() # qpos, qvel, IMU (local_linvel, gyro, gravity, accelerometer, pose), feet, contacts+s.sensor(name); s.gravity() # one MuJoCo sensor; gravity's direction in the IMU frame+s.model, s.data # the live MuJoCo model and data (read them; changing them is not part of the replay)+s.render(cam); s.cameras # uint8 (240, 320, 3) from cameras that follow the robot: `track`, `side`, `back`, `top` (they follow the robot)+s.reset() # back to t = 0+s.replay(rows) # reset, run the rows, return the check and the final state's hash+s.render_video(rows, "/app/output/try.mp4")+s.save_trajectory(rows, "/app/output/trajectory.npz")+```+The grader runs exactly this CLI in two fresh processes, so run it to check yourself:+`python /opt/tools/rcb_quadruped.py replay --instance /app/instance.json --traj /app/output/trajectory.npz`++## Conventions+- Joint position actuators (PD): kp = 35 N m/rad, joint damping 0.5 N m s/rad, as Playground's environment sets them; the physics step is 0.004 s,+ the control step 0.02 s (5 physics steps); a row holds until the next one.+- World frame z up, metres; quaternions **wxyz**. The IMU frame is the trunk's: x forward, y left, z up.+- Physics is MuJoCo on the CPU: the same rows from the same start give the same result in every fresh process.diff --git a/tasks/mujoco_playground_go1_handstand-privileged/solution/oracle.npy b/tasks/mujoco_playground_go1_handstand-privileged/solution/oracle.npynew file mode 100644index 0000000000..92f939ea5bBinary files /dev/null and b/tasks/mujoco_playground_go1_handstand-privileged/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_go1_handstand-privileged/solution/oracle_replay.py b/tasks/mujoco_playground_go1_handstand-privileged/solution/oracle_replay.pynew file mode 100644index 0000000000..46987df1d0--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-privileged/solution/oracle_replay.py@@ -0,0 +1,15 @@+"""Oracle (privileged): replay the reference rows in the tooling, check them, and save them as the deliverable."""+import json+import os+import sys++import numpy as np++sys.path.insert(0, "/opt/tools")+from rcb_quadruped import Session # noqa: E402++rows = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy"))+s = Session("/app/instance.json")+r = s.replay(rows)+s.save_trajectory(rows, "/app/output/trajectory.npz", meta={"source": "reference trajectory (solution/oracle.npy)"})+print(json.dumps({k: v for k, v in r.items() if k != "segments"}))diff --git a/tasks/mujoco_playground_go1_handstand-privileged/solution/solve.sh b/tasks/mujoco_playground_go1_handstand-privileged/solution/solve.shnew file mode 100755index 0000000000..430ffb6017--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-privileged/solution/solve.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Oracle (privileged): write the reference trajectory frozen at generation time (solution/oracle.npy; how it was made:+# scripts/mujoco-playground/oracle.py) as the deliverable.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_go1_handstand-privileged/task.toml b/tasks/mujoco_playground_go1_handstand-privileged/task.tomlnew file mode 100644index 0000000000..8b063574c6--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-privileged/task.toml@@ -0,0 +1,43 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = ["/app/output/", "/logs/agent/rcb/"]++[task]+name = "robot-coding-bench/mujoco_playground_go1_handstand-privileged"+description = "MuJoCo Playground Go1Handstand in plain MuJoCo (Unitree Go1, joint position control every 0.02 s): Make the Unitree Go1 do a handstand: balance on its front legs, nose down, hind legs in the air, for 2 s. Produce one replayable trajectory of joint position targets on a frozen instance (Playground's reset with seed 0); graded by a handstand held for the trajectory's last 2 s, without a termination (two fresh-process replays)."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "unitree-go1", "quadruped", "locomotion", "stand_on_two", "code-as-policy", "trajectory", "privileged"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "unitree-go1"+family = "mujoco_playground/Go1Handstand"+mode = "privileged"+oracle = "full"+instance_seed = 0 # the PRNGKey of Playground's reset (and, for the joystick tasks, its command process)+expert_time_estimate_hours = 3.0++[verifier]+timeout_sec = 1200.0+environment_mode = "separate"+network_mode = "no-network"++[verifier.environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192++[agent]+timeout_sec = 3600.0+# MuJoCo Playground's trained policies are public upstream, so the agent reaches the model APIs and nothing else+# (scripts/set_agent_egress.py HOSTS).+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_go1_handstand-privileged/tests/Dockerfile b/tasks/mujoco_playground_go1_handstand-privileged/tests/Dockerfilenew file mode 100644index 0000000000..f49c79154d--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-privileged/tests/Dockerfile@@ -0,0 +1,7 @@+# Separate verifier sandbox (PROTOCOL §4): the same image with the verifier's own copies of the tooling and the frozen+# instance. Nothing the agent did in its container reaches this one: Harbor uploads only the declared artifacts.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY grade.py instance.json rcb_quadruped.py test.sh /tests/+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier+ENV PYTHONPATH=/tests+WORKDIR /testsdiff --git a/tasks/mujoco_playground_go1_handstand-privileged/tests/grade.py b/tasks/mujoco_playground_go1_handstand-privileged/tests/grade.pynew file mode 100644index 0000000000..e5668de85f--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-privileged/tests/grade.py@@ -0,0 +1,126 @@+"""Verifier (privileged): replay /app/output/trajectory.npz from the frozen instance and write Harbor's rewards.++ python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz++Two replays, each in its own fresh process (`rcb_quadruped.py replay`: the frozen start, one control step per row, the+task's success check on the whole trajectory). success = both replays succeed and end in the same state. Writes+/logs/verifier/reward.txt (1/0) and reward.json (numbers only); then a third replay renders replay.mp4, after the+verdict is on disk (it never changes it).+"""+import argparse+import json+import os+import subprocess+import sys+import tempfile+import traceback++import numpy as np++LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")+TOOL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_quadruped.py")+REPLAY_TIMEOUT_S = 300 # a 1000-step replay takes a few seconds; the video replay renders 4 views every 2nd step+++def write(ok: bool, out: dict) -> None:+ os.makedirs(LOG_DIR, exist_ok=True)+ open(os.path.join(LOG_DIR, "reward.txt"), "w").write("1\n" if ok else "0\n")+ json.dump(out, open(os.path.join(LOG_DIR, "reward.json"), "w"))+ print(json.dumps(out), flush=True)+++def agent_cost() -> dict:+ """Self-reported cost from the tooling's log in the agent's container (accounting, not evidence)."""+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_replays": 0, "agent_cost_self_reported": 1}+ for path in ("/logs/agent/rcb/rcb_session_log.jsonl", "/app/output/rcb_session_log.jsonl"):+ if not os.path.exists(path):+ continue+ try:+ with open(path) as f:+ for i, line in enumerate(f):+ if i > 200_000 or len(line) > 10_000:+ break+ try:+ e = json.loads(line)+ ev = e.get("ev") if isinstance(e, dict) else None+ if ev == "session_start":+ cost["agent_sessions"] += 1+ elif ev == "reset":+ cost["agent_resets"] += 1+ elif ev == "replay":+ cost["agent_replays"] += 1+ elif ev == "session_end":+ cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)+ except Exception: # noqa: BLE001 -- one bad line must not sink the verdict+ continue+ except OSError:+ pass+ break+ return cost+++def replay(instance: str, traj: str, video: str | None) -> dict:+ """One replay in a fresh process; its result (`--out`), or {"error": ...}."""+ with tempfile.NamedTemporaryFile(suffix=".json") as out:+ cmd = [sys.executable, TOOL, "replay", "--instance", instance, "--traj", traj, "--out", out.name]+ try:+ p = subprocess.run(cmd + (["--video", video] if video else []), stdout=subprocess.DEVNULL, stderr=sys.stderr,+ timeout=REPLAY_TIMEOUT_S, env={**os.environ, "RCB_SESSION_LOG": "", "RCB_AGENT_TRACE_DIR": ""})+ except subprocess.TimeoutExpired:+ return {"error": f"replay took over {REPLAY_TIMEOUT_S} s"}+ try:+ return json.load(open(out.name))+ except ValueError:+ return {"error": f"replay process rc={p.returncode}"}+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--instance", required=True)+ ap.add_argument("--traj", default="/app/output/trajectory.npz")+ a = ap.parse_args()+ cost = agent_cost()+ if not os.path.isfile(a.traj):+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost})+ return 0+ try:+ horizon = int(json.load(open(a.instance))["horizon"])+ d = np.load(a.traj, allow_pickle=False)+ acts = np.asarray(d["actions"], dtype=np.float64) if "actions" in d.files else np.zeros((0, 0))+ if acts.ndim != 2 or acts.shape[1] != 12 or len(acts) > horizon or not np.all(np.isfinite(acts)):+ write(False, {"success": 0, "bad_trajectory": 1, "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0,+ "grader_error": 0, **cost})+ return 0+ runs = [replay(a.instance, a.traj, None), replay(a.instance, a.traj, None)]+ if any("error" in r and not r.get("bad_trajectory") for r in runs):+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ if not all(r.get("instance_ok") for r in runs): # the image no longer builds the frozen start: not the agent's 0+ write(False, {"success": 0, "grader_error": 1, "instance_mismatch": 1, **cost})+ return 0+ all_success = all(bool(r.get("success")) for r in runs)+ deterministic = runs[0].get("state_sha") == runs[1].get("state_sha")+ ok = all_success and deterministic+ r = runs[0]+ num = lambda k: float(r.get(k) if r.get(k) is not None else -1) # noqa: E731+ out = {"success": int(ok), "replay_success": int(all_success), "deterministic": int(deterministic),+ "n_actions": int(len(acts)), "horizon": horizon, "fell": int(r.get("fell_at") is not None),+ "fell_at_step": num("fell_at"), "worst_lin_err": num("worst_lin_err"), "worst_yaw_err": num("worst_yaw_err"),+ "end_tilt_deg": num("tilt_deg"), "end_imu_height": num("imu_height"), "end_pose_angle_deg": num("pose_angle_deg"),+ "grader_error": 0,+ "video_rendered": 0, **cost}+ write(ok, out) # the verdict, before any video+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ try: # the video, for humans: it never changes the verdict+ if replay(a.instance, a.traj, os.path.join(LOG_DIR, "replay.mp4")).get("video"):+ write(ok, {**out, "video_rendered": 1})+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/mujoco_playground_go1_handstand-privileged/tests/instance.json b/tasks/mujoco_playground_go1_handstand-privileged/tests/instance.jsonnew file mode 100644index 0000000000..253a2a549f--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-privileged/tests/instance.json@@ -0,0 +1,67 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1Handstand",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ -0.3957096338272095,+ -0.1560124158859253,+ 0.27799999713897705,+ 0.2572470009326935,+ 0.0,+ 0.0,+ -0.9663457870483398,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842+ ],+ "qvel0": [+ -0.4893399477005005,+ 0.021045565605163574,+ 0.45396435260772705,+ -0.16251015663146973,+ -0.030068635940551758,+ -0.1645064353942871,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "text": "Make the Unitree Go1 do a handstand: balance on its front legs, nose down, hind legs in the air, for 2 s.",+ "facts": {+ "start_xy_m": [+ -0.396,+ -0.156+ ],+ "start_yaw_deg": -150.2,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.272,+ "reference_rows": 115,+ "reference_imu_height": 0.5314,+ "reference_pose_angle_deg": 13.82+ },+ "state_sha": "edd665f20ded",+ "horizon": 500,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_go1_handstand-privileged/tests/rcb_quadruped.py b/tasks/mujoco_playground_go1_handstand-privileged/tests/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-privileged/tests/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_go1_handstand-privileged/tests/test.sh b/tasks/mujoco_playground_go1_handstand-privileged/tests/test.shnew file mode 100755index 0000000000..1c3d2f767b--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-privileged/tests/test.sh@@ -0,0 +1,9 @@+#!/bin/bash+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in two fresh processes (the+# verdict), then a third that renders replay.mp4.+# Writes /logs/verifier/reward.txt (1/0) and reward.json (numeric fields, docs/PROTOCOL.md §2.6).+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/*+mkdir -p /logs/verifier+python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz 2> /logs/verifier/grade.logdiff --git a/tasks/mujoco_playground_go1_handstand-standard/README.md b/tasks/mujoco_playground_go1_handstand-standard/README.mdnew file mode 100644index 0000000000..cfe84aa05b--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/README.md@@ -0,0 +1,44 @@+# mujoco_playground_go1_handstand-standard++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | standard (`eai-standard/2.2`) |+| Twin | `mujoco_playground_go1_handstand-privileged` |+| Simulator / robot | `mujoco` / `unitree-go1` |+| Family / instance | `mujoco_playground/Go1Handstand` / seed 0 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `Go1Handstand` (Unitree Go1) on the same frozen instance as `mujoco_playground_go1_handstand-privileged`: Make the Unitree Go1 do a handstand: balance on its front legs, nose down, hind legs in the air, for 2 s.+From standing, it has 10 s to get into a handstand on its front legs and hold it for 2 s (Playground's handstand reward aims at the IMU 0.55 m high). Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with only+the robot's own sensors and four cameras that follow it.++## Difficulty+Same instance and success check as `mujoco_playground_go1_handstand-privileged`. In standard mode the agent loses resets, the simulator and+the world state: it sees camera images and proprioception (joints, IMU, foot contacts), acts in joint position chunks,+and gets one episode, so it has to close the loop on the robot's own sensors and recover from its own mistakes without+starting over.++## Reference solution+`solution/oracle_replay.py` streams the privileged reference's rows (`solution/oracle.npy`, 115 rows, float32-exact)+through the client in `hold` chunks; it uses no privileged information at run time. The service's recorded trajectory+is then exactly the privileged reference, and the episode ends with success after 115 control steps.++## Verification+The sim service judges the episode live and records every executed control step; the collect hook+(`environment/sim/finalize.sh`) ends the service, replays the recorded trajectory in two fresh processes and writes+`final.json`; `tests/grade.py` (separate sandbox, no network) passes iff the live check succeeded, both replays succeed,+and they end in the same state. Oracle: success after 115 control steps.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `locomotion/go1/xmls/scene_mjx_flat_terrain.xml`; MuJoCo Menagerie @ 1b86ece (`unitree_go1`); MuJoCo 3.3.7 on the CPU |+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); cameras `track`, `side`, `back`, `top` (they follow the robot) (320 x 240), the feet's kinematics in the trunk frame |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py`, as its privileged twin.diff --git a/tasks/mujoco_playground_go1_handstand-standard/environment/Dockerfile b/tasks/mujoco_playground_go1_handstand-standard/environment/Dockerfilenew file mode 100644index 0000000000..ed5eee3703--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/environment/Dockerfile@@ -0,0 +1,9 @@+# Standard mode: the agent container has NO simulator and no Playground code, only Python and the client, on the shared+# pinned client base with the shared pins (scripts/eai_standard/client.env, client-requirements.txt).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY client-requirements.txt /tmp/client-requirements.txt+RUN pip install --no-cache-dir -r /tmp/client-requirements.txt+COPY rcb_client.py rcb1.py /opt/tools/+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_go1_handstand-standard/environment/client-requirements.txt b/tasks/mujoco_playground_go1_handstand-standard/environment/client-requirements.txtnew file mode 100644index 0000000000..8aa73a968f--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/environment/client-requirements.txt@@ -0,0 +1,11 @@+# Exact pins for what the standard agent container installs (and a verifier, if it installs anything): the closure of+# `pip install requests numpy pillow scipy`, the unpinned line of every standard task at 9eb18edf, resolved on+# 2026-10-01 in CLIENT_IMAGE (client.env: Python 3.12.14, pip 25.0.1). A change here is a shared-files PR.+certifi==2026.7.22+charset-normalizer==3.5.2+idna==3.20+numpy==2.5.3+pillow==12.3.0+requests==2.34.2+scipy==1.18.1+urllib3==2.8.0diff --git a/tasks/mujoco_playground_go1_handstand-standard/environment/docker-compose.yaml b/tasks/mujoco_playground_go1_handstand-standard/environment/docker-compose.yamlnew file mode 100644index 0000000000..8ec63c582e--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/environment/docker-compose.yaml@@ -0,0 +1,23 @@+# Standard mode: the simulator runs in the `sim` sidecar (the agent cannot open it); the agent only reaches port 8000.+# No `expose`/`ports` on sim: under Harbor's egress control it shares main's network namespace (localhost:8000).+# CPU only: MuJoCo physics and rendering (EGL when a GPU is there, else OSMesa); no GPU reservation.+# Crash recovery (docs/STANDARD_MODE_2_2.md §13): run.sh exits non-zero when the service crashes, compose restarts the+# container (same container, same /data) and the service replays its journal into the same episode, never a reset.+services:+ main:+ depends_on: [sim]+ sim:+ image: ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+ volumes:+ - ./sim:/srv:ro+ working_dir: /tmp+ command: sh /srv/run.sh+ restart: on-failure:6 # N >= 3 (PROTOCOL §4.1); a resume continues the episode+ environment:+ RCB_INSTANCE: /srv/instance.json+ RCB_TOOL: /srv/rcb_quadruped.py+ RCB_DATA: /data+ RCB_WALL_CLOCK_S: "3600"+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in about a second+ PYTHONPATH: /srv+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction logdiff --git a/tasks/mujoco_playground_go1_handstand-standard/environment/rcb1.py b/tasks/mujoco_playground_go1_handstand-standard/environment/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/environment/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_go1_handstand-standard/environment/rcb_client.py b/tasks/mujoco_playground_go1_handstand-standard/environment/rcb_client.pynew file mode 100644index 0000000000..aa25b0e050--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/environment/rcb_client.py@@ -0,0 +1,211 @@+"""eai-standard/2.2 client (formerly rcb-limited/2.x) — the only thing a standard-mode agent gets (installed at+/opt/tools/rcb_client.py).++ from rcb_client import Robot+ r = Robot() # finds the service (sim:8000, then localhost:8000), waits for warm-up+ spec = r.spec() # actions, cameras (+ intrinsics, mounting), robot_spec, world, budget, kinematics+ obs = r.get_obs() # current frames: obs.last[cam] -> uint8 (H,W,3); obs.meta["proprio"]+ obs = r.get_obs(depth=True) # + obs.last_depth[cam] -> float32 (H,W) z-depth in metres, 0 = no reading+ res = r.submit("joint_position", A, dt=0.1) # A: (T, dim) rows dt apart; returns the execution video+ res = r.submit("ee_pose", P) # (T, dim) end-effector targets (see spec()["action_types"])+ res.video[cam] -> mp4 bytes res.frames[cam] -> uint8 (N,H,W,3) if video="frames"/"both" res.last[cam]+ res.proprio -> float32 (N, D), one row per frame (names: spec()["proprio_layout"]; res.group("tcp_pose"))+ res.frame_step -> int64 (N,) control step of each frame res.frame_time_s -> float64 (N,) simulated time+ res.extrinsic_cv[cam] -> float64 (N,3,4) world->camera per frame (res.meta["cameras"]: intrinsics + the last frame's pose)+ res = r.submit(..., depth="frames") # + res.depth[cam] -> float32 (N,H,W) metres, one per frame (1 mm steps)+ r.fk(q) # {"ok", "poses": {frame: [x,y,z, quaternion]}}: forward kinematics, no physics+ r.ik({frame: pose}, seed=q) # {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}: inverse kinematics+ res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, frames/<cam>/NNN.jpg, proprio.npy, depth, frame_meta.npz+ obs = r.get_obs(seconds=3, video="both") # hold the last command, let physics run 3 s, return the video+ r.status() # calls, control steps, done, reason, elapsed time++Nothing is put into your context automatically: what you look at, and where you store it, is your code's decision.++If a call fails with a connection error or a 5xx, the service may have crashed; it restarts and resumes the SAME episode+(never a reset) in the state after the last call it completed, which you may not have received. r.wait_ready() waits+until it answers again (resuming replays the episode so far: long episodes can take minutes); then check r.status()+before you continue (spec()["on_service_error"]).+"""+from __future__ import annotations+import json, os, pathlib, sys, time, zlib+import numpy as np+import requests+import rcb1++PROTOCOL = "eai-standard/2.2" # also talks to 2.0 / 2.1 services (they ignore depth and send no frame metadata)+ACCEPTED = ("eai-standard/2.", "rcb-limited/2.") # every 2.x service, under the protocol's current and former name+++class EpisodeOver(RuntimeError):+ pass+++def _decode_depth_frames(p: dict) -> np.ndarray:+ a = np.frombuffer(zlib.decompress(p["data"]), dtype="<u2").reshape(p["shape"])+ return a.astype(np.float32) / 1000.0+++class Result:+ """Decoded RCB1 response: meta (dict), video (cam -> mp4 bytes), frames (cam -> uint8 (N,H,W,3)), last (cam -> uint8+ (H,W,3)), last_depth (cam -> float32 (H,W) m), depth (cam -> float32 (N,H,W) m, one per frame), proprio (float32 (N,D)),+ frame_step (int64 (N,)), frame_time_s (float64 (N,)), extrinsic_cv (cam -> float64 (N,3,4)). save(dir) writes it out;+ show(cam, k) returns one frame; group(name) the proprio columns of one spec()["proprio_groups"] group. stopped: None,+ or why the service stopped the call early ("max_call_wall_s": it ran longer than spec()["max_call_wall_s"]); then+ meta["executed_rows"] < the rows sent, and meta["proprio"]["now"] is where the robot is."""+ def __init__(self, meta: dict, parts: dict, spec: dict | None = None):+ self.meta = meta; self.raw = parts; self._spec = spec or {}; self.stopped = meta.get("stopped")+ self.video, self.frames, self.last, self.last_depth, self.depth, self.extrinsic_cv = {}, {}, {}, {}, {}, {}+ self.proprio = None; self.frame_step = None; self.frame_time_s = None+ for name, p in parts.items():+ kind, data = p["kind"], p["data"]+ if name.startswith("video/") and kind == "mp4": self.video[name[6:]] = data+ elif name.startswith("frames/") and kind == "array": self.frames[name[7:]] = data+ elif name.startswith("last/") and kind == "array": self.last[name[5:]] = data+ elif name.startswith("last_depth/") and kind == "array": self.last_depth[name[11:]] = np.asarray(data, dtype=np.float32)+ elif name.startswith("depth_frames/") and p.get("codec") == "zlib": self.depth[name[13:]] = _decode_depth_frames(p)+ elif name.startswith("depth/") and kind == "array": self.depth[name[6:]] = np.asarray(data, dtype=np.float32) # 2.1 form+ elif name.startswith("extrinsic_cv/") and kind == "array": self.extrinsic_cv[name[13:]] = data+ elif name == "proprio": self.proprio = data+ elif name == "frame_step": self.frame_step = data+ elif name == "frame_time_s": self.frame_time_s = data++ @property+ def done(self) -> bool: return bool(self.meta.get("done"))++ def show(self, camera: str, k: int = -1) -> np.ndarray:+ if camera in self.frames: return self.frames[camera][k]+ return self.last[camera]++ def group(self, name: str, now: bool = False) -> np.ndarray:+ """Columns of proprio group `name` (spec()["proprio_groups"]): (N, n) over the frames, or (n,) of meta["proprio"]["now"]."""+ first, n = self._spec["proprio_groups"][name][:2]+ if now: return np.asarray(self.meta["proprio"]["now"], dtype=np.float64)[first:first + n]+ return self.proprio[:, first:first + n]++ def save(self, out_dir: str) -> str:+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ (out / "meta.json").write_text(json.dumps(self.meta, indent=1))+ for cam, b in self.video.items(): (out / f"{cam}.mp4").write_bytes(b)+ try:+ from PIL import Image+ for cam, img in self.last.items():+ (out / "last").mkdir(exist_ok=True); Image.fromarray(np.ascontiguousarray(img)).save(out / "last" / f"{cam}.jpg", quality=90)+ for cam, arr in self.frames.items():+ d = out / "frames" / cam; d.mkdir(parents=True, exist_ok=True)+ for i, f in enumerate(arr): Image.fromarray(np.ascontiguousarray(f)).save(d / f"{i:03d}.jpg", quality=85)+ except ImportError:+ for cam, img in self.last.items(): np.save(out / f"last_{cam}.npy", img)+ for cam, arr in self.frames.items(): np.save(out / f"frames_{cam}.npy", arr)+ for cam, arr in self.last_depth.items(): np.save(out / f"last_depth_{cam}.npy", arr)+ for cam, arr in self.depth.items(): np.savez_compressed(out / f"depth_{cam}.npz", depth_mm=np.rint(arr * 1000).astype(np.uint16))+ if self.proprio is not None: np.save(out / "proprio.npy", self.proprio)+ if self.frame_step is not None:+ np.savez(out / "frame_meta.npz", frame_step=self.frame_step, frame_time_s=self.frame_time_s,+ **{f"extrinsic_cv/{c}": e for c, e in self.extrinsic_cv.items()})+ return str(out)+++class Robot:+ def __init__(self, base: str | None = None, timeout: float = 600.0):+ cands = [base or os.environ.get("SIM_URL"), "http://sim:8000", "http://localhost:8000"]+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ for b in [c for c in cands if c]:+ try:+ r = requests.get(b + "/spec", timeout=(5, 30))+ if r.status_code == 503: last = "warming up"; break+ r.raise_for_status(); self.base = b; self._spec = r.json()+ if not str(self._spec.get("protocol", "")).startswith(ACCEPTED):+ raise RuntimeError(f"not a 2.x service: protocol {self._spec.get('protocol')!r}")+ return+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(2)+ raise RuntimeError(f"sim service unavailable: {last}")++ def spec(self) -> dict:+ return self._spec++ def _post(self, path: str, meta: dict, parts: list, timeout: float) -> Result:+ body = rcb1.encode(meta, parts)+ r = requests.post(self.base + path, data=body, headers={"Content-Type": "application/x-rcb1"}, timeout=(5, timeout))+ if r.status_code == 409:+ raise EpisodeOver(r.json().get("reason") if r.headers.get("Content-Type", "").startswith("application/json") else "episode finished")+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ m, p = rcb1.decode(r.content); return Result(m, p, self._spec)++ def _common(self, cameras, video_fps, depth, include_depth) -> dict:+ cams = list(cameras) if cameras is not None else self._spec.get("default_cameras")+ if depth is None or depth is False: depth = "frames" if include_depth else "none"+ elif depth is True: depth = "last"+ m = {"cameras": cams, "video_fps": None if video_fps is None else int(video_fps), "depth": depth}+ return {k: v for k, v in m.items() if v is not None}++ def submit(self, action_type: str, actions, dt: float | None = None, interpolate: str = "linear", cameras=None,+ video_fps: int | None = None, video: str = "mp4", depth=None, include_depth: bool = False, note: str = "") -> Result:+ """Execute a chunk of low-level actions (T, dim); see spec()['action_types'] for dims, layouts, limits and semantics.+ dt defaults to one control period, cameras to spec()['default_cameras']; depth: None | True (= "last") | "frames"."""+ a = np.asarray(actions, dtype=np.float32)+ if a.ndim == 1: a = a[None, :]+ if dt is None and self._spec.get("control_hz"): dt = 1.0 / float(self._spec["control_hz"])+ meta = {"type": action_type, "interpolate": interpolate, "video": video, "note": note,+ **({} if dt is None else {"dt": float(dt)}), **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/submit", meta, [rcb1.array_part("actions", a)], timeout=1800)+ if res.stopped:+ print(f"[rcb_client] the service stopped this call early ({res.stopped}): {res.meta.get('executed_rows')} of {len(a)} rows "+ "executed; meta['proprio']['now'] is where the robot is", file=sys.stderr)+ return res++ def get_obs(self, cameras=None, seconds: float = 0.0, video_fps: int | None = None, depth=None, include_depth: bool = False,+ video: str = "frames") -> Result:+ """Current frames (seconds=0, free) or hold the last command and watch for `seconds` (returns the video).+ depth: None | True (= "last": the last frame's depth) | "frames" (one depth map per frame)."""+ meta = {"seconds": float(seconds), "video": video, **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/observe", meta, [], timeout=600)+ if res.stopped:+ print(f"[rcb_client] the service stopped this watch early ({res.stopped}) after {res.meta.get('control_steps_watch')} control "+ "steps", file=sys.stderr)+ return res++ def status(self) -> dict:+ r = requests.get(self.base + "/status", timeout=(5, 60)); r.raise_for_status(); return r.json()++ def wait_ready(self, timeout: float = 3600.0) -> dict:+ """After a connection error: wait until the service answers GET /status again (it resumes the same episode after a+ crash), then return the status. Raises RuntimeError after `timeout` seconds."""+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ try:+ return self.status()+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(5)+ raise RuntimeError(f"sim service did not come back within {timeout:.0f} s: {last}")++ def kinematics(self, body: dict) -> dict:+ """POST /kinematics (stateless: never moves the robot, never advances time). Raises ValueError on a bad request."""+ r = requests.post(self.base + "/kinematics", json=body, timeout=(5, 120))+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ return r.json()++ def fk(self, q, links=None, base_pose=None) -> dict:+ """Forward kinematics: q in spec()['kinematics']['joint_names'] order -> {"ok", "frame", "poses": {link: [x,y,z, quat]}}+ (quaternion order spec()['world']['quaternion_order']; a mobile robot answers in its base frame unless base_pose is given)."""+ body = {"op": "fk", "q": [float(v) for v in np.asarray(q).reshape(-1)]}+ if links is not None: body["links"] = list(links)+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)++ def ik(self, targets: dict, seed=None, base_pose=None, **opts) -> dict:+ """Inverse kinematics: {frame: [x,y,z, quat]} (frames from spec()['kinematics']['ik_targets']) and an optional seed q ->+ {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}. opts: tol_pos_m, tol_rot_rad, max_iters."""+ body = {"op": "ik", "targets": {k: [float(v) for v in p] for k, p in targets.items()}, **opts}+ if seed is not None: body["seed"] = [float(v) for v in np.asarray(seed).reshape(-1)]+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)diff --git a/tasks/mujoco_playground_go1_handstand-standard/environment/sim/finalize.sh b/tasks/mujoco_playground_go1_handstand-standard/environment/sim/finalize.shnew file mode 100755index 0000000000..02048ddc74--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/environment/sim/finalize.sh@@ -0,0 +1,80 @@+#!/bin/sh+# [[verifier.collect]] hook, run inside the `sim` sidecar once Harbor has stopped the agent's container.+# 1. `rcb_limited.py end` (docs/STANDARD_MODE_2_2.md §13.3): SIGUSR1 to the service, which ends the episode if the+# agent had not (reason "timeout"), writes trajectory.npz + episode.json (live verdict, final-state hash) and exits.+# It exits 2 when final.json already holds the verdict (the service gave up after crashes): that verdict stays.+# 2. replay the trajectory from the frozen instance in TWO fresh processes (`rcb_quadruped.py replay`, the privileged+# verifier's replay): determinism = fresh process == fresh process; live_matches_replay = live == replay.+# 3. merge everything into final.json, the only thing the verifier sandbox grades;+# 4. a third replay renders replay.mp4, after the verdict is on disk (it never changes it).+set -u+DATA="${RCB_DATA:-/data}"; TOOL="${RCB_TOOL:?}"; INSTANCE="${RCB_INSTANCE:?}"+python /srv/rcb_limited.py end "$DATA" --timeout "${RCB_COLLECT_END_TIMEOUT_S:-900}"; rc=$?+if [ "$rc" = 2 ]; then+ echo "[finalize] final.json already holds the verdict; no replay"; exit 0+fi+if [ "$rc" != 0 ]; then+ echo "[finalize] the service did not end and dump the episode in time (rc $rc): an infrastructure failure"+ python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data"); p = os.path.join(d, "final.json")+try:+ out = json.load(open(p))+except Exception:+ out = {}+out.update({"finalized": True, "success": False, "replay_success": False, "deterministic": False, "infra_error": 1,+ "error": "collect hook: the sim service did not end and dump the episode in time"})+json.dump(out, open(p, "w"))+print(json.dumps(out))+PY+ exit 0+fi+replay() { # <n> [--video FILE]: one replay in a fresh process, its result in $DATA/replay<n>.json+ n=$1; shift+ RCB_SESSION_LOG= python "$TOOL" replay --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --out "$DATA/replay$n.json" \+ "$@" > /dev/null 2> "$DATA/replay$n.log"+ echo "[finalize] replay $n exit $?"+}+echo "[finalize] episode dumped; replaying twice in fresh processes"+rm -f "$DATA/replay1.json" "$DATA/replay2.json" "$DATA/replay3.json"+replay 1+replay 2+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+def result(name):+ try:+ v = json.load(open(os.path.join(d, name)))+ except (OSError, ValueError):+ return {}+ return v if isinstance(v, dict) else {}+out = {"replay_success": False, "deterministic": False, "video": False}+try:+ out.update(json.load(open(os.path.join(d, "episode.json"))))+except Exception as exc:+ out["error"] = f"no episode.json: {exc!r}"+a, b = result("replay1.json"), result("replay2.json")+out["replay_success"] = bool(a.get("success")) and bool(b.get("success"))+out["replay_sha"], out["replay_sha2"] = a.get("state_sha"), b.get("state_sha")+out["deterministic"] = bool(a.get("state_sha")) and a.get("state_sha") == b.get("state_sha")+out["live_matches_replay"] = bool(a.get("state_sha")) and a.get("state_sha") == out.get("live_sha")+if not (a.get("state_sha") and b.get("state_sha")): # a replay process died (it crashed or timed out): not the agent's 0+ out.update({"replay_failed": 1, "infra_error": 1,+ "error": "a replay process gave no result (replay1.log / replay2.log)"})+elif not (a.get("instance_ok") and b.get("instance_ok")): # the image no longer builds the frozen start: not the agent's 0+ out.update({"instance_mismatch": 1, "infra_error": 1, "error": "a replay did not start in the instance's t = 0 state"})+out["finalized"] = True+json.dump(out, open(os.path.join(d, "final.json"), "w"))+print(json.dumps(out))+PY+replay 3 --video "$DATA/replay.mp4"+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+try:+ shown = json.load(open(os.path.join(d, "replay3.json"))).get("video")+except (OSError, ValueError):+ shown = False+if shown:+ p = os.path.join(d, "final.json"); out = json.load(open(p)); out["video"] = True; json.dump(out, open(p, "w"))+PYdiff --git a/tasks/mujoco_playground_go1_handstand-standard/environment/sim/instance.json b/tasks/mujoco_playground_go1_handstand-standard/environment/sim/instance.jsonnew file mode 100644index 0000000000..253a2a549f--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/environment/sim/instance.json@@ -0,0 +1,67 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1Handstand",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ -0.3957096338272095,+ -0.1560124158859253,+ 0.27799999713897705,+ 0.2572470009326935,+ 0.0,+ 0.0,+ -0.9663457870483398,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842+ ],+ "qvel0": [+ -0.4893399477005005,+ 0.021045565605163574,+ 0.45396435260772705,+ -0.16251015663146973,+ -0.030068635940551758,+ -0.1645064353942871,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "text": "Make the Unitree Go1 do a handstand: balance on its front legs, nose down, hind legs in the air, for 2 s.",+ "facts": {+ "start_xy_m": [+ -0.396,+ -0.156+ ],+ "start_yaw_deg": -150.2,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.272,+ "reference_rows": 115,+ "reference_imu_height": 0.5314,+ "reference_pose_angle_deg": 13.82+ },+ "state_sha": "edd665f20ded",+ "horizon": 500,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_go1_handstand-standard/environment/sim/rcb1.py b/tasks/mujoco_playground_go1_handstand-standard/environment/sim/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/environment/sim/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_go1_handstand-standard/environment/sim/rcb_limited.py b/tasks/mujoco_playground_go1_handstand-standard/environment/sim/rcb_limited.pynew file mode 100644index 0000000000..1ce1171787--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/environment/sim/rcb_limited.py@@ -0,0 +1,930 @@+"""eai-standard/2.2 (formerly rcb-limited/2.2): the HTTP layer, the protocol helpers and the crash recovery that every+2.2 sim service shares (docs/STANDARD_MODE_2_2.md; the 2.1 base is docs/LIMITED_MODE_PROTOCOL.md).++The source is scripts/eai_standard/rcb_limited.py; the generators copy it unchanged into every standard task's+environment/sim/ (ci_checks/check-tooling-identity.sh). A service keeps its simulator to itself (scene, action+execution, cameras, kinematic model) and hands this module plain callables:++ import rcb_limited as L+ EP = L.Episode(DATA, dim=N, resume="exact") # before the scene is built; "approx" for a nondeterministic simulator+ EP.startup() # start count, back-off after failed starts, startup watchdog+ S = <build the scene>; EP.scene_built() # the watchdog stands down+ def ctrl_step(a, rec): # every executed control step+ S.step(a); stop = EP.journal(a); rec.tick(); return E["done"] or stop+ rec = L.Recorder(cams, every, grab, proprio_row, extrinsics, clock, depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+ rec.tick(force=True) # first frame (before the chunk / watch)+ ...; rec.tick(); ... # after every control step: a frame every `every` steps+ rec.tick(force=True, last=True) # last frame (+ its depth)+ parts = rec.parts(video, fps) # RCB1 parts: video/ frames/ last/ extrinsic_cv/ last_depth/ depth_frames/ depth/ proprio frame_*+ S.record_start()+ EP.begin(state=E, step=S.step, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, start_event={...}, on_end=end_fn)+ L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics,+ status=status, on_submit_error=lambda exc: finish("error"), log=EP.log,+ episode=EP, state_sha=S.state_sha, proprio=proprio_row))++ grab(cams, want_depth) -> ({cam: uint8 (H,W,3)}, {cam: float32 (H,W) z-depth in metres, 0 = no reading})+ extrinsics(cams) -> {cam: (3,4) world -> camera, OpenCV axes (x right, y down, z forward)}+ proprio_row() -> float32 (len(spec["proprio_layout"]),)+ clock() -> int, control steps since the episode start (the frame's step index)+ do_kinematics(req) -> dict; `req` is parse_kinematics(body, spec["kinematics"]); it must never step physics++None of the callables may step physics. check_spec(SPEC) runs in serve(): a service whose /spec misses a 2.2 field, or+carries a field the protocol forbids (segmentation, object identities or sizes, physical parameters), does not start.+Crash recovery (class Episode; PROTOCOL §4.7): every executed control step is journaled, every completed call+checkpointed (rows, state hash, the robot's proprio row); after a crash compose restarts the container and the service+replays the journal and continues the SAME episode, never a reset. `python rcb_limited.py end <data dir>` is the shared+first half of a collect hook."""+from __future__ import annotations+import faulthandler, json, math, os, re, select, signal, socket, sys, tempfile, threading, time, traceback, zlib+from http.server import BaseHTTPRequestHandler, HTTPServer+from typing import Any, Callable++import numpy as np++import rcb1++PROTOCOL = "eai-standard/2.2"+COMPAT = ["rcb-limited/2.0", "rcb-limited/2.1", "eai-standard/2.1"] # requests written for these are served unchanged+MAX_BODY = 64 * 1024 * 1024+MAX_RESP = 256 * 1024 * 1024+DEPTH_MODES = ("none", "last", "frames")+DEPTH_MAX_M = 65.535 # uint16 millimetres; a farther surface reads 0 (no reading)+DEPTH_NOISE = os.environ.get("RCB_DEPTH_NOISE", "off").strip().lower() # off | realsense (as rcb-limited/2.1)+_RNG = np.random.default_rng(int(os.environ.get("RCB_DEPTH_NOISE_SEED", "0")))+PROPRIO_GROUPS_REQUIRED = ("joint_pos", "joint_vel", "gripper_opening", "tcp_pose", "joint_effort")+PART_PREFIXES = ("video/", "frames/", "last/", "last_depth/", "depth_frames/", "depth/", "extrinsic_cv/")+PART_NAMES = ("proprio", "frame_step", "frame_time_s")+++# ---------------------------------------------------------------- depth+def depth_mode(meta: dict) -> str:+ """The request's depth mode: "none" | "last" | "frames" (2.2 field `depth`), or "legacy" for a 2.0/2.1 request that+ sets `include_depth: true` and no `depth` (answered as 2.1 did: `depth/<cam>` float16 (N,H,W) metres)."""+ d = meta.get("depth")+ if d is None or d is False:+ return "legacy" if meta.get("include_depth") is True else "none"+ if d is True:+ return "last"+ if isinstance(d, str) and d in DEPTH_MODES:+ return d+ raise ValueError(f"depth must be one of {'|'.join(DEPTH_MODES)} (got {d!r})")+++def clean_depth(z) -> np.ndarray:+ """float32 z-depth in metres: non-finite, negative and beyond-range pixels read 0 (no reading); the optional+ RCB_DEPTH_NOISE=realsense model (sigma = 2 mm + 2.5 mm * z^2, 1 % dropouts) is applied here, after rendering, so it+ never touches physics."""+ z = np.asarray(z, dtype=np.float32).copy()+ if z.ndim == 3 and z.shape[-1] == 1:+ z = z[..., 0]+ bad = ~np.isfinite(z) | (z <= 0) | (z > DEPTH_MAX_M)+ z[bad] = 0.0+ if DEPTH_NOISE == "realsense":+ valid = z > 0+ z = z + _RNG.normal(0.0, 1.0, z.shape).astype(np.float32) * (0.002 + 0.0025 * z * z)+ z[_RNG.random(z.shape) < 0.01] = 0.0+ z[~valid] = 0.0+ z[(z < 0) | (z > DEPTH_MAX_M)] = 0.0+ return z.astype(np.float32)+++def depth_frames_part(name: str, stack: np.ndarray) -> tuple[str, str, bytes, dict]:+ """(N,H,W) metres -> an RCB1 "bytes" part: zlib of C-order uint16 millimetres (0 = no reading). Clients that do not+ know it keep the raw bytes and ignore it; rcb_client decodes it back to float32 metres."""+ mm = np.rint(np.asarray(stack, dtype=np.float64) * 1000.0)+ mm[(mm < 0) | (mm > 65535)] = 0+ a = np.ascontiguousarray(mm.astype("<u2"))+ return (name, "bytes", zlib.compress(a.tobytes(), 1), {"codec": "zlib", "dtype": "uint16", "shape": list(a.shape), "unit": "mm"})+++def encode_mp4(frames: np.ndarray, fps: int) -> bytes:+ """H.264 mp4 (yuv420p, faststart) of uint8 (N,H,W,3) frames: the same encoding every 2.0 service used."""+ import imageio.v2 as imageio+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tf:+ path = tf.name+ try:+ with imageio.get_writer(path, format="FFMPEG", mode="I", fps=fps, codec="libx264", macro_block_size=1,+ output_params=["-movflags", "+faststart", "-pix_fmt", "yuv420p"]) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ return open(path, "rb").read()+ finally:+ try:+ os.unlink(path)+ except OSError:+ pass+++# ---------------------------------------------------------------- recording what the cameras see during one call+class Recorder:+ """Frames of the requested cameras every `every` clock ticks, plus forced first/last frames; for every frame the+ proprio row, the clock (step index), each camera's extrinsics and, if asked, its depth. All arrays share one frame+ axis N: frames/<cam>, the mp4's frames, proprio, frame_step, frame_time_s, extrinsic_cv/<cam>, depth_frames/<cam>."""++ def __init__(self, cameras, every: int, grab: Callable, proprio_row: Callable, extrinsics: Callable, clock: Callable,+ depth: str = "none", clock_hz: float = 1.0):+ if depth not in DEPTH_MODES + ("legacy",):+ raise ValueError(f"bad depth mode {depth!r}")+ self.cams = list(cameras); self.every = max(1, int(every)); self.mode = depth; self.hz = float(clock_hz)+ self._grab, self._prop, self._ext, self._clock = grab, proprio_row, extrinsics, clock+ self.frames: dict = {c: [] for c in self.cams}; self.depth: dict = {c: [] for c in self.cams}+ self.ext: dict = {c: [] for c in self.cams}; self.last_depth: dict = {}+ self.prop: list = []; self.steps: list = []; self.n = 0; self.missing = 0++ def tick(self, force: bool = False, last: bool = False) -> None:+ if force or last or self.n % self.every == 0:+ self._capture(last)+ self.n += 1++ def _capture(self, last: bool) -> None:+ want = self.mode in ("frames", "legacy") or (last and self.mode == "last")+ rgb, dep = self._grab(self.cams, want)+ ext = self._ext(self.cams)+ for c in self.cams:+ img = rgb.get(c)+ if img is not None:+ img = np.ascontiguousarray(np.asarray(img)[..., :3].astype(np.uint8))+ else: # a camera that failed to render: a black frame (sized in parts()) keeps one frame axis+ self.missing += 1+ self.frames[c].append(img)+ e = ext.get(c)+ self.ext[c].append(np.full((3, 4), np.nan) if e is None else np.asarray(e, dtype=np.float64).reshape(3, 4))+ if want:+ d = dep.get(c)+ if d is None:+ d = np.zeros(img.shape[:2] if img is not None else (1, 1), np.float32)+ else:+ d = clean_depth(d)+ if img is not None and d.shape != img.shape[:2]:+ raise RuntimeError(f"depth of {c} is {d.shape}, its RGB {img.shape[:2]}: they must be pixel-aligned")+ if self.mode in ("frames", "legacy"):+ self.depth[c].append(d)+ if last or self.mode == "frames":+ self.last_depth[c] = d+ self.prop.append(np.asarray(self._prop(), dtype=np.float32).reshape(-1))+ self.steps.append(int(self._clock()))++ def parts(self, video: str, fps: int) -> list:+ if self.mode == "last" and not self.last_depth and self.prop: # no last=True tick: the state has not moved since+ _, dep = self._grab(self.cams, True)+ self.last_depth = {c: clean_depth(dep[c]) for c in self.cams if c in dep}+ out = []+ for c in self.cams:+ good = [f for f in self.frames[c] if f is not None]+ hw = good[-1].shape[:2] if good else (1, 1)+ if len(good) < len(self.frames[c]):+ self.frames[c] = [f if f is not None else np.zeros(hw + (3,), np.uint8) for f in self.frames[c]]+ self.depth[c] = [d if d.shape == hw else np.zeros(hw, np.float32) for d in self.depth[c]]+ if c in self.last_depth and self.last_depth[c].shape != hw:+ self.last_depth[c] = np.zeros(hw, np.float32)+ fr = np.stack(self.frames[c]) if self.frames[c] else np.zeros((0, 1, 1, 3), np.uint8)+ if video in ("mp4", "both") and len(fr):+ out.append((f"video/{c}", "mp4", encode_mp4(fr, fps), {"fps": fps, "n": int(len(fr))}))+ if video in ("frames", "both"):+ out.append(rcb1.array_part(f"frames/{c}", fr))+ if len(fr):+ out.append(rcb1.array_part(f"last/{c}", fr[-1]))+ out.append(rcb1.array_part(f"extrinsic_cv/{c}", np.stack(self.ext[c]) if self.ext[c] else np.zeros((0, 3, 4))))+ if self.mode in ("last", "frames") and c in self.last_depth:+ out.append(rcb1.array_part(f"last_depth/{c}", self.last_depth[c]))+ if self.mode == "frames" and self.depth[c]:+ out.append(depth_frames_part(f"depth_frames/{c}", np.stack(self.depth[c])))+ if self.mode == "legacy" and self.depth[c]:+ out.append(rcb1.array_part(f"depth/{c}", np.stack(self.depth[c]).astype(np.float16)))+ out.append(rcb1.array_part("proprio", np.stack(self.prop) if self.prop else np.zeros((0, 0), np.float32)))+ st = np.asarray(self.steps, dtype=np.int64)+ out.append(rcb1.array_part("frame_step", st))+ out.append(rcb1.array_part("frame_time_s", st.astype(np.float64) / self.hz))+ return out+++def encode_response(meta: dict, parts: list, max_bytes: int = MAX_RESP) -> bytes:+ """The RCB1 body; over `max_bytes` the per-frame depth goes first, then the raw frames (mp4, last frames, last+ depth, proprio and the per-frame arrays always stay), and meta["degraded"] says what was dropped."""+ body = rcb1.encode(meta, parts)+ dropped = []+ for prefixes in (("depth_frames/", "depth/"), ("frames/",)):+ if len(body) <= max_bytes:+ break+ keep = [p for p in parts if not p[0].startswith(prefixes)]+ if len(keep) < len(parts):+ parts = keep; dropped += [x.rstrip("/") for x in prefixes]+ body = rcb1.encode({**meta, "degraded": f"response over {max_bytes} bytes: {', '.join(dropped)} dropped"}, parts)+ return body+++# ---------------------------------------------------------------- kinematics+def _vec(x, n: int, what: str) -> list:+ a = np.asarray(x, dtype=np.float64).reshape(-1) if x is not None else None+ if a is None or a.size != n or not np.all(np.isfinite(a)):+ raise ValueError(f"{what} must be {n} finite numbers")+ return a.tolist()+++def _pose(x, what: str) -> list:+ p = _vec(x, 7, what)+ nq = math.sqrt(sum(v * v for v in p[3:]))+ if nq < 1e-6:+ raise ValueError(f"{what}: quaternion has zero norm")+ return p[:3] + [v / nq for v in p[3:]]+++def parse_kinematics(body: dict, kin: dict) -> dict:+ """Validate a /kinematics request against spec["kinematics"] (ValueError -> 400). Returns+ {"op": "fk", "q", "links", "base_pose"} or {"op": "ik", "targets": {frame: pose7}, "seed", "base_pose", "tol_pos_m",+ "tol_rot_rad", "max_iters"}; poses are x y z + a unit quaternion in the spec's order; q follows kin["joint_names"]."""+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object")+ op = body.get("op"); n = len(kin["joint_names"])+ base = None+ if body.get("base_pose") is not None:+ if kin.get("frame") != "base":+ raise ValueError("base_pose is only accepted by a mobile robot (spec kinematics.frame == 'base')")+ base = _pose(body["base_pose"], "base_pose")+ if op == "fk":+ links = body.get("links") or list(kin["links"])+ if not isinstance(links, list) or any(l not in kin["links"] for l in links):+ raise ValueError(f"links must be a list of names from spec kinematics.links: {kin['links']}")+ return {"op": "fk", "q": _vec(body.get("q"), n, "q"), "links": links, "base_pose": base}+ if op == "ik":+ tg = body.get("targets")+ if not isinstance(tg, dict) or not tg or any(k not in kin["ik_targets"] for k in tg):+ raise ValueError(f"targets must map frames from spec kinematics.ik_targets {kin['ik_targets']} to poses")+ ik = kin.get("ik", {})+ seed = None if body.get("seed") is None else _vec(body["seed"], n, "seed")+ tol_p = float(body.get("tol_pos_m", ik.get("tol_pos_m", 0.005)))+ tol_r = float(body.get("tol_rot_rad", ik.get("tol_rot_rad", 0.05)))+ it = int(body.get("max_iters", ik.get("max_iters", 200)))+ if not (1e-5 <= tol_p <= 0.5 and 1e-4 <= tol_r <= 3.2 and 1 <= it <= 5000):+ raise ValueError("tol_pos_m in [1e-5, 0.5], tol_rot_rad in [1e-4, 3.2], max_iters in [1, 5000]")+ return {"op": "ik", "targets": {k: _pose(v, f"targets[{k}]") for k, v in tg.items()}, "seed": seed, "base_pose": base,+ "tol_pos_m": tol_p, "tol_rot_rad": tol_r, "max_iters": it}+ raise ValueError("op must be 'fk' or 'ik'")+++def fk_response(poses: dict, frame: str) -> dict:+ return {"ok": True, "op": "fk", "frame": frame, "poses": {k: [float(v) for v in np.asarray(p, dtype=np.float64).reshape(7)] for k, p in poses.items()}}+++def ik_response(q, ok: bool, errors: dict, frame: str, note: str | None = None) -> dict:+ """errors: {frame: (position error m, rotation error rad)} of the returned q (None / non-finite -> null: no solution)."""+ fin = lambda v: float(v) if v is not None and math.isfinite(float(v)) else None # noqa: E731+ out = {"ok": bool(ok), "op": "ik", "frame": frame, "q": None if q is None else [float(v) for v in np.asarray(q).reshape(-1)],+ "error": {k: {"pos_m": fin(e[0]), "rot_rad": fin(e[1])} for k, e in errors.items()}}+ if note:+ out["note"] = note+ return out+++def quat_angle(q1, q2) -> float:+ """Rotation angle (rad) between two unit quaternions of the same order."""+ d = abs(float(np.dot(np.asarray(q1, dtype=np.float64), np.asarray(q2, dtype=np.float64))))+ return 2.0 * math.acos(min(1.0, d))+++# ---------------------------------------------------------------- /spec self-check+FORBIDDEN_KEY = re.compile(r"mask|segment|semantic(?!s$)|instance_?id|bbox|bounding|categor|object|\bobj_|label|mass|friction|"+ r"restitution|inertia|density|damping|stiffness", re.I)+GAIN_PATHS = ("robot_spec.controller",) # joint drive gains (stiffness, damping) are the robot's own, and allowed there+POSITION_KEY = re.compile(r"(?:^|_)(?:pos|position|positions|pose|poses|origin|location|coords?|coordinates|world|translation)(?:_|$)|"+ r"(?:^|_)cent(?:er|re)s?(?:_|$)|(?:^|_)xyz?$|(?:^|_)(?:top|surface|floor|table|plane|height|elevation)?_?z$", re.I)+WORLD_TEXT = re.compile(r"\bworld\s+[xyz]\s*=", re.I)+COORDS = re.compile(r"\(\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*(?:,\s*-?\d+(?:\.\d+)?\s*)?\)")+++def world_text(s: str) -> bool:+ """A text that gives a world coordinate: a pixel-to-world formula, or a coordinate tuple with a decimal point that is+ not the robot's own pose ("robot base at (0, 0, 1.08)" stays)."""+ return bool(WORLD_TEXT.search(s)) or any("." in m.group(0) and not re.search(r"base|robot|origin", s[max(0, m.start() - 40):m.start()], re.I)+ for m in COORDS.finditer(s))+CONVENTIONS = {"static.floor_z": 0.0} # BEHAVIOR: the floor is the plane z = 0 (the world frame's definition)+++def static_positions(obj: Any, path: str = "static") -> list[str]:+ """Paths in /spec static that say WHERE something is (keys naming positions, heights, centres; texts with world+ coordinates). Names, inventories, sizes and colours may stay in static; positions never (docs § Never provided)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}"+ if POSITION_KEY.search(str(k)) and CONVENTIONS.get(p, object()) != v:+ out.append(p)+ else:+ out += static_positions(v, p)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += static_positions(v, f"{path}[{i}]")+ elif isinstance(obj, str) and world_text(obj):+ out.append(path)+ return out+++SPEC_REQUIRED = ("protocol", "protocol_compat", "simulator", "robot", "task_text", "control_hz", "cameras", "default_cameras",+ "action_types", "proprio_layout", "proprio_groups", "static", "world", "budget", "robot_spec", "kinematics", "depth")+++def forbidden_keys(obj: Any, path: str = "", skip: tuple = ()) -> list[str]:+ """Key paths that name something the protocol never provides (key paths in `skip` are not searched)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}" if path else str(k)+ if p in skip:+ continue+ if FORBIDDEN_KEY.search(str(k)) and not (re.search(r"damping|stiffness", str(k), re.I) and p.startswith(GAIN_PATHS)):+ out.append(p)+ out += forbidden_keys(v, p, skip)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += forbidden_keys(v, f"{path}[{i}]", skip)+ return out+++def check_spec(spec: dict) -> None:+ """Raise if /spec is not a complete 2.2 spec or names anything forbidden (run at startup, before binding :8000)."""+ miss = [k for k in SPEC_REQUIRED if k not in spec]+ if miss:+ raise RuntimeError(f"/spec misses {miss}")+ if spec["protocol"] != PROTOCOL:+ raise RuntimeError(f"/spec protocol {spec['protocol']!r} != {PROTOCOL}")+ bad = forbidden_keys(spec, skip=())+ if bad:+ raise RuntimeError(f"/spec names forbidden fields: {bad}")+ pos = static_positions(spec["static"])+ if pos:+ raise RuntimeError(f"/spec static says where things are (never provided): {pos}")+ lay = spec["proprio_layout"]+ if len(set(lay)) != len(lay):+ raise RuntimeError("proprio_layout names are not unique")+ for g in PROPRIO_GROUPS_REQUIRED:+ if g not in spec["proprio_groups"]:+ raise RuntimeError(f"proprio_groups misses {g}")+ for g, (first, n, _meaning) in spec["proprio_groups"].items():+ if not (0 <= first and first + n <= len(lay)):+ raise RuntimeError(f"proprio group {g} [{first}, +{n}) outside the {len(lay)} columns")+ kin = spec["kinematics"]+ for k in ("endpoint", "joint_names", "frame", "quaternion_order", "links", "tcp_frames", "ee_frames", "ik_targets"):+ if k not in kin:+ raise RuntimeError(f"kinematics misses {k}")+ if any(j not in lay for j in kin["joint_names"]):+ raise RuntimeError("kinematics.joint_names must be proprio_layout columns (the measured joint positions)")+ if any(f not in kin["links"] for f in list(kin["tcp_frames"]) + list(kin["ee_frames"]) + list(kin["ik_targets"])):+ raise RuntimeError("kinematics tcp_frames / ee_frames / ik_targets must be listed in kinematics.links")+ if spec["proprio_groups"]["tcp_pose"][1] != 7 * len(kin["tcp_frames"]):+ raise RuntimeError("proprio group tcp_pose must hold 7 columns per kinematics.tcp_frames entry")+ for c, cam in spec["cameras"].items():+ for k in ("rgb", "depth", "mounted", "resolution", "intrinsic_cv", "mount"):+ if k not in cam:+ raise RuntimeError(f"cameras.{c} misses {k}")+ if cam["mount"].get("type") not in ("static", "link"):+ raise RuntimeError(f"cameras.{c}.mount.type must be static|link")+ if any(c not in spec["cameras"] for c in spec["default_cameras"]):+ raise RuntimeError("default_cameras must be cameras")+++# ---------------------------------------------------------------- crash recovery (PROTOCOL §4.7; docs/STANDARD_MODE_2_2.md)+MAX_RESUMES = int(os.environ.get("RCB_MAX_RESUMES", "2"))+STARTUP_TIMEOUT_S = float(os.environ.get("RCB_STARTUP_TIMEOUT_S", "900")) # a task with a slower scene build sets more+MAX_CALL_WALL_S = float(os.environ.get("RCB_MAX_CALL_WALL_S", "900")) # < the client's 1800 s /submit read timeout+RESUME_MAX_DEV_M = float(os.environ.get("RCB_RESUME_MAX_DEV_M", "0.05")) # approx resumes: the gross-divergence guard+ON_SERVICE_ERROR = ("a connection error means the service crashed: it restarts and resumes the SAME episode (never a reset) "+ "in the state after the last call it completed, which you may not have received. Wait until GET /status "+ "answers again (rcb_client: Robot.wait_ready(); resuming replays the episode so far, which can take "+ "minutes in a long episode, and the wall clock keeps running), then check calls and control_steps "+ "before you continue. A 500 means the simulator failed: the episode is over (reason \"error\"). A call "+ "that runs longer than max_call_wall_s seconds stops at the next control step and returns what it "+ "executed (meta.stopped, executed_rows).")+++def _jsonable(v: Any) -> Any:+ if isinstance(v, np.ndarray):+ return v.tolist()+ if isinstance(v, (np.floating, np.integer, np.bool_)):+ return v.item()+ if isinstance(v, (list, tuple)):+ return [_jsonable(x) for x in v]+ if isinstance(v, dict):+ return {str(k): _jsonable(x) for k, x in v.items()}+ return v+++def _peer_closed(sock) -> bool:+ """True when the client of an HTTP request has closed its connection (it gave up on the call): the socket reads as+ end-of-file. A client never sends anything while it waits for the response, so readable means closed."""+ try:+ r, _, _ = select.select([sock], [], [], 0)+ return bool(r) and sock.recv(1, socket.MSG_PEEK) == b""+ except (OSError, ValueError):+ return True+++def _read_json(path: str) -> dict:+ try:+ with open(path) as f:+ d = json.load(f)+ return d if isinstance(d, dict) else {}+ except (OSError, ValueError):+ return {}+++def _write_json(path: str, obj: dict) -> None:+ tmp = f"{path}.{os.getpid()}.tmp"+ with open(tmp, "w") as f:+ json.dump(obj, f)+ os.replace(tmp, path)+++def final_verdict(data: str) -> dict | None:+ """final.json if it already holds a verdict that nothing may overwrite: the grading result (finalized, with+ `deterministic`) or the end of an episode the service gave up after crashes (`gave_up`)."""+ fin = _read_json(os.path.join(data, "final.json"))+ if fin.get("finalized") and (fin.get("gave_up") or fin.get("deterministic") is not None):+ return fin+ return None+++class Episode:+ """Crash-safe episode bookkeeping, the same rules as the RoboTwin and MuJoCo services (PROTOCOL §4.7):++ - startup(): before the scene is built. One line in startups.jsonl; a back-off of min(120, 20 (n - 1)) s when the+ earlier starts never began an episode (they crashed while building, e.g. GPU memory taken by other trials); the+ startup watchdog (faulthandler, a C thread: it fires even when a native scene build holds the GIL) dumps every+ thread's traceback and exits 1 after RCB_STARTUP_TIMEOUT_S, so compose restarts the build. Until begin() a SIGUSR1+ (the collect hook's "the agent phase is over") is only remembered.+ - journal(row): every executed control step (the exact row given to the simulator's step) goes to journal.f64.+ - checkpoint(): after every completed call (the HTTP layer calls it): the journal is flushed, then the call's+ checkpoint is logged in episode.jsonl (rows, control steps, state hash, the robot's proprio row, `persist` keys).+ - begin(): a fresh episode, or after a crash (run.sh exits non-zero, compose restarts the container, `restart:+ on-failure:N`) the SAME episode resumed: the journal is replayed up to the last checkpoint, the journal truncated+ there (the call that was in flight is lost as a whole: its caller got an error, not a result), the state hash+ compared, the service's counters restored; the wall clock keeps running from the first start.+ - Resume check, by the simulator's determinism class: `exact` (bit-exact in a fresh process): the hash must match,+ else the episode ends `resume_failed` (infra_error). `approx` (a simulator declared nondeterministic): a+ mismatch is recorded (resume_state_mismatch, and the robot's deviation from its checkpointed proprio: joint_pos and+ tcp_pose) and the episode continues, unless a TCP is more than RCB_RESUME_MAX_DEV_M from where it was+ (resume_failed, infra_error). The verdict never comes from the live state but from fresh replays of the complete+ recorded trajectory, so continuing cannot raise a score.+ - More than RCB_MAX_RESUMES crashes end the episode: `sim_crashed_on_call` if every crash happened while a call was+ being served (the agent's failure), else `sim_crashed` (infra_error = 1). A verdict already on disk is never+ overwritten; the service then idles with its PID file for the collect hook.+ - Per call, two bounds keep one call from holding the single-threaded service: a call that runs longer than+ max_call_wall_s, or whose client has hung up, stops at the next control step and returns what it executed+ (journal() returns True; meta.stopped says why). Neither bounds the episode: the wall clock is its only budget."""++ def __init__(self, data: str, dim: int, resume: str = "exact", persist: tuple = ()):+ if resume not in ("exact", "approx"):+ raise ValueError("resume must be 'exact' or 'approx'")+ self.data, self.dim, self.resume_class, self.persist = data, int(dim), resume, tuple(persist)+ os.makedirs(data, exist_ok=True)+ p = lambda n: os.path.join(data, n) # noqa: E731+ self.f_events, self.f_journal, self.f_final, self.f_pid, self.f_startups = (+ p("episode.jsonl"), p("journal.f64"), p("final.json"), p("server.pid"), p("startups.jsonl"))+ self.rows = 0 # control steps executed in this episode (journaled)+ self.max_call_wall_s = MAX_CALL_WALL_S+ self.n_startups = 0; self.resumes = 0; self.mismatches = 0; self.max_tcp_dev = 0.0; self.max_joint_dev = 0.0+ self._jf = None; self._call: dict | None = None; self._ids = 0; self._ck: tuple | None = None+ self._on_end: Callable | None = None; self._end_pending = False++ # ---- startup+ def startup(self) -> None:+ signal.signal(signal.SIGUSR1, self._usr1)+ try:+ os.remove(self.f_pid) # a PID file from before a crash would send the collect hook to a dead process+ except OSError:+ pass+ with open(self.f_startups, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid()}) + "\n")+ with open(self.f_startups) as f:+ self.n_startups = sum(1 for line in f if line.strip())+ if self.n_startups > 1 and not any(e.get("ev") == "start" for e in self.events()):+ time.sleep(min(120.0, 20.0 * (self.n_startups - 1)))+ faulthandler.dump_traceback_later(STARTUP_TIMEOUT_S, exit=True)++ def scene_built(self) -> None:+ faulthandler.cancel_dump_traceback_later() # the scene exists: a resume replay may take long, it is not a hang++ def _usr1(self, *_):+ if self._on_end is None:+ self._end_pending = True+ else:+ threading.Thread(target=self._on_end, daemon=True).start()++ # ---- the record+ def log(self, ev: dict) -> None:+ with open(self.f_events, "a") as f:+ f.write(json.dumps(_jsonable({"ts": time.time(), **ev})) + "\n")++ def events(self) -> list:+ out = []+ try:+ with open(self.f_events) as f:+ for line in f:+ try:+ out.append(json.loads(line))+ except ValueError: # a line cut by a crash+ pass+ except OSError:+ pass+ return [e for e in out if isinstance(e, dict)]++ def journal(self, row) -> bool:+ """One executed control step. True: the call in progress must stop at this step boundary (meta.stopped)."""+ a = np.asarray(row, dtype=np.float64).reshape(-1)+ if a.size != self.dim:+ raise ValueError(f"journal rows have {self.dim} entries, got {a.size}")+ if self._jf is None:+ self._jf = open(self.f_journal, "ab")+ self._jf.write(a.tobytes()); self.rows += 1+ c = self._call+ if c is None:+ return False+ if c["stopped"] is None:+ now = time.monotonic()+ if now - c["t0"] > self.max_call_wall_s:+ c["stopped"] = "max_call_wall_s"+ elif c["sock"] is not None and now - c["polled"] >= 0.2:+ c["polled"] = now+ if _peer_closed(c["sock"]):+ c["stopped"] = "client_disconnected"+ return c["stopped"] is not None++ @property+ def stopping(self) -> bool:+ """The call in progress must stop (adapters whose loops test E["done"] test this too)."""+ return bool(self._call and self._call["stopped"])++ @property+ def stop_reason(self) -> str | None:+ return self._call["stopped"] if self._call else None++ def call_begin(self, path: str, sock=None) -> int:+ self._ids += 1+ if path != "/kinematics":+ self._call = {"id": self._ids, "t0": time.monotonic(), "sock": sock, "polled": 0.0, "stopped": None}+ self.log({"ev": "call_begin", "id": self._ids, "path": path})+ return self._ids++ def call_end(self, cid: int, path: str, **extra) -> None:+ self.log({"ev": "call_end", "id": cid, "path": path, **extra})+ if path != "/kinematics":+ self._call = None++ def checkpoint(self, state: dict, state_sha: Callable | None, proprio: Callable | None) -> None:+ if self._jf is not None:+ self._jf.flush() # the rows reach the file before the checkpoint that counts them+ if self._ck is not None and self._ck[0] == self.rows:+ sha, pr = self._ck[1], self._ck[2] # no physics since the last checkpoint+ else:+ try:+ sha = state_sha() if state_sha else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); sha = None+ pr = self._proprio_row(proprio)+ self._ck = (self.rows, sha, pr)+ self.log({"ev": "checkpoint", "call": int(state.get("calls") or 0), "step": int(state.get("step") or 0),+ "control_steps": self.rows, "success": bool(state.get("success")), "done": bool(state.get("done")),+ "reason": state.get("reason"), "state_sha": sha, "proprio": pr,+ **({"persist": {k: state.get(k) for k in self.persist}} if self.persist else {})})++ @staticmethod+ def _proprio_row(proprio: Callable | None) -> list | None:+ try:+ return [round(float(v), 6) for v in np.asarray(proprio(), dtype=np.float64).reshape(-1)] if proprio else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); return None++ def final_fields(self) -> dict:+ """Crash-recovery fields for final.json / episode.json (all numeric, for reward.json)."""+ return {"sim_startups": self.n_startups, "resumes": self.resumes, "resume_state_mismatch": int(self.mismatches > 0),+ "resume_max_tcp_dev_m": round(self.max_tcp_dev, 6), "resume_max_joint_dev": round(self.max_joint_dev, 6)}++ # ---- start or resume+ def begin(self, *, state: dict, step: Callable, state_sha: Callable, proprio: Callable, spec: dict,+ start_event: dict | None = None, on_end: Callable | None = None) -> bool:+ """Start the episode, or resume it after a crash. `step(row)` executes one journaled row on the simulator (the+ recorder on, no rendering needed); `on_end` is what the collect hook's SIGUSR1 runs (in a thread). Returns True+ if the episode was resumed."""+ try: # a line cut by the crash must not swallow the next record+ with open(self.f_events, "rb+") as f:+ f.seek(0, os.SEEK_END)+ if f.tell():+ f.seek(-1, os.SEEK_END)+ if f.read(1) != b"\n":+ f.write(b"\n")+ except OSError:+ pass+ ev = self.events()+ starts = [e for e in ev if e.get("ev") == "start"]+ if not starts:+ try:+ os.remove(self.f_journal)+ except OSError:+ pass+ sha = state_sha()+ self._ck = (0, sha, self._proprio_row(proprio))+ self.log({**(start_event or {}), "ev": "start", "state_sha": sha, "protocol": PROTOCOL, "resume": self.resume_class,+ "journal_dim": self.dim})+ state["t0"] = time.time()+ self._arm(on_end)+ return False+ tries = [e for e in ev if e.get("ev") == "resuming"] # earlier resumes (a crash during one counts too)+ resumed = [e for e in ev if e.get("ev") == "resumed"]+ self.resumes = len(tries) # the record so far, also for a give-up below (final_fields)+ self.mismatches = sum(1 for e in resumed if e.get("exact") is False)+ self.max_tcp_dev = max([float(e.get("tcp_dev_m") or 0) for e in resumed] + [0.0])+ self.max_joint_dev = max([float(e.get("joint_dev") or 0) for e in resumed] + [0.0])+ if final_verdict(self.data):+ self.give_up("restarted after finalize", infra=False)+ k = max(i for i, e in enumerate(ev) if e.get("ev") in ("start", "resuming", "resumed"))+ tail = ev[k + 1:]+ in_call = bool({e.get("id") for e in tail if e.get("ev") == "call_begin"} - {e.get("id") for e in tail if e.get("ev") == "call_end"})+ if len(tries) >= MAX_RESUMES:+ agent = sum(1 for e in tries if e.get("crashed_in_call")) + int(in_call) == len(tries) + 1+ self.give_up("sim_crashed_on_call" if agent else "sim_crashed", infra=not agent)+ self.log({"ev": "resuming", "attempt": len(tries) + 1, "crashed_in_call": in_call,+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self.resumes = len(tries) + 1 # this attempt counts, whether or not it succeeds+ cps = [e for e in ev if e.get("ev") == "checkpoint"]+ last = cps[-1] if cps else {"call": 0, "step": 0, "control_steps": 0, "success": False, "state_sha": starts[0].get("state_sha")}+ n = int(last.get("control_steps") or 0)+ try:+ R = np.fromfile(self.f_journal, dtype=np.float64)+ except (OSError, ValueError):+ R = np.zeros(0)+ if R.size < n * self.dim:+ self.give_up("resume_failed: journal shorter than the log", infra=True)+ R = R[: n * self.dim].reshape(n, self.dim)+ t = time.time()+ for row in R:+ step(row)+ replay_s = time.time() - t+ R.tofile(self.f_journal) # drop the rows of the call that was in flight+ self.rows = n+ sha = state_sha(); want = last.get("state_sha")+ exact = None if want is None else sha == want+ dev = self._deviation(last.get("proprio"), proprio, spec)+ if exact is False: # recorded first: a give-up below reports it too+ self.mismatches += 1+ self.max_tcp_dev = max(self.max_tcp_dev, dev.get("tcp_m") or 0.0)+ self.max_joint_dev = max(self.max_joint_dev, dev.get("joint") or 0.0)+ if self.resume_class == "exact":+ self.give_up("resume_failed: replayed state differs from the logged one", infra=True)+ if dev.get("tcp_m") is not None and dev["tcp_m"] > RESUME_MAX_DEV_M:+ self.give_up(f"resume_failed: a replayed TCP is {dev['tcp_m']:.3f} m from its checkpoint (> {RESUME_MAX_DEV_M} m)", infra=True)+ state["calls"] = int(last.get("call") or 0); state["step"] = int(last.get("step") or 0)+ if "success" in state:+ state["success"] = bool(last.get("success"))+ for key, v in (last.get("persist") or {}).items():+ state[key] = v+ state["t0"] = float(starts[0]["ts"])+ ended = [e for e in ev if e.get("ev") == "end" and int(e.get("control_steps") or 0) <= n] # not the lost call's+ if ended:+ state["done"] = True; state["reason"] = ended[-1].get("reason"); state["t_end"] = float(ended[-1]["ts"])+ state["episode_control_steps"] = int(ended[-1].get("control_steps") or n)+ self._ck = (n, sha, self._proprio_row(proprio)) # the replayed state's row (it may differ under approx)+ self.log({"ev": "resumed", "attempt": self.resumes, "control_steps": n, "calls": state["calls"], "state_sha": sha,+ "logged_sha": want, "exact": exact, "class": self.resume_class, "tcp_dev_m": dev.get("tcp_m"),+ "joint_dev": dev.get("joint"), "crashed_in_call": in_call, "replay_s": round(replay_s, 1),+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self._arm(on_end)+ return True++ @staticmethod+ def _deviation(ref, proprio: Callable, spec: dict) -> dict:+ """The replayed robot against its checkpointed proprio row: max |joint_pos| difference (rad or m) and the largest+ TCP position error (m) over the tcp_pose frames (7 columns each: x y z + quaternion)."""+ if ref is None:+ return {}+ try:+ now = np.asarray(proprio(), dtype=np.float64).reshape(-1); ref = np.asarray(ref, dtype=np.float64).reshape(-1)+ except Exception: # noqa: BLE001+ return {}+ if now.shape != ref.shape:+ return {}+ g, out = spec.get("proprio_groups") or {}, {}+ if "joint_pos" in g:+ f, n = int(g["joint_pos"][0]), int(g["joint_pos"][1])+ out["joint"] = float(np.max(np.abs(now[f:f + n] - ref[f:f + n]))) if n else 0.0+ if "tcp_pose" in g:+ f, n = int(g["tcp_pose"][0]), int(g["tcp_pose"][1]); m = n // 7+ d = (now[f:f + 7 * m] - ref[f:f + 7 * m]).reshape(m, 7)[:, :3]+ out["tcp_m"] = float(np.max(np.linalg.norm(d, axis=1))) if m else 0.0+ return out++ def _arm(self, on_end: Callable | None) -> None:+ self._on_end = on_end+ signal.signal(signal.SIGUSR1, self._usr1)+ if on_end is not None and self._end_pending:+ self._end_pending = False+ threading.Thread(target=on_end, daemon=True).start()++ def give_up(self, reason: str, infra: bool) -> None:+ """End the trial's episode without a new one (never a reset): log it, write the verdict unless one is on disk,+ leave the PID file for the collect hook, and idle until the container is removed."""+ faulthandler.cancel_dump_traceback_later()+ self.log({"ev": "restart_refused", "reason": reason})+ if not final_verdict(self.data):+ fin = _read_json(self.f_final)+ fin.update({"success": False, "done": True, "reason": reason, "finalized": True, "gave_up": True, "protocol": PROTOCOL,+ **self.final_fields(), **({"infra_error": 1} if infra else {})})+ _write_json(self.f_final, fin)+ with open(self.f_pid, "w") as f:+ f.write(str(os.getpid()))+ signal.signal(signal.SIGUSR1, lambda *_: None)+ print(f"[{PROTOCOL}] restart refused: {reason}", flush=True)+ while True:+ time.sleep(3600)+++# ---------------------------------------------------------------- the HTTP layer+class Service:+ """What a sim service hands to serve(): spec (dict), lock, state (the service's E dict: done, reason, exiting, error),+ submit(meta, actions) and observe(meta) -> (meta_out, rcb1 parts), kinematics(req) -> dict, status() -> dict,+ on_submit_error(exc) (a simulator error in /submit or /observe: it ends the episode, reason "error"), log(event dict),+ and for crash recovery the Episode with the simulator's state_sha() and proprio row()."""++ def __init__(self, *, spec: dict, lock, state: dict, submit: Callable, observe: Callable, kinematics: Callable,+ status: Callable, on_submit_error: Callable, log: Callable, max_resp: int = MAX_RESP,+ episode: Episode | None = None, state_sha: Callable | None = None, proprio: Callable | None = None):+ self.spec, self.lock, self.state, self.submit, self.observe = spec, lock, state, submit, observe+ self.kinematics, self.status, self.on_submit_error, self.log, self.max_resp = kinematics, status, on_submit_error, log, max_resp+ self.episode, self.state_sha, self.proprio = episode, state_sha, proprio+ self.kin_calls = 0+++def make_handler(svc: Service):+ class H(BaseHTTPRequestHandler):+ def _send(self, code: int, ctype: str, body: bytes) -> None:+ try:+ self.send_response(code); self.send_header("Content-Type", ctype); self.send_header("Content-Length", str(len(body)))+ self.end_headers(); self.wfile.write(body)+ except (BrokenPipeError, ConnectionResetError): # the client hung up (its call was abandoned)+ pass++ def _json(self, code: int, obj: dict) -> None:+ self._send(code, "application/json", json.dumps(obj).encode())++ def _rcb1(self, meta: dict, parts: list) -> None:+ self._send(200, "application/x-rcb1", encode_response(meta, parts, svc.max_resp))++ def log_message(self, *a):+ pass++ def _body(self):+ try:+ n = int(self.headers.get("Content-Length", 0))+ except ValueError:+ raise ValueError("bad Content-Length")+ if n > MAX_BODY:+ raise ValueError("request too large")+ raw = self.rfile.read(n) if n else b""+ if raw[:4] == rcb1.MAGIC:+ return rcb1.decode(raw)+ body = json.loads(raw or b"{}")+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object or an RCB1 frame")+ return body, {}++ def do_GET(self):+ if self.path == "/spec":+ return self._json(200, svc.spec)+ if self.path == "/status":+ st = svc.status()+ return self._json(200, {**st, "resumes": svc.episode.resumes} if svc.episode else st)+ return self._json(404, {"error": "no such endpoint"})++ def do_POST(self):+ if self.path not in ("/submit", "/observe", "/kinematics"):+ return self._json(404, {"error": "no such endpoint"})+ try:+ meta, parts = self._body()+ except Exception as exc: # noqa: BLE001+ return self._json(413 if "too large" in str(exc) else 400, {"error": str(exc)[:200]})+ E, ep = svc.state, svc.episode+ if self.path == "/kinematics": # stateless: never steps physics, never waits for the episode lock+ cid = ep.call_begin(self.path) if ep else 0+ try:+ req = parse_kinematics(meta, svc.spec["kinematics"])+ out = svc.kinematics(req); svc.kin_calls += 1+ except ValueError as exc:+ return self._json(400, {"error": str(exc)[:300]})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); return self._json(500, {"error": "kinematics error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ ep.call_end(cid, self.path)+ return self._json(200, out)+ with svc.lock:+ if E.get("exiting") or (self.path == "/submit" and E.get("done")):+ return self._json(409, {"error": "episode finished", "reason": E.get("reason")})+ cid = ep.call_begin(self.path, self.connection) if ep else 0+ rows0 = ep.rows if ep else 0+ out = blobs = err = None; stopped = None+ try:+ if self.path == "/submit":+ A = np.asarray(parts["actions"]["data"] if "actions" in parts else meta.get("actions", []), dtype=np.float64)+ out, blobs = svc.submit(meta, A)+ else:+ out, blobs = svc.observe(meta)+ except ValueError as exc:+ err = (400, {"error": str(exc)})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); E["error"] = repr(exc); svc.log({"ev": "error", "path": self.path, "error": repr(exc)})+ try:+ svc.on_submit_error(exc) # PROTOCOL §4.6: a simulator error ends the episode (reason "error")+ except Exception: # noqa: BLE001+ traceback.print_exc()+ err = (500, {"error": "simulator error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ stopped = ep.stop_reason+ if err is None or ep.rows != rows0:+ try:+ ep.checkpoint(E, svc.state_sha, svc.proprio)+ except Exception: # noqa: BLE001+ traceback.print_exc()+ ep.call_end(cid, self.path, **({"stopped": stopped} if stopped else {}))+ if err is not None:+ return self._json(*err)+ return self._rcb1({**out, "stopped": stopped}, blobs)+ return H+++def serve(svc: Service, port: int = 8000) -> None:+ """Check the spec, then serve forever (one request at a time, as every 2.x service)."""+ svc.spec.setdefault("on_service_error", ON_SERVICE_ERROR)+ if svc.episode is not None:+ svc.spec.setdefault("max_call_wall_s", svc.episode.max_call_wall_s)+ check_spec(svc.spec)+ HTTPServer(("0.0.0.0", port), make_handler(svc)).serve_forever()+++# ---------------------------------------------------------------- the collect hook's first half+def _alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ try: # a zombie (exited, not yet reaped) counts as gone+ with open(f"/proc/{pid}/stat") as f:+ return f.read().rsplit(")", 1)[-1].split()[0] != "Z"+ except OSError:+ return True+++def end_episode(data: str, timeout: float = 21600.0, wait_key: str | None = None, resend_s: float = 30.0) -> int:+ """Tell the service that the agent phase is over and wait until it has ended the episode. The service may be+ resuming after a crash (no PID file until it is ready again), so there is no fixed start-up wait, and a signal goes+ only to the process that wrote the newest line of startups.jsonl (its SIGUSR1 handler is installed by then).+ Returns 2: final.json already holds the verdict (the service gave up after crashes, or graded in-process; with+ `wait_key`, also waits for that final.json key, e.g. video_done): keep it, run no replays.+ Returns 0: the service dumped the episode (episode.json) and exited: the hook replays it next.+ Returns 1: timed out."""+ t0, sent = time.time(), 0.0+ f_pid, f_dump, f_starts = (os.path.join(data, n) for n in ("server.pid", "episode.json", "startups.jsonl"))+ while time.time() - t0 < timeout:+ fin = final_verdict(data)+ if fin is not None:+ if not wait_key or fin.get(wait_key) or fin.get("gave_up"):+ return 2+ time.sleep(2); continue+ try:+ with open(f_pid) as f:+ pid = int(f.read().strip())+ except (OSError, ValueError):+ pid = None+ try:+ with open(f_starts) as f:+ cur = json.loads([x for x in f if x.strip()][-1]).get("pid")+ except (OSError, ValueError, IndexError):+ cur = None # a service without Episode.startup(): signal what the PID file names+ if pid is not None and (cur is None or pid == cur):+ if not _alive(pid):+ if os.path.exists(f_dump):+ return 0+ elif time.time() - sent >= resend_s:+ try:+ os.kill(pid, signal.SIGUSR1); sent = time.time()+ except OSError:+ pass+ time.sleep(2)+ return 1+++if __name__ == "__main__":+ a = sys.argv[1:]+ if len(a) >= 2 and a[0] == "end":+ wk = a[a.index("--wait-key") + 1] if "--wait-key" in a else None+ to = float(a[a.index("--timeout") + 1]) if "--timeout" in a else 21600.0+ rc = end_episode(a[1], timeout=to, wait_key=wk)+ print({0: "[collect] episode dumped by the service", 1: "[collect] timed out waiting for the service",+ 2: "[collect] final.json already holds the verdict"}[rc], flush=True)+ sys.exit(rc)+ if len(a) == 2 and a[0] == "final-verdict":+ fin = final_verdict(a[1])+ print(json.dumps(fin) if fin else "no final verdict")+ sys.exit(0 if fin else 1)+ print("usage: rcb_limited.py end <data dir> [--wait-key KEY] [--timeout S] | final-verdict <data dir>")+ sys.exit(2)diff --git a/tasks/mujoco_playground_go1_handstand-standard/environment/sim/rcb_quadruped.py b/tasks/mujoco_playground_go1_handstand-standard/environment/sim/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/environment/sim/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_go1_handstand-standard/environment/sim/run.sh b/tasks/mujoco_playground_go1_handstand-standard/environment/sim/run.shnew file mode 100755index 0000000000..49d4d045d4--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/environment/sim/run.sh@@ -0,0 +1,22 @@+#!/bin/sh+# eai-standard/2.2 sidecar entrypoint: PID 1 of the `sim` container, shared by every 2.2 service+# (scripts/eai_standard/run.sh, copied unchanged into each standard task's environment/sim/).+# - The service crashed (a non-zero exit: an exception, a signal, the startup watchdog): exit with its code, so compose+# restarts the container (`restart: on-failure:6`) and the service resumes the same episode from its journal+# (rcb_limited.Episode). The container keeps its /data (or /out) across the restart.+# - The service exited cleanly (0: it dumped its episode on the collect hook's SIGUSR1 and released the simulator): keep+# the container up for the collect hook's fresh-process replays. If the service were PID 1 itself, that exit would+# stop the container and kill the hook with it (Harbor reports exit 137).+# - Everything the service prints also goes to $RCB_DATA/server.log (an artifact: Harbor keeps no sidecar output, and a+# simulator that dies while it loads leaves no other trace).+DATA="${RCB_DATA:-/data}"+mkdir -p "$DATA"+rm -f "$DATA/.service_rc"+{ python -u "${RCB_SERVER:-/srv/server.py}" 2>&1; echo "$?" > "$DATA/.service_rc"; } | tee -a "$DATA/server.log"+rc="$(cat "$DATA/.service_rc" 2>/dev/null)"; rc="${rc:-1}"+if [ "$rc" != 0 ]; then+ echo "[sim] service exited ($rc): leaving, so compose restarts the container (the service resumes the episode if one began)" | tee -a "$DATA/server.log"+ exit "$rc"+fi+echo "[sim] service exited (0); holding the container open for the collect hook" | tee -a "$DATA/server.log"+while true; do sleep 3600; donediff --git a/tasks/mujoco_playground_go1_handstand-standard/environment/sim/server.py b/tasks/mujoco_playground_go1_handstand-standard/environment/sim/server.pynew file mode 100644index 0000000000..b0c774b183--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/environment/sim/server.py@@ -0,0 +1,478 @@+"""eai-standard/2.2 sim service for MuJoCo Playground's quadruped tasks (docs/STANDARD_MODE_2_2.md): the adapter of the+shared layer rcb_limited.py; the simulator is rcb_quadruped.Session (plain MuJoCo on the CPU).+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to+/data/episode.jsonl.++The episode is the frozen instance's: one control step = 1/50 s. A joystick episode ends after the whole command schedule+(the horizon), when the robot meets Playground's termination rule (it falls over: a failure), when the agent submits+`done`, or when its time is over; success = the task's check on the steps executed. A getup episode ends the moment the+check holds (success), after the horizon, on `done` or on timeout.++Crash recovery (rcb_limited.Episode, resume class `exact`: MuJoCo on the CPU repeats bit for bit in a fresh process):+every executed row is journaled; after a crash the service rebuilds the episode and replays the journal. When the+episode ends the service writes /data/trajectory.npz + /data/episode.json; the collect hook (finalize.sh) makes it exit+and replays the trajectory in two fresh processes."""++import math+import os+import sys+import threading+import time+import traceback++import numpy as np++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import rcb_limited as L # noqa: E402++DATA = os.environ.get("RCB_DATA", "/data")+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.json"))+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "3600"))+MAX_CHUNK_S = float(os.environ.get("RCB_MAX_CHUNK_S", "10"))+MAX_WATCH_S = float(os.environ.get("RCB_MAX_WATCH_S", "30"))+CAM_W, CAM_H = 320, 240+LOCK = threading.Lock()+PID_FILE = os.path.join(DATA, "server.pid")+E = {"ready": False, "step": 0, "calls": 0, "done": False, "reason": None, "success": False, "t0": time.time(), "error": None}++os.environ["RCB_SESSION_LOG"] = ""+os.environ["RCB_AGENT_TRACE_DIR"] = ""+import rcb_quadruped as Q # noqa: E402 (first: it picks the rendering backend before mujoco loads)+import mujoco # noqa: E402++EP = L.Episode(DATA, dim=Q.N, resume="exact")+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()+S = Q.Session(INSTANCE)+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz+DT = S.control_dt # one control step of simulated time (Barkour: 10 ms, as Playground steps it)+CTRL_HZ = 1.0 / DT+SUBSTEPS = S.substeps+M = S.model+CAMS = list(S.cameras)+FEET = S.robot["feet"]+LIMITS = np.stack([S.lower, S.upper], axis=1)+GROUPS = [+ ("joint_pos", S.joint_names, "measured joint positions (rad), in the action's order"),+ ("joint_vel", [f"{j}_vel" for j in S.joint_names], "measured joint velocities (rad/s)"),+ ("joint_effort", [f"{j}_effort" for j in S.joint_names], "actuator torques of those joints (N m)"),+ ("gripper_opening", [], "none (no gripper)"),+ ("tcp_pose", [], "none (no gripper)"),+ ("imu_gyro", ["gyro_x", "gyro_y", "gyro_z"], "angular velocity of the trunk, IMU frame (rad/s)"),+ ("imu_accelerometer", ["acc_x", "acc_y", "acc_z"], "specific force at the IMU, IMU frame (m/s^2; +9.81 up at rest)"),+ ("imu_gravity", ["gravity_x", "gravity_y", "gravity_z"], "unit vector of gravity's direction in the IMU frame "+ "([0, 0, -1] when the trunk is level)"),+ ("imu_linvel", ["linvel_x", "linvel_y", "linvel_z"], "linear velocity of the trunk at the IMU, IMU frame (m/s; the "+ "IMU's velocimeter, what a state estimator gives)"),+ ("foot_contact", [f"{f}_contact" for f in FEET], "1 when the foot touches the ground, else 0"),+]+PROPRIO_LAYOUT = [n for _, names, _ in GROUPS for n in names]+PROPRIO_GROUPS, _i = {}, 0+for _g, _names, _meaning in GROUPS:+ PROPRIO_GROUPS[_g] = [_i, len(_names), _meaning]+ _i += len(_names)+++# ------------------------------------------------------------------------------------------------- cameras+def _intrinsic(cam: str) -> list:+ fovy = math.radians(float(M.cam_fovy[M.camera(cam).id]))+ f = 0.5 * CAM_H / math.tan(fovy / 2)+ return [[f, 0.0, CAM_W / 2], [0.0, f, CAM_H / 2], [0.0, 0.0, 1.0]]+++def camera_info(cam: str) -> dict:+ """World -> camera (OpenCV axes) and camera -> world (OpenGL axes) at the current state."""+ i = M.camera(cam).id+ R_gl = S.data.cam_xmat[i].reshape(3, 3) # camera axes (OpenGL: x right, y up, z back) in the world+ p = S.data.cam_xpos[i].copy()+ R_cv = R_gl @ np.diag([1.0, -1.0, -1.0])+ ext = np.zeros((3, 4))+ ext[:, :3] = R_cv.T+ ext[:, 3] = -R_cv.T @ p+ c2w = np.eye(4)+ c2w[:3, :3] = R_gl+ c2w[:3, 3] = p+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": ext.tolist(), "cam2world_gl": c2w.tolist(),+ "image_size": [CAM_W, CAM_H]}+++# ------------------------------------------------------------------------------------------------- kinematics+KD = mujoco.MjData(M) # kinematics only: the trunk at the origin, level; never stepped+_FOOT = {f: M.site(f).id for f in FEET}+_LEG_DOF = {f: [6 + 3 * k + j for j in range(3)] for k, f in enumerate(FEET)} # actuator order = leg order = FEET+++def _fk_kd(q) -> None:+ KD.qpos[:] = 0.0+ KD.qpos[3] = 1.0+ KD.qpos[7:] = q+ mujoco.mj_kinematics(M, KD)+++def _foot_pose(f: str) -> list:+ quat = np.zeros(4)+ mujoco.mju_mat2Quat(quat, KD.site_xmat[_FOOT[f]])+ return [*KD.site_xpos[_FOOT[f]].tolist(), *quat.tolist()]+++def do_kinematics(req: dict) -> dict:+ """Feet in the trunk frame (the trunk body's origin and axes; x forward, y left, z up). IK solves positions only, one+ leg (3 joints) per foot target, damped least squares within the joint ranges; a foot's orientation is ignored."""+ if req["op"] == "fk":+ _fk_kd(np.asarray(req["q"]))+ return L.fk_response({f: _foot_pose(f) for f in req["links"]}, "trunk")+ q = np.array(req["seed"] if req["seed"] is not None else S.data.qpos[7:], dtype=np.float64)+ errors = {}+ jac = np.zeros((3, M.nv))+ for f, pose in req["targets"].items():+ tgt = np.asarray(pose[:3])+ idx = _LEG_DOF[f]+ for _ in range(req["max_iters"]):+ _fk_kd(q)+ err = tgt - KD.site_xpos[_FOOT[f]]+ if np.linalg.norm(err) < req["tol_pos_m"]:+ break+ mujoco.mj_jacSite(M, KD, jac, None, _FOOT[f])+ J = jac[:, idx]+ dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(3), err)+ q[[i - 6 for i in idx]] = np.clip(q[[i - 6 for i in idx]] + dq, S.lower[[i - 6 for i in idx]],+ S.upper[[i - 6 for i in idx]])+ _fk_kd(q)+ errors[f] = (float(np.linalg.norm(tgt - KD.site_xpos[_FOOT[f]])), 0.0)+ ok = all(e[0] <= req["tol_pos_m"] for e in errors.values())+ return L.ik_response(q, ok, errors, "trunk", note="feet: position only (a foot is a sphere; its orientation is ignored)")+++# ------------------------------------------------------------------------------------------------- spec+def schedule_text() -> list:+ if S.commands is None:+ return []+ return [{"from_s": round(int(c["start_step"]) * DT, 2), "vx_mps": round(c["vx"], 4), "vy_mps": round(c["vy"], 4),+ "wz_radps": round(c["wz"], 4)} for c in S.inst["commands"]]+++TASK_EPISODE = {+ "joystick": f"one episode, no reset: it ends after {S.horizon} control steps (the {S.horizon * DT:g} s command "+ f"schedule), when the robot meets its termination rule ({S.spec.get('term_text')}: a failure), when you "+ "submit `done`, or when your time is over",+ "getup": f"one episode, no reset: it ends the moment the robot has stood upright for {Q.HOLD_STEPS} control steps in a "+ f"row (success), after {S.horizon} control steps, when you submit `done`, or when your time is over",+ "stand_on_two": f"one episode, no reset: it ends the moment the pose has been held for {Q.POSE_HOLD_STEPS} control steps "+ "in a row (success), when the robot meets the termination rule (a failure: its trunk's up axis below "+ f"-0.25, or {'a leg' if S.spec.get('hind_leg_contact') else 'a front leg'}'s thigh, calf or hip on the "+ f"floor), after {S.horizon} control steps, when you "+ "submit `done`, or when your time is over",+}[S.kind]+_ctl = {"type": "joint position actuators (PD)", "kp_nm_per_rad": float(M.actuator_gainprm[0, 0]),+ "kd_nms_per_rad": float(M.dof_damping[6] - M.actuator_biasprm[0, 2])}+SPEC = {+ "protocol": L.PROTOCOL,+ "protocol_compat": list(L.COMPAT),+ "simulator": "MuJoCo 3.3.7 (MuJoCo Playground's scene, plain MuJoCo on the CPU)",+ "robot": S.robot["name"],+ "task_text": S.inst["text"],+ "control_hz": CTRL_HZ,+ "physics_substeps": SUBSTEPS,+ "max_chunk_s": MAX_CHUNK_S,+ "max_watch_s": MAX_WATCH_S,+ "cameras": {c: {"rgb": True, "depth": True, "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),+ **({"mounted": "follows the robot", "mount": {"type": "link", "link": S.robot["root"], "note":+ "follows the robot's centre of mass at a fixed offset; it does not turn with the robot"}}+ if int(M.cam_mode[M.camera(c).id]) != 0 else+ {"mounted": "on the robot's head", "mount": {"type": "link", "link": M.body(M.cam_bodyid[M.camera(c).id]).name+ or S.robot["root"], "note": "fixed to the robot: moves and turns with it"}})}+ for c in CAMS},+ "default_cameras": ["track"],+ "action_types": {+ "joint_position": {+ "dim": Q.N,+ "layout": S.joint_names,+ "limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "units": "rad",+ "semantics": "absolute targets of the 12 joint position actuators, one per control step (1/50 s); rows `dt` "+ "apart (a multiple of the control period, at most 0.5 s), `hold` or `linear` between rows; values "+ "outside the limits are clipped and reported",+ },+ "done": {"dim": 0, "layout": [], "semantics": 'ends the episode now, in the current state (no physics); r.submit("done", [])'},+ "not_yet": ["joint_velocity", "joint_torque", "joint_delta"],+ },+ "proprio_layout": PROPRIO_LAYOUT,+ "proprio_groups": PROPRIO_GROUPS,+ "static": {},+ "world": {"frame": "z up; the robot starts where the episode puts it (no world coordinates are given)", "up": "+z",+ "units": {"length": "m", "angle": "rad", "time": "s"}, "quaternion_order": "wxyz",+ "camera_axes": "intrinsic_cv / extrinsic_cv: OpenCV camera axes (x right, y down, z forward); cam2world_gl: OpenGL axes"},+ "budget": {"reset": 0, "steps": None, "wall_clock_s": WALL_CLOCK_S},+ "max_control_steps": S.horizon,+ "episode": TASK_EPISODE,+ "command_schedule": schedule_text(),+ **({"gait": {k: S.gait[k] for k in ("name", "frequency_hz", "foot_height_m", "phase0", "phase_dt")} | {+ "feet": FEET, "rule": "foot i's target height at control step t is get_rz(wrap(phase0[i] + t * phase_dt)) with "+ "Playground's gait.get_rz (a cubic Bezier from 0 up to foot_height_m over the first half of the phase, then "+ "down); phases in rad, wrapped to [-pi, pi)"}} if S.gait else {}),+ "robot_spec": {"name": S.robot["name"], "joints": S.joint_names, "joint_limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "joint_order": S.robot["joint_text"], "home_pose": dict(zip(S.joint_names, S.home.tolist())),+ "feet": FEET, "controller": _ctl},+ "kinematics": {"endpoint": "/kinematics", "joint_names": S.joint_names, "frame": "trunk", "quaternion_order": "wxyz",+ "links": FEET, "tcp_frames": [], "ee_frames": FEET, "ik_targets": FEET,+ "ik": {"tol_pos_m": 0.002, "tol_rot_rad": 3.2, "max_iters": 100},+ "note": "poses of the feet in the trunk frame (x forward, y left, z up, metres) for joint positions q; "+ "ik: one leg per foot, positions only"},+ "depth": {"modes": list(L.DEPTH_MODES), "default": "none", "kind": "z-depth", "unit": "m", "invalid": 0,+ "max_m": L.DEPTH_MAX_M, "frames_encoding": "uint16 mm, zlib", "noise": L.DEPTH_NOISE},+}+L.check_spec(SPEC) # a spec that misses a 2.2 field or names a forbidden one never starts the episode+EP.scene_built()++_RENDER = {}+++def _renderer():+ if "r" not in _RENDER:+ _RENDER["r"] = mujoco.Renderer(M, CAM_H, CAM_W)+ return _RENDER["r"]+++def ctrl_steps() -> int:+ return S.steps+++def proprio_row() -> np.ndarray:+ d = S.data+ return np.concatenate([d.qpos[7:], d.qvel[6:], d.actuator_force, S.sensor("gyro"), S.sensor("accelerometer"), S.gravity(),+ S.sensor("local_linvel"), S.foot_contacts()]).astype(np.float32)+++def grab(cams, want_depth: bool):+ r = _renderer()+ rgb, dep = {}, {}+ for c in cams:+ r.update_scene(S.data, camera=c)+ rgb[c] = r.render().copy()+ if want_depth:+ r.enable_depth_rendering()+ r.update_scene(S.data, camera=c)+ dep[c] = r.render().astype(np.float32).copy()+ r.disable_depth_rendering()+ return rgb, dep+++def extrinsics(cams) -> dict:+ return {c: np.asarray(camera_info(c)["extrinsic_cv"], dtype=np.float64) for c in cams}+++def write_final() -> None:+ if L.final_verdict(DATA): # finalize.sh's verdict, or a give-up after crashes: never overwritten+ return+ L._write_json(os.path.join(DATA, "final.json"), {**summary(), "finalized": False, "live_sha": E.get("live_sha")})+++def summary() -> dict:+ n = int(E.get("episode_control_steps") or ctrl_steps())+ chk = E.get("check") or {}+ return {"success": bool(E["success"]), "steps": E["step"], "calls": E["calls"], "control_steps": n,+ "physics_steps": n * SUBSTEPS, "elapsed_s": round((E.get("t_end") or time.time()) - E["t0"], 1),+ "reason": E["reason"], "done": E["done"], "env": S.env, "protocol": L.PROTOCOL, "n_actions": len(ROWS),+ "fell_at": chk.get("fell_at"), "worst_lin_err": chk.get("worst_lin_err"), "worst_yaw_err": chk.get("worst_yaw_err"),+ "tilt_deg": chk.get("tilt_deg"), "imu_height": chk.get("imu_height"), "pose_angle_deg": chk.get("pose_angle_deg"),+ **EP.final_fields()}+++def finish(reason: str) -> None:+ """The episode is over: the task's check on the steps executed, then the record for the collect hook."""+ if E["done"]:+ return+ E["done"] = True+ E["reason"] = reason+ E["t_end"] = time.time()+ E["episode_control_steps"] = ctrl_steps()+ try:+ chk = S.check()+ E["check"] = {k: v for k, v in chk.items() if k != "segments"}+ E["success"] = bool(chk["success"])+ except Exception: # noqa: BLE001+ traceback.print_exc()+ EP.log({"ev": "end", "reason": reason, "step": E["step"], "control_steps": ctrl_steps(), "success": bool(E["success"])})+ dump()+++def dump() -> None:+ if E.get("dumped"):+ return+ E["dumped"] = True+ E["live_sha"] = S.state_sha()+ np.savez(os.path.join(DATA, "trajectory.npz"), actions=np.asarray(ROWS, dtype=np.float64).reshape(-1, Q.N),+ env=S.env, action_layout=",".join(S.joint_names))+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})+ write_final()+++def after_step() -> None:+ if S.kind in ("joystick", "stand_on_two") and S.fell_at is not None:+ finish("fell")+ elif S.kind in ("getup", "stand_on_two") and S.check()["success"]:+ finish("success")+ elif S.done:+ finish("horizon")+++def ctrl_step(a, rec) -> bool:+ """One executed control step, journaled. True when the call must stop here."""+ S.step(a)+ ROWS.append(np.asarray(a, dtype=np.float64))+ stop = EP.journal(a)+ rec.tick()+ after_step()+ return E["done"] or stop+++def recorder(cams, fps: int, meta: dict) -> L.Recorder:+ return L.Recorder(cams, max(1, int(round(CTRL_HZ / max(1, fps)))), grab, proprio_row, extrinsics, ctrl_steps,+ depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+++def video_fps(meta: dict) -> int:+ fps = meta.get("video_fps")+ if fps is None:+ return 10+ if isinstance(fps, bool) or not isinstance(fps, (int, float)) or not (1 <= fps <= 50):+ raise ValueError("video_fps must be in [1, 50]")+ return int(fps)+++def cameras_of(meta: dict) -> list:+ cams = meta.get("cameras") or ["track"]+ bad = [c for c in cams if c not in CAMS]+ if bad:+ raise ValueError(f"unknown cameras {bad}; cameras: {CAMS}")+ return list(cams)+++def meta_common(cams) -> dict:+ n = ctrl_steps()+ out = {"step": E["step"], "calls": E["calls"], "control_steps": n, "physics_steps": n * SUBSTEPS,+ "sim_time_s": round(n * DT, 3), "time_s": round(time.time() - E["t0"], 2),+ "time_left_s": max(0.0, round(WALL_CLOCK_S - (time.time() - E["t0"]), 1)),+ "proprio": {"layout": PROPRIO_LAYOUT, "now": proprio_row().tolist()}, "done": E["done"], "reason": E["reason"],+ "cameras": {c: camera_info(c) for c in cams}}+ if S.kind == "joystick":+ out["command_now"] = dict(zip(("vx_mps", "vy_mps", "wz_radps"), S.command_now().round(4).tolist()))+ return out+++def do_submit(meta: dict, A: np.ndarray):+ typ = meta.get("type")+ if typ == "done":+ rec = recorder(cameras_of(meta), 5, meta)+ rec.tick(force=True, last=True) # every response carries the last frames+ E["calls"] += 1+ finish("done")+ return {**meta_common(cameras_of(meta)), "chunk_id": E["calls"], "type": typ, "executed_rows": 0, "ok": True}, rec.parts("none", 5)+ if typ != "joint_position":+ raise ValueError(f"type must be joint_position or done (not yet: {SPEC['action_types']['not_yet']})")+ dt = float(meta.get("dt", DT))+ interp = meta.get("interpolate", "linear")+ video = meta.get("video", "mp4")+ cams, fps = cameras_of(meta), video_fps(meta)+ k = dt / DT+ if A.ndim != 2 or A.shape[1] != Q.N:+ raise ValueError(f"joint_position actions must be (T, {Q.N}), got {list(A.shape)}")+ if not np.all(np.isfinite(A)):+ raise ValueError("actions contain NaN/inf")+ if not (math.isfinite(dt) and dt <= 0.5 + 1e-9 and round(k) >= 1 and abs(k - round(k)) < 1e-6):+ raise ValueError(f"dt must be a whole multiple of the {DT:g} s control period and at most 0.5 s; got {dt}")+ if A.shape[0] * dt > MAX_CHUNK_S + 1e-9:+ raise ValueError(f"chunk longer than max_chunk_s={MAX_CHUNK_S}: {A.shape[0]} rows x {dt} s")+ if interp not in ("hold", "linear"):+ raise ValueError("interpolate must be hold|linear")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, clipped = recorder(cams, fps, meta), []+ E["calls"] += 1+ step0, before = E["step"], ctrl_steps()+ rec.tick(force=True)+ prev = S.targets.copy()+ for ri, row in enumerate(A):+ E["step"] += 1+ target = np.clip(row, LIMITS[:, 0], LIMITS[:, 1])+ for j in np.flatnonzero(target != row)[:20]:+ clipped.append({"row": ri, "index": int(j), "reason": f"{S.joint_names[j]} limit [{LIMITS[j, 0]:g}, {LIMITS[j, 1]:g}]"})+ n = int(round(k))+ stop = False+ for s in range(1, n + 1):+ a = target if interp == "hold" else prev + (target - prev) * (s / n)+ if ctrl_step(a, rec):+ stop = True+ break+ prev = target+ if stop:+ break+ rec.tick(force=True, last=True)+ out = {**meta_common(cams), "chunk_id": E["calls"], "type": typ, "executed_rows": E["step"] - step0,+ "control_steps_chunk": ctrl_steps() - before, "physics_steps_chunk": (ctrl_steps() - before) * SUBSTEPS,+ "clipped": clipped[:200], "n_clipped": len(clipped), "plan": [], "ok": True}+ EP.log({"ev": "submit", "call": E["calls"], "rows": E["step"] - step0, "dt": dt, "interpolate": interp, "cameras": cams,+ "control_steps": ctrl_steps() - before, "n_clipped": len(clipped), "note": (meta.get("note") or "")[:500],+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video, fps)+++def do_observe(meta: dict):+ cams, fps = cameras_of(meta), video_fps(meta)+ seconds = float(meta.get("seconds", 0))+ video = meta.get("video", "frames")+ if not math.isfinite(seconds) or seconds < 0 or seconds > MAX_WATCH_S:+ raise ValueError(f"seconds must be in [0, {MAX_WATCH_S}]")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, before = recorder(cams, fps, meta), ctrl_steps()+ if seconds > 0 and not E["done"]:+ rec.tick(force=True)+ hold = S.targets.copy()+ for _ in range(int(round(seconds / DT))):+ if ctrl_step(hold, rec):+ break+ rec.tick(force=True, last=True)+ E["calls"] += 1+ out = {**meta_common(cams), "obs_id": E["calls"], "seconds": seconds, "control_steps_watch": ctrl_steps() - before,+ "physics_steps_watch": (ctrl_steps() - before) * SUBSTEPS, "ok": True}+ EP.log({"ev": "observe", "call": E["calls"], "seconds": seconds, "cameras": cams, "control_steps": ctrl_steps() - before,+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video if seconds > 0 else ("frames" if video == "mp4" else video), fps)+++def status() -> dict:+ return {"step": E["step"], "calls": E["calls"], "control_steps": ctrl_steps(), "done": E["done"], "reason": E["reason"],+ "elapsed_s": round(time.time() - E["t0"], 1)}+++def end_from_signal() -> None:+ """The collect hook's SIGUSR1: end the episode (the agent's time is over), dump it, exit so the replays can start."""+ with LOCK:+ E["exiting"] = True+ if not E["done"]:+ finish("timeout")+ EP.log({"ev": "exit", "reason": "collect hook: episode dumped"})+ if not os.path.exists(PID_FILE):+ open(PID_FILE, "w").write(str(os.getpid()))+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(0)+++def replay_row(row) -> None:+ """A journaled row during a resume."""+ S.step(row)+ ROWS.append(np.asarray(row, dtype=np.float64))+++EP.begin(state=E, step=replay_row, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, on_end=end_from_signal,+ start_event={"env": S.env, "seed": S.inst.get("seed"), "cameras": CAMS})+if E["done"]:+ dump() # resumed after the episode had ended: the record is rewritten from the replay+E["ready"] = True+write_final()+open(PID_FILE, "w").write(str(os.getpid()))+print(f"{L.PROTOCOL} MuJoCo Playground quadruped sim ready ({S.env}; startup {EP.n_startups}, resumes {EP.resumes})", flush=True)+L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics, status=status,+ on_submit_error=lambda exc: finish("error"), log=EP.log, episode=EP, state_sha=S.state_sha,+ proprio=proprio_row), port=int(os.environ.get("RCB_PORT", "8000")))diff --git a/tasks/mujoco_playground_go1_handstand-standard/instruction.md b/tasks/mujoco_playground_go1_handstand-standard/instruction.mdnew file mode 100644index 0000000000..d9ea8a1092--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/instruction.md@@ -0,0 +1,46 @@+# MuJoCo Playground · Go1Handstand — STANDARD MODE (robot as a service, eai-standard/2.2)++**Task:** Make the Unitree Go1 do a handstand: balance on its front legs, nose down, hind legs in the air, for 2 s.++You control the Unitree Go1 quadruped — **as if it were real hardware** — in one episode of MuJoCo Playground's+`Go1Handstand` environment (plain MuJoCo 3.3.7 with Playground's scene, commit 4057c14). The simulator runs in a service you+cannot open. You get one client and one episode.++## The episode+The robot starts standing at Playground's `home` pose with a random base velocity (Playground's reset). You have 500 control steps (10 s).++## Rules (real-robot rules)+- **No reset.** One episode. You see four cameras that follow the robot (RGB, depth if you ask) and the robot's own+ sensors: joint positions, velocities and torques, the IMU (gyro, accelerometer, gravity's direction, the trunk's+ velocity), foot contacts. No world positions, no success check.+- **The episode ends** the moment the pose has been held for 100 control steps in a row (success), when the robot meets the termination rule (the trunk's up axis below -0.25 (z component of the IMU frame's z axis), or any part of a front leg other than its foot (thigh, calf, hip) touching the floor: a failure), after 500 control steps (`spec["max_control_steps"]`), when you submit `done`, or when your time is up.+- **Success** is 100 control steps in a row (2 s) with the trunk's forward axis (the IMU frame's x axis) within 30 deg of straight down, the IMU at least 0.4 m above the floor, and the hind (RR, RL) feet off the ground, without a termination before; judged after every control step.+- Your wall-clock budget is 3600 s from your start. Simulated time only advances with your commands (and+ `get_obs(seconds=...)`, which holds the current targets).+- Nothing to hand in: the service records the episode and grades it. Leave your script at `/app/output/gen.py`.+- **If the service crashes**, a call fails with a connection error: it restarts and resumes the SAME episode (never a+ reset) in the state after the last call it completed. `r.wait_ready()` waits for it; then check `r.status()`.+- Nothing is put into your context automatically: images come back as arrays in Python objects.++## Client (`/opt/tools/rcb_client.py`)+```python+from rcb_client import Robot+r = Robot() # connects (waits while the service starts)+spec = r.spec() # action types, limits, cameras, robot_spec (home pose, gains), kinematics+obs = r.get_obs() # obs.last[cam] -> uint8 (240, 320, 3); obs.meta["proprio"] {"layout", "now"}+res = r.submit("joint_position", A, dt=0.02) # A: (T, 12) rows dt apart; res.proprio (one row per frame), res.meta+obs = r.get_obs(seconds=1.0, video="mp4") # hold the current targets and watch for 1 s (max 30)+r.fk(q); r.ik({"FR": [x, y, z, 1, 0, 0, 0]}, seed=q) # feet in the trunk frame <-> joints (no physics)+r.submit("done", []) # end the episode now+r.status() # calls, control steps, done, reason, elapsed time+```+Cameras: `track`, `side`, `back`, `top` (they follow the robot); `spec["cameras"]` gives each one's mounting and intrinsics, and every response carries its pose. Proprioception (`spec["proprio_groups"]`): `joint_pos`, `joint_vel`, `joint_effort` (12 each, action+order), `imu_gyro`, `imu_accelerometer`, `imu_gravity`, `imu_linvel` (3 each, IMU frame: x forward, y left, z up),+`foot_contact` (FR, FL, RR, RL).++### `joint_position` (12)+FR, FL, RR, RL legs, each hip (abduction), thigh (hip pitch), calf (knee): absolute targets of the joint position actuators (rad; kp = 35 N m/rad, joint damping 0.5 N m s/rad).+Rows are `dt` apart (a whole multiple of the 0.02 s control period, at most 0.5 s), `interpolate="linear"` (default) or+`"hold"` between rows; a chunk covers at most 10 s; values outside the limits+(`spec["action_types"]["joint_position"]["limits"]`) are clipped and listed in `res.meta["clipped"]`. Feedback control+means short chunks: each response tells you where the robot is now.diff --git a/tasks/mujoco_playground_go1_handstand-standard/solution/oracle.npy b/tasks/mujoco_playground_go1_handstand-standard/solution/oracle.npynew file mode 100644index 0000000000..92f939ea5bBinary files /dev/null and b/tasks/mujoco_playground_go1_handstand-standard/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_go1_handstand-standard/solution/oracle_replay.py b/tasks/mujoco_playground_go1_handstand-standard/solution/oracle_replay.pynew file mode 100644index 0000000000..b6a9824592--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/solution/oracle_replay.py@@ -0,0 +1,42 @@+"""Oracle (standard mode): streams the reference rows (one per 1/50 s control step, `hold`) as `joint_position` chunks+through the client, the same interface an agent has. Uses no privileged information at run time; the service's recorded+trajectory is then exactly the privileged reference. If the service crashes it resumes the same episode+(spec["on_service_error"]): the oracle waits until it answers again and goes on from the control step it reports."""+import os+import sys+import time++import numpy as np+import requests++sys.path.insert(0, "/opt/tools")+from rcb_client import EpisodeOver, Robot # noqa: E402++Q = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy")).astype(np.float64)+r = Robot()+spec = r.spec()+dt = 1.0 / float(spec["control_hz"])+per_chunk = max(1, int(spec.get("max_chunk_s", 10) / dt + 1e-9))+print("spec:", spec["protocol"], "rows:", len(Q), flush=True)+t0, i = time.time(), 0+while i < len(Q):+ chunk = Q[i:i + per_chunk]+ try:+ res = r.submit("joint_position", chunk, dt=dt, interpolate="hold", cameras=["track"], video="none", note=f"oracle rows {i}+")+ except EpisodeOver as e:+ print("episode over:", e)+ break+ except requests.exceptions.RequestException as e: # the service crashed: it restarts and resumes the same episode+ print("service unreachable:", repr(e)[:200], "- waiting for it to resume", flush=True)+ st = r.wait_ready()+ n = int(st["control_steps"])+ if not i <= n <= i + len(chunk):+ raise SystemExit(f"resumed at control step {n}: outside the chunk in flight (rows {i}..{i + len(chunk)})")+ i = n+ continue+ n = int(res.meta["control_steps"])+ print(f"rows {i}..{n}: clipped={res.meta['n_clipped']} done={res.meta['done']} reason={res.meta['reason']}", flush=True)+ if res.meta["done"] or n <= i:+ break+ i = n+print("status:", r.status(), "wall %.0fs" % (time.time() - t0))diff --git a/tasks/mujoco_playground_go1_handstand-standard/solution/solve.sh b/tasks/mujoco_playground_go1_handstand-standard/solution/solve.shnew file mode 100755index 0000000000..ecb1f6c954--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/solution/solve.sh@@ -0,0 +1,8 @@+#!/bin/bash+# Oracle (standard mode): streams the reference trajectory's joint targets (solution/oracle.npy, one row per control step)+# as `joint_position` chunks through the client. Uses no privileged information at run time (only the pre-recorded+# targets); the service's recorded trajectory is then exactly the privileged reference.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_go1_handstand-standard/task.toml b/tasks/mujoco_playground_go1_handstand-standard/task.tomlnew file mode 100644index 0000000000..1b44bbb662--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/task.toml@@ -0,0 +1,54 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = [+ { source = "/data/final.json", service = "sim" },+ { source = "/data/episode.jsonl", service = "sim" },+ { source = "/data/trajectory.npz", service = "sim" },+ { source = "/data/replay.mp4", service = "sim" },+ { source = "/data/server.log", service = "sim" }, # the service's own output (Harbor keeps none)+ { source = "/data/journal.f64", service = "sim" }, # crash recovery: every executed control step (float64 rows)+ { source = "/data/startups.jsonl", service = "sim" }, # crash recovery: one line per service start+ { source = "/data/replay1.log", service = "sim" }, # the collect hook's two fresh-process replays+ { source = "/data/replay2.log", service = "sim" },+ { source = "/data/replay3.log", service = "sim" }, # and its third, which renders replay.mp4+ "/app/output/",+]++[task]+name = "robot-coding-bench/mujoco_playground_go1_handstand-standard"+description = "STANDARD MODE (robot as a service, eai-standard/2.2): MuJoCo Playground Go1Handstand (Unitree Go1) on the same frozen instance as mujoco_playground_go1_handstand-privileged: Make the Unitree Go1 do a handstand: balance on its front legs, nose down, hind legs in the air, for 2 s. The agent only gets a client: four cameras that follow the robot (RGB, optional depth), the robot's joints and IMU, joint position chunks at 50 Hz, the feet's kinematics; one episode, no reset, no world state; the sim service records the episode, replays it in fresh processes and grades it."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "unitree-go1", "quadruped", "locomotion", "stand_on_two", "code-as-policy", "trajectory", "standard-mode"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "unitree-go1"+family = "mujoco_playground/Go1Handstand"+mode = "standard"+protocol = "eai-standard/2.2"+oracle = "full"+instance_seed = 0+expert_time_estimate_hours = 4.0++[verifier]+timeout_sec = 600.0+environment_mode = "separate"+network_mode = "no-network"++[[verifier.collect]]+service = "sim"+command = "sh /srv/finalize.sh" # end + dump + exit the service, replay twice in fresh processes, write final.json, video+timeout_sec = 1200++[agent]+timeout_sec = 3600.0+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_go1_handstand-standard/tests/Dockerfile b/tasks/mujoco_playground_go1_handstand-standard/tests/Dockerfilenew file mode 100644index 0000000000..26bc699ebe--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/tests/Dockerfile@@ -0,0 +1,5 @@+# Separate verifier sandbox: grades the sim service's own artifacts; needs nothing but python (the shared client base).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY test.sh /tests/test.sh+COPY grade.py /tests/grade.py+RUN chmod +x /tests/test.shdiff --git a/tasks/mujoco_playground_go1_handstand-standard/tests/grade.py b/tasks/mujoco_playground_go1_handstand-standard/tests/grade.pynew file mode 100644index 0000000000..5b990bf458--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/tests/grade.py@@ -0,0 +1,64 @@+"""Standard-mode verifier (MuJoCo Playground quadrupeds): reads what the sim service (which the agent could not touch) wrote:+/data/final.json (live success, two fresh-process replays of the recorded trajectory, determinism, crash-recovery+fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, the+replays having started in the instance's t = 0 state. Numeric-only reward.json."""++import json, os, shutil++LOG = "/logs/verifier"+os.makedirs(LOG, exist_ok=True)+++def write(ok, out):+ open(f"{LOG}/reward.txt", "w").write("1\n" if ok else "0\n")+ json.dump(out, open(f"{LOG}/reward.json", "w"))+ print(out)+++p = "/data/final.json"+if not os.path.exists(p):+ write(False, {"success": 0, "missing_log": 1, "grader_error": 0, "infra_error": 0})+ raise SystemExit+d = json.load(open(p))+for f in ("replay.mp4", "trajectory.npz", "episode.jsonl"):+ if os.path.exists(f"/data/{f}"):+ shutil.copy(f"/data/{f}", f"{LOG}/{f}")+ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic"))+ok = ok and not d.get("instance_mismatch")+num = lambda k: float(d.get(k) or 0) # noqa: E731+write(+ ok,+ {+ "success": int(ok),+ "live_success": int(bool(d.get("success"))),+ "replay_success": int(bool(d.get("replay_success"))),+ "deterministic": int(bool(d.get("deterministic"))),+ "live_matches_replay": int(bool(d.get("live_matches_replay"))),+ "finalized": int(bool(d.get("finalized"))),+ "n_actions": int(d.get("n_actions") or 0),+ "sim_steps": int(d.get("control_steps") or 0),+ "physics_steps": int(d.get("physics_steps") or 0),+ "steps": int(d.get("steps") or 0),+ "elapsed_s": float(d.get("elapsed_s") or 0),+ "video_rendered": int(bool(d.get("video"))),+ "fell": int(d.get("fell_at") is not None),+ "worst_lin_err": float(d["worst_lin_err"]) if d.get("worst_lin_err") is not None else -1.0,+ "worst_yaw_err": float(d["worst_yaw_err"]) if d.get("worst_yaw_err") is not None else -1.0,+ "end_tilt_deg": float(d["tilt_deg"]) if d.get("tilt_deg") is not None else -1.0,+ "end_imu_height": float(d["imu_height"]) if d.get("imu_height") is not None else -1.0,+ "end_pose_angle_deg": float(d["pose_angle_deg"]) if d.get("pose_angle_deg") is not None else -1.0,+ # a replay process gave no result, or the image no longer builds the frozen start: not the agent's 0+ "grader_error": int(bool(d.get("replay_failed") or d.get("instance_mismatch"))),+ "instance_mismatch": int(bool(d.get("instance_mismatch"))),+ # an infrastructure failure, not the agent's (PROTOCOL §2.6): a give-up after crashes between calls or a failed+ # resume (docs/STANDARD_MODE_2_2.md §13), the service not ending its episode for the collect hook, a replay+ # process that gave no result, replays that did not start in the instance's t = 0 state+ "infra_error": int(bool(d.get("infra_error"))),+ "gave_up": int(bool(d.get("gave_up"))),+ "sim_error": int(d.get("reason") == "error"),+ "sim_startups": int(d.get("sim_startups") or 0),+ "resumes": int(d.get("resumes") or 0),+ "resume_state_mismatch": int(d.get("resume_state_mismatch") or 0),+ "resume_max_joint_dev": num("resume_max_joint_dev"),+ },+)diff --git a/tasks/mujoco_playground_go1_handstand-standard/tests/test.sh b/tasks/mujoco_playground_go1_handstand-standard/tests/test.shnew file mode 100755index 0000000000..bc608aa8b9--- /dev/null+++ b/tasks/mujoco_playground_go1_handstand-standard/tests/test.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Verifier (separate sandbox): the sim sidecar's artifacts were uploaded to /data by Harbor.+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)+mkdir -p /logs/verifier+python /tests/grade.py 2> /logs/verifier/grade.logdiff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/README.md b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/README.mdnew file mode 100644index 0000000000..e46daca1fe--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/README.md@@ -0,0 +1,42 @@+# mujoco_playground_go1_joystick_flat_terrain-privileged++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | privileged |+| Twin | `mujoco_playground_go1_joystick_flat_terrain-standard` |+| Simulator / robot | `mujoco` / `unitree-go1` |+| Family / instance | `mujoco_playground/Go1JoystickFlatTerrain` / seed 0 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `Go1JoystickFlatTerrain` (Unitree Go1), rebuilt in plain MuJoCo from Playground's scene files: Make the Unitree Go1 follow the joystick command schedule on flat ground for the whole 20 s episode without falling over.+For 20 s the robot gets a joystick command schedule (4 segments: planar velocity and yaw rate in its own frame) and must track it without falling over. The deliverable is one replayable trajectory of joint position targets+(`/app/output/trajectory.npz`, `(T, 12)`, T = 1000 (the whole schedule)).++## Difficulty+Velocity tracking for 20 s: the agent has to make a 12-joint quadruped walk (a gait, not one motion) and steer it through the schedule's changes of speed, direction and turning rate, and an open-loop trajectory of 1000 steps only works if it is computed against the simulator. Torque limits and a soft PD drive leave little margin; Playground trains a neural policy with 200 M steps of PPO for this.++## Reference solution+MuJoCo Playground's own Go1 joystick policy (`experimental/sim2sim/onnx/go1_policy.onnx` @4057c14, not in the image) run closed loop on this instance with the observation of Playground's `play_go1_joystick.py`, its targets recorded (`scripts/mujoco-playground/oracle.py`): worst segment errors 0.073 m/s and 0.091 rad/s. Replayed by `solution/solve.sh` (`solution/oracle.npy`, 1000 rows); the rows are float32-exact, so the+standard twin's client executes the same targets. Re-verified by `scripts/mujoco-playground/select_instances.py`: two+fresh-process replays succeed and end in the same state.++## Verification+`tests/grade.py` in a separate sandbox without network: two replays, each in a fresh process, from the verifier's own+copy of the instance (`tests/instance.json`; the start state is checked against its hash on every load); pass iff both+succeed and end in the same state (`deterministic`). Oracle: success, worst segment errors 0.073 m/s and 0.091 rad/s. `nop`: no trajectory, reward 0.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml`; MuJoCo Menagerie @ 1b86ece (`unitree_go1`); simulated in MuJoCo 3.3.7 on the CPU |+| Instance | Playground's `reset` with `jax.random.PRNGKey(0)` and Playground's command process over the 1000 steps; chosen by `scripts/mujoco-playground/select_instances.py` (seed 0; the first candidate) |+| Actions | 12 joint position targets per control step (0.02 s of simulated time); kp = 35 N m/rad, joint damping 0.5 N m s/rad |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py` from `scripts/mujoco-playground/instances/Go1JoystickFlatTerrain.json`+(`make_instances.py`, `select_instances.py`) and `scripts/mujoco-playground/oracles/Go1JoystickFlatTerrain.npy` (`oracle.py`).diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/environment/Dockerfile b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/environment/Dockerfilenew file mode 100644index 0000000000..7bdd7d2938--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/environment/Dockerfile@@ -0,0 +1,8 @@+# MuJoCo Playground quadruped task (privileged): plain MuJoCo with Playground's and Menagerie's assets+# (images/mujoco/prepare_assets.sh), the task's tooling and its frozen instance.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY instance.json /app/instance.json+COPY rcb_quadruped.py /opt/tools/rcb_quadruped.py+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/environment/instance.json b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/environment/instance.jsonnew file mode 100644index 0000000000..20aecf51c1--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/environment/instance.json@@ -0,0 +1,93 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1JoystickFlatTerrain",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ -0.49270617961883545,+ -0.4791088104248047,+ 0.27799999713897705,+ 0.32240399718284607,+ 0.0,+ 0.0,+ -0.9466021656990051,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842+ ],+ "qvel0": [+ -0.4173961877822876,+ 0.2807871103286743,+ 0.4382798671722412,+ 0.4672558307647705,+ -0.3059135675430298,+ -0.2901715040206909,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 1.4129691123962402,+ "vy": -0.611178994178772,+ "wz": 0.7116400003433228+ },+ {+ "start_step": 42,+ "vx": -0.2525142431259155,+ "vy": -0.611178994178772,+ "wz": 0.7116400003433228+ },+ {+ "start_step": 238,+ "vx": -0.2525142431259155,+ "vy": -0.611178994178772,+ "wz": 0.0+ },+ {+ "start_step": 298,+ "vx": -0.552196741104126,+ "vy": -0.611178994178772,+ "wz": 0.0+ }+ ],+ "text": "Make the Unitree Go1 follow the joystick command schedule on flat ground for the whole 20 s episode without falling over.",+ "facts": {+ "start_xy_m": [+ -0.493,+ -0.479+ ],+ "start_yaw_deg": -142.4,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.272,+ "reference_rows": 1000,+ "reference_worst_lin_err": 0.0732,+ "reference_worst_yaw_err": 0.0914+ },+ "state_sha": "086e8c16c213",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/environment/rcb_quadruped.py b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/environment/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/environment/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/instruction.md b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/instruction.mdnew file mode 100644index 0000000000..8c764c44e5--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/instruction.md@@ -0,0 +1,62 @@+# MuJoCo Playground · Go1JoystickFlatTerrain — frozen episode++**Task:** Make the Unitree Go1 follow the joystick command schedule on flat ground for the whole 20 s episode without falling over.++You control the Unitree Go1 quadruped in one episode of MuJoCo Playground's `Go1JoystickFlatTerrain` environment, rebuilt in plain+MuJoCo 3.3.7 from Playground's own scene files (Apache-2.0, commit 4057c14) and the robot from MuJoCo Menagerie. The+episode is frozen: it starts the same way after every reset (Playground's `reset` with seed 0), and you may reset+as often as you like. Your deliverable is **one open-loop trajectory**, not a general policy.++## The episode+The robot starts at Playground's `home` pose, its base moved to (-0.493, -0.479) m and turned to a yaw of -142.4 deg, with a random base velocity (Playground's reset). The ground is flat.+For 20 s (1000 control steps) it is given this command schedule, drawn by Playground's command process (a new draw after Exp(1) x 5 s; a draw may keep a component). A command is a velocity in the robot's own frame: vx forward, vy to the left (the trunk's planar velocity), and the yaw rate:++| from (s) | vx (m/s) | vy (m/s) | yaw rate (rad/s) |+|---:|---:|---:|---:|+| 0.00 | +1.413 | -0.611 | +0.712 |+| 0.84 | -0.253 | -0.611 | +0.712 |+| 4.76 | -0.253 | -0.611 | +0.000 |+| 5.96 | -0.552 | -0.611 | +0.000 |++`s.commands` holds the schedule per control step; `s.state()["command"]` is the current one.++## Success+The episode lasts exactly 1000 control steps: the trajectory must have T = 1000 rows. Success iff+1. the robot never meets Playground's termination rule for this environment: the trunk's up axis pointing below the horizon (the z component of the IMU frame's z axis negative); and+2. in every command segment, over its control steps after the first 25 (0.5 s): the mean planar velocity error |v_xy - cmd_xy| is at most 0.2 m/s, with v the IMU's velocimeter (`local_linvel`, trunk frame), and the mean yaw-rate error |w_z - cmd_wz| at most 0.3 rad/s, with w the IMU's gyro.++`s.check()` reports `fell_at`, each segment's errors and `success`.++## Deliverable+`/app/output/trajectory.npz` with `actions`: float64 (T, 12), one row per control step (0.02 s): absolute targets of+the 12 joint position actuators, in `s.joint_names` order (FR, FL, RR, RL legs, each hip (abduction), thigh (hip pitch), calf (knee)), in radians; T = 1000 (the whole schedule). Values+outside the actuator ranges (`s.lower`, `s.upper`) are clipped. `s.save_trajectory(rows)` writes it. Also leave the+script that produced it at `/app/output/gen.py`. Save a working trajectory as soon as you have one and overwrite it as+you improve it: whatever is in `/app/output/` when your 3600 s are up is graded. The tooling logs your sessions and+resets (cost accounting, not graded).++## Tooling (installed; `python` from any directory)+```python+from rcb_quadruped import Session+s = Session("/app/instance.json") # the frozen episode at t = 0 (checked against the instance's state hash)+s.joint_names; s.lower; s.upper # the actuator order and ranges (rad)+s.home # Playground's standing pose (its `home` keyframe), in that order+s.step(row) # one control step: 12 joint targets, 5 physics steps of 0.004 s; returns s.check()+s.check() # the task's check on the steps so far (see Success)+s.state() # qpos, qvel, IMU (local_linvel, gyro, gravity, accelerometer, pose), feet, contacts, command+s.sensor(name); s.gravity() # one MuJoCo sensor; gravity's direction in the IMU frame+s.model, s.data # the live MuJoCo model and data (read them; changing them is not part of the replay)+s.render(cam); s.cameras # uint8 (240, 320, 3) from cameras that follow the robot: `track`, `side`, `back`, `top` (they follow the robot)+s.reset() # back to t = 0+s.replay(rows) # reset, run the rows, return the check and the final state's hash+s.render_video(rows, "/app/output/try.mp4")+s.save_trajectory(rows, "/app/output/trajectory.npz")+```+The grader runs exactly this CLI in two fresh processes, so run it to check yourself:+`python /opt/tools/rcb_quadruped.py replay --instance /app/instance.json --traj /app/output/trajectory.npz`++## Conventions+- Joint position actuators (PD): kp = 35 N m/rad, joint damping 0.5 N m s/rad, as Playground's environment sets them; the physics step is 0.004 s,+ the control step 0.02 s (5 physics steps); a row holds until the next one.+- World frame z up, metres; quaternions **wxyz**. The IMU frame is the trunk's: x forward, y left, z up.+- Physics is MuJoCo on the CPU: the same rows from the same start give the same result in every fresh process.diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/solution/oracle.npy b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/solution/oracle.npynew file mode 100644index 0000000000..0e3688d4fbBinary files /dev/null and b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/solution/oracle_replay.py b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/solution/oracle_replay.pynew file mode 100644index 0000000000..46987df1d0--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/solution/oracle_replay.py@@ -0,0 +1,15 @@+"""Oracle (privileged): replay the reference rows in the tooling, check them, and save them as the deliverable."""+import json+import os+import sys++import numpy as np++sys.path.insert(0, "/opt/tools")+from rcb_quadruped import Session # noqa: E402++rows = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy"))+s = Session("/app/instance.json")+r = s.replay(rows)+s.save_trajectory(rows, "/app/output/trajectory.npz", meta={"source": "reference trajectory (solution/oracle.npy)"})+print(json.dumps({k: v for k, v in r.items() if k != "segments"}))diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/solution/solve.sh b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/solution/solve.shnew file mode 100755index 0000000000..430ffb6017--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/solution/solve.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Oracle (privileged): write the reference trajectory frozen at generation time (solution/oracle.npy; how it was made:+# scripts/mujoco-playground/oracle.py) as the deliverable.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/task.toml b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/task.tomlnew file mode 100644index 0000000000..b9bc583893--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/task.toml@@ -0,0 +1,43 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = ["/app/output/", "/logs/agent/rcb/"]++[task]+name = "robot-coding-bench/mujoco_playground_go1_joystick_flat_terrain-privileged"+description = "MuJoCo Playground Go1JoystickFlatTerrain in plain MuJoCo (Unitree Go1, joint position control every 0.02 s): Make the Unitree Go1 follow the joystick command schedule on flat ground for the whole 20 s episode without falling over. Produce one replayable trajectory of joint position targets on a frozen instance (Playground's reset with seed 0); graded by velocity tracking over the whole 20 s schedule without a fall (two fresh-process replays)."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "unitree-go1", "quadruped", "locomotion", "joystick", "code-as-policy", "trajectory", "privileged"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "unitree-go1"+family = "mujoco_playground/Go1JoystickFlatTerrain"+mode = "privileged"+oracle = "full"+instance_seed = 0 # the PRNGKey of Playground's reset (and, for the joystick tasks, its command process)+expert_time_estimate_hours = 3.0++[verifier]+timeout_sec = 1200.0+environment_mode = "separate"+network_mode = "no-network"++[verifier.environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192++[agent]+timeout_sec = 3600.0+# MuJoCo Playground's trained policies are public upstream, so the agent reaches the model APIs and nothing else+# (scripts/set_agent_egress.py HOSTS).+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/tests/Dockerfile b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/tests/Dockerfilenew file mode 100644index 0000000000..f49c79154d--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/tests/Dockerfile@@ -0,0 +1,7 @@+# Separate verifier sandbox (PROTOCOL §4): the same image with the verifier's own copies of the tooling and the frozen+# instance. Nothing the agent did in its container reaches this one: Harbor uploads only the declared artifacts.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY grade.py instance.json rcb_quadruped.py test.sh /tests/+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier+ENV PYTHONPATH=/tests+WORKDIR /testsdiff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/tests/grade.py b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/tests/grade.pynew file mode 100644index 0000000000..e5668de85f--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/tests/grade.py@@ -0,0 +1,126 @@+"""Verifier (privileged): replay /app/output/trajectory.npz from the frozen instance and write Harbor's rewards.++ python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz++Two replays, each in its own fresh process (`rcb_quadruped.py replay`: the frozen start, one control step per row, the+task's success check on the whole trajectory). success = both replays succeed and end in the same state. Writes+/logs/verifier/reward.txt (1/0) and reward.json (numbers only); then a third replay renders replay.mp4, after the+verdict is on disk (it never changes it).+"""+import argparse+import json+import os+import subprocess+import sys+import tempfile+import traceback++import numpy as np++LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")+TOOL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_quadruped.py")+REPLAY_TIMEOUT_S = 300 # a 1000-step replay takes a few seconds; the video replay renders 4 views every 2nd step+++def write(ok: bool, out: dict) -> None:+ os.makedirs(LOG_DIR, exist_ok=True)+ open(os.path.join(LOG_DIR, "reward.txt"), "w").write("1\n" if ok else "0\n")+ json.dump(out, open(os.path.join(LOG_DIR, "reward.json"), "w"))+ print(json.dumps(out), flush=True)+++def agent_cost() -> dict:+ """Self-reported cost from the tooling's log in the agent's container (accounting, not evidence)."""+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_replays": 0, "agent_cost_self_reported": 1}+ for path in ("/logs/agent/rcb/rcb_session_log.jsonl", "/app/output/rcb_session_log.jsonl"):+ if not os.path.exists(path):+ continue+ try:+ with open(path) as f:+ for i, line in enumerate(f):+ if i > 200_000 or len(line) > 10_000:+ break+ try:+ e = json.loads(line)+ ev = e.get("ev") if isinstance(e, dict) else None+ if ev == "session_start":+ cost["agent_sessions"] += 1+ elif ev == "reset":+ cost["agent_resets"] += 1+ elif ev == "replay":+ cost["agent_replays"] += 1+ elif ev == "session_end":+ cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)+ except Exception: # noqa: BLE001 -- one bad line must not sink the verdict+ continue+ except OSError:+ pass+ break+ return cost+++def replay(instance: str, traj: str, video: str | None) -> dict:+ """One replay in a fresh process; its result (`--out`), or {"error": ...}."""+ with tempfile.NamedTemporaryFile(suffix=".json") as out:+ cmd = [sys.executable, TOOL, "replay", "--instance", instance, "--traj", traj, "--out", out.name]+ try:+ p = subprocess.run(cmd + (["--video", video] if video else []), stdout=subprocess.DEVNULL, stderr=sys.stderr,+ timeout=REPLAY_TIMEOUT_S, env={**os.environ, "RCB_SESSION_LOG": "", "RCB_AGENT_TRACE_DIR": ""})+ except subprocess.TimeoutExpired:+ return {"error": f"replay took over {REPLAY_TIMEOUT_S} s"}+ try:+ return json.load(open(out.name))+ except ValueError:+ return {"error": f"replay process rc={p.returncode}"}+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--instance", required=True)+ ap.add_argument("--traj", default="/app/output/trajectory.npz")+ a = ap.parse_args()+ cost = agent_cost()+ if not os.path.isfile(a.traj):+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost})+ return 0+ try:+ horizon = int(json.load(open(a.instance))["horizon"])+ d = np.load(a.traj, allow_pickle=False)+ acts = np.asarray(d["actions"], dtype=np.float64) if "actions" in d.files else np.zeros((0, 0))+ if acts.ndim != 2 or acts.shape[1] != 12 or len(acts) > horizon or not np.all(np.isfinite(acts)):+ write(False, {"success": 0, "bad_trajectory": 1, "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0,+ "grader_error": 0, **cost})+ return 0+ runs = [replay(a.instance, a.traj, None), replay(a.instance, a.traj, None)]+ if any("error" in r and not r.get("bad_trajectory") for r in runs):+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ if not all(r.get("instance_ok") for r in runs): # the image no longer builds the frozen start: not the agent's 0+ write(False, {"success": 0, "grader_error": 1, "instance_mismatch": 1, **cost})+ return 0+ all_success = all(bool(r.get("success")) for r in runs)+ deterministic = runs[0].get("state_sha") == runs[1].get("state_sha")+ ok = all_success and deterministic+ r = runs[0]+ num = lambda k: float(r.get(k) if r.get(k) is not None else -1) # noqa: E731+ out = {"success": int(ok), "replay_success": int(all_success), "deterministic": int(deterministic),+ "n_actions": int(len(acts)), "horizon": horizon, "fell": int(r.get("fell_at") is not None),+ "fell_at_step": num("fell_at"), "worst_lin_err": num("worst_lin_err"), "worst_yaw_err": num("worst_yaw_err"),+ "end_tilt_deg": num("tilt_deg"), "end_imu_height": num("imu_height"), "end_pose_angle_deg": num("pose_angle_deg"),+ "grader_error": 0,+ "video_rendered": 0, **cost}+ write(ok, out) # the verdict, before any video+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ try: # the video, for humans: it never changes the verdict+ if replay(a.instance, a.traj, os.path.join(LOG_DIR, "replay.mp4")).get("video"):+ write(ok, {**out, "video_rendered": 1})+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/tests/instance.json b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/tests/instance.jsonnew file mode 100644index 0000000000..20aecf51c1--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/tests/instance.json@@ -0,0 +1,93 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1JoystickFlatTerrain",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ -0.49270617961883545,+ -0.4791088104248047,+ 0.27799999713897705,+ 0.32240399718284607,+ 0.0,+ 0.0,+ -0.9466021656990051,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842+ ],+ "qvel0": [+ -0.4173961877822876,+ 0.2807871103286743,+ 0.4382798671722412,+ 0.4672558307647705,+ -0.3059135675430298,+ -0.2901715040206909,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 1.4129691123962402,+ "vy": -0.611178994178772,+ "wz": 0.7116400003433228+ },+ {+ "start_step": 42,+ "vx": -0.2525142431259155,+ "vy": -0.611178994178772,+ "wz": 0.7116400003433228+ },+ {+ "start_step": 238,+ "vx": -0.2525142431259155,+ "vy": -0.611178994178772,+ "wz": 0.0+ },+ {+ "start_step": 298,+ "vx": -0.552196741104126,+ "vy": -0.611178994178772,+ "wz": 0.0+ }+ ],+ "text": "Make the Unitree Go1 follow the joystick command schedule on flat ground for the whole 20 s episode without falling over.",+ "facts": {+ "start_xy_m": [+ -0.493,+ -0.479+ ],+ "start_yaw_deg": -142.4,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.272,+ "reference_rows": 1000,+ "reference_worst_lin_err": 0.0732,+ "reference_worst_yaw_err": 0.0914+ },+ "state_sha": "086e8c16c213",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/tests/rcb_quadruped.py b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/tests/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/tests/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/tests/test.sh b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/tests/test.shnew file mode 100755index 0000000000..1c3d2f767b--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-privileged/tests/test.sh@@ -0,0 +1,9 @@+#!/bin/bash+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in two fresh processes (the+# verdict), then a third that renders replay.mp4.+# Writes /logs/verifier/reward.txt (1/0) and reward.json (numeric fields, docs/PROTOCOL.md §2.6).+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/*+mkdir -p /logs/verifier+python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz 2> /logs/verifier/grade.logdiff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/README.md b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/README.mdnew file mode 100644index 0000000000..8a31856a36--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/README.md@@ -0,0 +1,44 @@+# mujoco_playground_go1_joystick_flat_terrain-standard++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | standard (`eai-standard/2.2`) |+| Twin | `mujoco_playground_go1_joystick_flat_terrain-privileged` |+| Simulator / robot | `mujoco` / `unitree-go1` |+| Family / instance | `mujoco_playground/Go1JoystickFlatTerrain` / seed 0 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `Go1JoystickFlatTerrain` (Unitree Go1) on the same frozen instance as `mujoco_playground_go1_joystick_flat_terrain-privileged`: Make the Unitree Go1 follow the joystick command schedule on flat ground for the whole 20 s episode without falling over.+For 20 s the robot gets a joystick command schedule (4 segments: planar velocity and yaw rate in its own frame) and must track it without falling over. Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with only+the robot's own sensors and four cameras that follow it.++## Difficulty+Same instance and success check as `mujoco_playground_go1_joystick_flat_terrain-privileged`. In standard mode the agent loses resets, the simulator and+the world state: it sees camera images and proprioception (joints, IMU, foot contacts), acts in joint position chunks,+and gets one episode, so it has to close the loop on the robot's own sensors and recover from its own mistakes without+starting over.++## Reference solution+`solution/oracle_replay.py` streams the privileged reference's rows (`solution/oracle.npy`, 1000 rows, float32-exact)+through the client in `hold` chunks; it uses no privileged information at run time. The service's recorded trajectory+is then exactly the privileged reference, and the episode ends after the 1000 steps of the schedule, with success.++## Verification+The sim service judges the episode live and records every executed control step; the collect hook+(`environment/sim/finalize.sh`) ends the service, replays the recorded trajectory in two fresh processes and writes+`final.json`; `tests/grade.py` (separate sandbox, no network) passes iff the live check succeeded, both replays succeed,+and they end in the same state. Oracle: success, worst segment errors 0.073 m/s and 0.091 rad/s.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml`; MuJoCo Menagerie @ 1b86ece (`unitree_go1`); MuJoCo 3.3.7 on the CPU |+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); cameras `track`, `side`, `back`, `top` (they follow the robot) (320 x 240), the feet's kinematics in the trunk frame |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py`, as its privileged twin.diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/Dockerfile b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/Dockerfilenew file mode 100644index 0000000000..ed5eee3703--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/Dockerfile@@ -0,0 +1,9 @@+# Standard mode: the agent container has NO simulator and no Playground code, only Python and the client, on the shared+# pinned client base with the shared pins (scripts/eai_standard/client.env, client-requirements.txt).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY client-requirements.txt /tmp/client-requirements.txt+RUN pip install --no-cache-dir -r /tmp/client-requirements.txt+COPY rcb_client.py rcb1.py /opt/tools/+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/client-requirements.txt b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/client-requirements.txtnew file mode 100644index 0000000000..8aa73a968f--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/client-requirements.txt@@ -0,0 +1,11 @@+# Exact pins for what the standard agent container installs (and a verifier, if it installs anything): the closure of+# `pip install requests numpy pillow scipy`, the unpinned line of every standard task at 9eb18edf, resolved on+# 2026-10-01 in CLIENT_IMAGE (client.env: Python 3.12.14, pip 25.0.1). A change here is a shared-files PR.+certifi==2026.7.22+charset-normalizer==3.5.2+idna==3.20+numpy==2.5.3+pillow==12.3.0+requests==2.34.2+scipy==1.18.1+urllib3==2.8.0diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/docker-compose.yaml b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/docker-compose.yamlnew file mode 100644index 0000000000..8ec63c582e--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/docker-compose.yaml@@ -0,0 +1,23 @@+# Standard mode: the simulator runs in the `sim` sidecar (the agent cannot open it); the agent only reaches port 8000.+# No `expose`/`ports` on sim: under Harbor's egress control it shares main's network namespace (localhost:8000).+# CPU only: MuJoCo physics and rendering (EGL when a GPU is there, else OSMesa); no GPU reservation.+# Crash recovery (docs/STANDARD_MODE_2_2.md §13): run.sh exits non-zero when the service crashes, compose restarts the+# container (same container, same /data) and the service replays its journal into the same episode, never a reset.+services:+ main:+ depends_on: [sim]+ sim:+ image: ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+ volumes:+ - ./sim:/srv:ro+ working_dir: /tmp+ command: sh /srv/run.sh+ restart: on-failure:6 # N >= 3 (PROTOCOL §4.1); a resume continues the episode+ environment:+ RCB_INSTANCE: /srv/instance.json+ RCB_TOOL: /srv/rcb_quadruped.py+ RCB_DATA: /data+ RCB_WALL_CLOCK_S: "3600"+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in about a second+ PYTHONPATH: /srv+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction logdiff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/rcb1.py b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/rcb_client.py b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/rcb_client.pynew file mode 100644index 0000000000..aa25b0e050--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/rcb_client.py@@ -0,0 +1,211 @@+"""eai-standard/2.2 client (formerly rcb-limited/2.x) — the only thing a standard-mode agent gets (installed at+/opt/tools/rcb_client.py).++ from rcb_client import Robot+ r = Robot() # finds the service (sim:8000, then localhost:8000), waits for warm-up+ spec = r.spec() # actions, cameras (+ intrinsics, mounting), robot_spec, world, budget, kinematics+ obs = r.get_obs() # current frames: obs.last[cam] -> uint8 (H,W,3); obs.meta["proprio"]+ obs = r.get_obs(depth=True) # + obs.last_depth[cam] -> float32 (H,W) z-depth in metres, 0 = no reading+ res = r.submit("joint_position", A, dt=0.1) # A: (T, dim) rows dt apart; returns the execution video+ res = r.submit("ee_pose", P) # (T, dim) end-effector targets (see spec()["action_types"])+ res.video[cam] -> mp4 bytes res.frames[cam] -> uint8 (N,H,W,3) if video="frames"/"both" res.last[cam]+ res.proprio -> float32 (N, D), one row per frame (names: spec()["proprio_layout"]; res.group("tcp_pose"))+ res.frame_step -> int64 (N,) control step of each frame res.frame_time_s -> float64 (N,) simulated time+ res.extrinsic_cv[cam] -> float64 (N,3,4) world->camera per frame (res.meta["cameras"]: intrinsics + the last frame's pose)+ res = r.submit(..., depth="frames") # + res.depth[cam] -> float32 (N,H,W) metres, one per frame (1 mm steps)+ r.fk(q) # {"ok", "poses": {frame: [x,y,z, quaternion]}}: forward kinematics, no physics+ r.ik({frame: pose}, seed=q) # {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}: inverse kinematics+ res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, frames/<cam>/NNN.jpg, proprio.npy, depth, frame_meta.npz+ obs = r.get_obs(seconds=3, video="both") # hold the last command, let physics run 3 s, return the video+ r.status() # calls, control steps, done, reason, elapsed time++Nothing is put into your context automatically: what you look at, and where you store it, is your code's decision.++If a call fails with a connection error or a 5xx, the service may have crashed; it restarts and resumes the SAME episode+(never a reset) in the state after the last call it completed, which you may not have received. r.wait_ready() waits+until it answers again (resuming replays the episode so far: long episodes can take minutes); then check r.status()+before you continue (spec()["on_service_error"]).+"""+from __future__ import annotations+import json, os, pathlib, sys, time, zlib+import numpy as np+import requests+import rcb1++PROTOCOL = "eai-standard/2.2" # also talks to 2.0 / 2.1 services (they ignore depth and send no frame metadata)+ACCEPTED = ("eai-standard/2.", "rcb-limited/2.") # every 2.x service, under the protocol's current and former name+++class EpisodeOver(RuntimeError):+ pass+++def _decode_depth_frames(p: dict) -> np.ndarray:+ a = np.frombuffer(zlib.decompress(p["data"]), dtype="<u2").reshape(p["shape"])+ return a.astype(np.float32) / 1000.0+++class Result:+ """Decoded RCB1 response: meta (dict), video (cam -> mp4 bytes), frames (cam -> uint8 (N,H,W,3)), last (cam -> uint8+ (H,W,3)), last_depth (cam -> float32 (H,W) m), depth (cam -> float32 (N,H,W) m, one per frame), proprio (float32 (N,D)),+ frame_step (int64 (N,)), frame_time_s (float64 (N,)), extrinsic_cv (cam -> float64 (N,3,4)). save(dir) writes it out;+ show(cam, k) returns one frame; group(name) the proprio columns of one spec()["proprio_groups"] group. stopped: None,+ or why the service stopped the call early ("max_call_wall_s": it ran longer than spec()["max_call_wall_s"]); then+ meta["executed_rows"] < the rows sent, and meta["proprio"]["now"] is where the robot is."""+ def __init__(self, meta: dict, parts: dict, spec: dict | None = None):+ self.meta = meta; self.raw = parts; self._spec = spec or {}; self.stopped = meta.get("stopped")+ self.video, self.frames, self.last, self.last_depth, self.depth, self.extrinsic_cv = {}, {}, {}, {}, {}, {}+ self.proprio = None; self.frame_step = None; self.frame_time_s = None+ for name, p in parts.items():+ kind, data = p["kind"], p["data"]+ if name.startswith("video/") and kind == "mp4": self.video[name[6:]] = data+ elif name.startswith("frames/") and kind == "array": self.frames[name[7:]] = data+ elif name.startswith("last/") and kind == "array": self.last[name[5:]] = data+ elif name.startswith("last_depth/") and kind == "array": self.last_depth[name[11:]] = np.asarray(data, dtype=np.float32)+ elif name.startswith("depth_frames/") and p.get("codec") == "zlib": self.depth[name[13:]] = _decode_depth_frames(p)+ elif name.startswith("depth/") and kind == "array": self.depth[name[6:]] = np.asarray(data, dtype=np.float32) # 2.1 form+ elif name.startswith("extrinsic_cv/") and kind == "array": self.extrinsic_cv[name[13:]] = data+ elif name == "proprio": self.proprio = data+ elif name == "frame_step": self.frame_step = data+ elif name == "frame_time_s": self.frame_time_s = data++ @property+ def done(self) -> bool: return bool(self.meta.get("done"))++ def show(self, camera: str, k: int = -1) -> np.ndarray:+ if camera in self.frames: return self.frames[camera][k]+ return self.last[camera]++ def group(self, name: str, now: bool = False) -> np.ndarray:+ """Columns of proprio group `name` (spec()["proprio_groups"]): (N, n) over the frames, or (n,) of meta["proprio"]["now"]."""+ first, n = self._spec["proprio_groups"][name][:2]+ if now: return np.asarray(self.meta["proprio"]["now"], dtype=np.float64)[first:first + n]+ return self.proprio[:, first:first + n]++ def save(self, out_dir: str) -> str:+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ (out / "meta.json").write_text(json.dumps(self.meta, indent=1))+ for cam, b in self.video.items(): (out / f"{cam}.mp4").write_bytes(b)+ try:+ from PIL import Image+ for cam, img in self.last.items():+ (out / "last").mkdir(exist_ok=True); Image.fromarray(np.ascontiguousarray(img)).save(out / "last" / f"{cam}.jpg", quality=90)+ for cam, arr in self.frames.items():+ d = out / "frames" / cam; d.mkdir(parents=True, exist_ok=True)+ for i, f in enumerate(arr): Image.fromarray(np.ascontiguousarray(f)).save(d / f"{i:03d}.jpg", quality=85)+ except ImportError:+ for cam, img in self.last.items(): np.save(out / f"last_{cam}.npy", img)+ for cam, arr in self.frames.items(): np.save(out / f"frames_{cam}.npy", arr)+ for cam, arr in self.last_depth.items(): np.save(out / f"last_depth_{cam}.npy", arr)+ for cam, arr in self.depth.items(): np.savez_compressed(out / f"depth_{cam}.npz", depth_mm=np.rint(arr * 1000).astype(np.uint16))+ if self.proprio is not None: np.save(out / "proprio.npy", self.proprio)+ if self.frame_step is not None:+ np.savez(out / "frame_meta.npz", frame_step=self.frame_step, frame_time_s=self.frame_time_s,+ **{f"extrinsic_cv/{c}": e for c, e in self.extrinsic_cv.items()})+ return str(out)+++class Robot:+ def __init__(self, base: str | None = None, timeout: float = 600.0):+ cands = [base or os.environ.get("SIM_URL"), "http://sim:8000", "http://localhost:8000"]+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ for b in [c for c in cands if c]:+ try:+ r = requests.get(b + "/spec", timeout=(5, 30))+ if r.status_code == 503: last = "warming up"; break+ r.raise_for_status(); self.base = b; self._spec = r.json()+ if not str(self._spec.get("protocol", "")).startswith(ACCEPTED):+ raise RuntimeError(f"not a 2.x service: protocol {self._spec.get('protocol')!r}")+ return+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(2)+ raise RuntimeError(f"sim service unavailable: {last}")++ def spec(self) -> dict:+ return self._spec++ def _post(self, path: str, meta: dict, parts: list, timeout: float) -> Result:+ body = rcb1.encode(meta, parts)+ r = requests.post(self.base + path, data=body, headers={"Content-Type": "application/x-rcb1"}, timeout=(5, timeout))+ if r.status_code == 409:+ raise EpisodeOver(r.json().get("reason") if r.headers.get("Content-Type", "").startswith("application/json") else "episode finished")+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ m, p = rcb1.decode(r.content); return Result(m, p, self._spec)++ def _common(self, cameras, video_fps, depth, include_depth) -> dict:+ cams = list(cameras) if cameras is not None else self._spec.get("default_cameras")+ if depth is None or depth is False: depth = "frames" if include_depth else "none"+ elif depth is True: depth = "last"+ m = {"cameras": cams, "video_fps": None if video_fps is None else int(video_fps), "depth": depth}+ return {k: v for k, v in m.items() if v is not None}++ def submit(self, action_type: str, actions, dt: float | None = None, interpolate: str = "linear", cameras=None,+ video_fps: int | None = None, video: str = "mp4", depth=None, include_depth: bool = False, note: str = "") -> Result:+ """Execute a chunk of low-level actions (T, dim); see spec()['action_types'] for dims, layouts, limits and semantics.+ dt defaults to one control period, cameras to spec()['default_cameras']; depth: None | True (= "last") | "frames"."""+ a = np.asarray(actions, dtype=np.float32)+ if a.ndim == 1: a = a[None, :]+ if dt is None and self._spec.get("control_hz"): dt = 1.0 / float(self._spec["control_hz"])+ meta = {"type": action_type, "interpolate": interpolate, "video": video, "note": note,+ **({} if dt is None else {"dt": float(dt)}), **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/submit", meta, [rcb1.array_part("actions", a)], timeout=1800)+ if res.stopped:+ print(f"[rcb_client] the service stopped this call early ({res.stopped}): {res.meta.get('executed_rows')} of {len(a)} rows "+ "executed; meta['proprio']['now'] is where the robot is", file=sys.stderr)+ return res++ def get_obs(self, cameras=None, seconds: float = 0.0, video_fps: int | None = None, depth=None, include_depth: bool = False,+ video: str = "frames") -> Result:+ """Current frames (seconds=0, free) or hold the last command and watch for `seconds` (returns the video).+ depth: None | True (= "last": the last frame's depth) | "frames" (one depth map per frame)."""+ meta = {"seconds": float(seconds), "video": video, **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/observe", meta, [], timeout=600)+ if res.stopped:+ print(f"[rcb_client] the service stopped this watch early ({res.stopped}) after {res.meta.get('control_steps_watch')} control "+ "steps", file=sys.stderr)+ return res++ def status(self) -> dict:+ r = requests.get(self.base + "/status", timeout=(5, 60)); r.raise_for_status(); return r.json()++ def wait_ready(self, timeout: float = 3600.0) -> dict:+ """After a connection error: wait until the service answers GET /status again (it resumes the same episode after a+ crash), then return the status. Raises RuntimeError after `timeout` seconds."""+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ try:+ return self.status()+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(5)+ raise RuntimeError(f"sim service did not come back within {timeout:.0f} s: {last}")++ def kinematics(self, body: dict) -> dict:+ """POST /kinematics (stateless: never moves the robot, never advances time). Raises ValueError on a bad request."""+ r = requests.post(self.base + "/kinematics", json=body, timeout=(5, 120))+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ return r.json()++ def fk(self, q, links=None, base_pose=None) -> dict:+ """Forward kinematics: q in spec()['kinematics']['joint_names'] order -> {"ok", "frame", "poses": {link: [x,y,z, quat]}}+ (quaternion order spec()['world']['quaternion_order']; a mobile robot answers in its base frame unless base_pose is given)."""+ body = {"op": "fk", "q": [float(v) for v in np.asarray(q).reshape(-1)]}+ if links is not None: body["links"] = list(links)+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)++ def ik(self, targets: dict, seed=None, base_pose=None, **opts) -> dict:+ """Inverse kinematics: {frame: [x,y,z, quat]} (frames from spec()['kinematics']['ik_targets']) and an optional seed q ->+ {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}. opts: tol_pos_m, tol_rot_rad, max_iters."""+ body = {"op": "ik", "targets": {k: [float(v) for v in p] for k, p in targets.items()}, **opts}+ if seed is not None: body["seed"] = [float(v) for v in np.asarray(seed).reshape(-1)]+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/finalize.sh b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/finalize.shnew file mode 100755index 0000000000..02048ddc74--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/finalize.sh@@ -0,0 +1,80 @@+#!/bin/sh+# [[verifier.collect]] hook, run inside the `sim` sidecar once Harbor has stopped the agent's container.+# 1. `rcb_limited.py end` (docs/STANDARD_MODE_2_2.md §13.3): SIGUSR1 to the service, which ends the episode if the+# agent had not (reason "timeout"), writes trajectory.npz + episode.json (live verdict, final-state hash) and exits.+# It exits 2 when final.json already holds the verdict (the service gave up after crashes): that verdict stays.+# 2. replay the trajectory from the frozen instance in TWO fresh processes (`rcb_quadruped.py replay`, the privileged+# verifier's replay): determinism = fresh process == fresh process; live_matches_replay = live == replay.+# 3. merge everything into final.json, the only thing the verifier sandbox grades;+# 4. a third replay renders replay.mp4, after the verdict is on disk (it never changes it).+set -u+DATA="${RCB_DATA:-/data}"; TOOL="${RCB_TOOL:?}"; INSTANCE="${RCB_INSTANCE:?}"+python /srv/rcb_limited.py end "$DATA" --timeout "${RCB_COLLECT_END_TIMEOUT_S:-900}"; rc=$?+if [ "$rc" = 2 ]; then+ echo "[finalize] final.json already holds the verdict; no replay"; exit 0+fi+if [ "$rc" != 0 ]; then+ echo "[finalize] the service did not end and dump the episode in time (rc $rc): an infrastructure failure"+ python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data"); p = os.path.join(d, "final.json")+try:+ out = json.load(open(p))+except Exception:+ out = {}+out.update({"finalized": True, "success": False, "replay_success": False, "deterministic": False, "infra_error": 1,+ "error": "collect hook: the sim service did not end and dump the episode in time"})+json.dump(out, open(p, "w"))+print(json.dumps(out))+PY+ exit 0+fi+replay() { # <n> [--video FILE]: one replay in a fresh process, its result in $DATA/replay<n>.json+ n=$1; shift+ RCB_SESSION_LOG= python "$TOOL" replay --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --out "$DATA/replay$n.json" \+ "$@" > /dev/null 2> "$DATA/replay$n.log"+ echo "[finalize] replay $n exit $?"+}+echo "[finalize] episode dumped; replaying twice in fresh processes"+rm -f "$DATA/replay1.json" "$DATA/replay2.json" "$DATA/replay3.json"+replay 1+replay 2+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+def result(name):+ try:+ v = json.load(open(os.path.join(d, name)))+ except (OSError, ValueError):+ return {}+ return v if isinstance(v, dict) else {}+out = {"replay_success": False, "deterministic": False, "video": False}+try:+ out.update(json.load(open(os.path.join(d, "episode.json"))))+except Exception as exc:+ out["error"] = f"no episode.json: {exc!r}"+a, b = result("replay1.json"), result("replay2.json")+out["replay_success"] = bool(a.get("success")) and bool(b.get("success"))+out["replay_sha"], out["replay_sha2"] = a.get("state_sha"), b.get("state_sha")+out["deterministic"] = bool(a.get("state_sha")) and a.get("state_sha") == b.get("state_sha")+out["live_matches_replay"] = bool(a.get("state_sha")) and a.get("state_sha") == out.get("live_sha")+if not (a.get("state_sha") and b.get("state_sha")): # a replay process died (it crashed or timed out): not the agent's 0+ out.update({"replay_failed": 1, "infra_error": 1,+ "error": "a replay process gave no result (replay1.log / replay2.log)"})+elif not (a.get("instance_ok") and b.get("instance_ok")): # the image no longer builds the frozen start: not the agent's 0+ out.update({"instance_mismatch": 1, "infra_error": 1, "error": "a replay did not start in the instance's t = 0 state"})+out["finalized"] = True+json.dump(out, open(os.path.join(d, "final.json"), "w"))+print(json.dumps(out))+PY+replay 3 --video "$DATA/replay.mp4"+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+try:+ shown = json.load(open(os.path.join(d, "replay3.json"))).get("video")+except (OSError, ValueError):+ shown = False+if shown:+ p = os.path.join(d, "final.json"); out = json.load(open(p)); out["video"] = True; json.dump(out, open(p, "w"))+PYdiff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/instance.json b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/instance.jsonnew file mode 100644index 0000000000..20aecf51c1--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/instance.json@@ -0,0 +1,93 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1JoystickFlatTerrain",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ -0.49270617961883545,+ -0.4791088104248047,+ 0.27799999713897705,+ 0.32240399718284607,+ 0.0,+ 0.0,+ -0.9466021656990051,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842+ ],+ "qvel0": [+ -0.4173961877822876,+ 0.2807871103286743,+ 0.4382798671722412,+ 0.4672558307647705,+ -0.3059135675430298,+ -0.2901715040206909,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 1.4129691123962402,+ "vy": -0.611178994178772,+ "wz": 0.7116400003433228+ },+ {+ "start_step": 42,+ "vx": -0.2525142431259155,+ "vy": -0.611178994178772,+ "wz": 0.7116400003433228+ },+ {+ "start_step": 238,+ "vx": -0.2525142431259155,+ "vy": -0.611178994178772,+ "wz": 0.0+ },+ {+ "start_step": 298,+ "vx": -0.552196741104126,+ "vy": -0.611178994178772,+ "wz": 0.0+ }+ ],+ "text": "Make the Unitree Go1 follow the joystick command schedule on flat ground for the whole 20 s episode without falling over.",+ "facts": {+ "start_xy_m": [+ -0.493,+ -0.479+ ],+ "start_yaw_deg": -142.4,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.272,+ "reference_rows": 1000,+ "reference_worst_lin_err": 0.0732,+ "reference_worst_yaw_err": 0.0914+ },+ "state_sha": "086e8c16c213",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/rcb1.py b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/rcb_limited.py b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/rcb_limited.pynew file mode 100644index 0000000000..1ce1171787--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/rcb_limited.py@@ -0,0 +1,930 @@+"""eai-standard/2.2 (formerly rcb-limited/2.2): the HTTP layer, the protocol helpers and the crash recovery that every+2.2 sim service shares (docs/STANDARD_MODE_2_2.md; the 2.1 base is docs/LIMITED_MODE_PROTOCOL.md).++The source is scripts/eai_standard/rcb_limited.py; the generators copy it unchanged into every standard task's+environment/sim/ (ci_checks/check-tooling-identity.sh). A service keeps its simulator to itself (scene, action+execution, cameras, kinematic model) and hands this module plain callables:++ import rcb_limited as L+ EP = L.Episode(DATA, dim=N, resume="exact") # before the scene is built; "approx" for a nondeterministic simulator+ EP.startup() # start count, back-off after failed starts, startup watchdog+ S = <build the scene>; EP.scene_built() # the watchdog stands down+ def ctrl_step(a, rec): # every executed control step+ S.step(a); stop = EP.journal(a); rec.tick(); return E["done"] or stop+ rec = L.Recorder(cams, every, grab, proprio_row, extrinsics, clock, depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+ rec.tick(force=True) # first frame (before the chunk / watch)+ ...; rec.tick(); ... # after every control step: a frame every `every` steps+ rec.tick(force=True, last=True) # last frame (+ its depth)+ parts = rec.parts(video, fps) # RCB1 parts: video/ frames/ last/ extrinsic_cv/ last_depth/ depth_frames/ depth/ proprio frame_*+ S.record_start()+ EP.begin(state=E, step=S.step, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, start_event={...}, on_end=end_fn)+ L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics,+ status=status, on_submit_error=lambda exc: finish("error"), log=EP.log,+ episode=EP, state_sha=S.state_sha, proprio=proprio_row))++ grab(cams, want_depth) -> ({cam: uint8 (H,W,3)}, {cam: float32 (H,W) z-depth in metres, 0 = no reading})+ extrinsics(cams) -> {cam: (3,4) world -> camera, OpenCV axes (x right, y down, z forward)}+ proprio_row() -> float32 (len(spec["proprio_layout"]),)+ clock() -> int, control steps since the episode start (the frame's step index)+ do_kinematics(req) -> dict; `req` is parse_kinematics(body, spec["kinematics"]); it must never step physics++None of the callables may step physics. check_spec(SPEC) runs in serve(): a service whose /spec misses a 2.2 field, or+carries a field the protocol forbids (segmentation, object identities or sizes, physical parameters), does not start.+Crash recovery (class Episode; PROTOCOL §4.7): every executed control step is journaled, every completed call+checkpointed (rows, state hash, the robot's proprio row); after a crash compose restarts the container and the service+replays the journal and continues the SAME episode, never a reset. `python rcb_limited.py end <data dir>` is the shared+first half of a collect hook."""+from __future__ import annotations+import faulthandler, json, math, os, re, select, signal, socket, sys, tempfile, threading, time, traceback, zlib+from http.server import BaseHTTPRequestHandler, HTTPServer+from typing import Any, Callable++import numpy as np++import rcb1++PROTOCOL = "eai-standard/2.2"+COMPAT = ["rcb-limited/2.0", "rcb-limited/2.1", "eai-standard/2.1"] # requests written for these are served unchanged+MAX_BODY = 64 * 1024 * 1024+MAX_RESP = 256 * 1024 * 1024+DEPTH_MODES = ("none", "last", "frames")+DEPTH_MAX_M = 65.535 # uint16 millimetres; a farther surface reads 0 (no reading)+DEPTH_NOISE = os.environ.get("RCB_DEPTH_NOISE", "off").strip().lower() # off | realsense (as rcb-limited/2.1)+_RNG = np.random.default_rng(int(os.environ.get("RCB_DEPTH_NOISE_SEED", "0")))+PROPRIO_GROUPS_REQUIRED = ("joint_pos", "joint_vel", "gripper_opening", "tcp_pose", "joint_effort")+PART_PREFIXES = ("video/", "frames/", "last/", "last_depth/", "depth_frames/", "depth/", "extrinsic_cv/")+PART_NAMES = ("proprio", "frame_step", "frame_time_s")+++# ---------------------------------------------------------------- depth+def depth_mode(meta: dict) -> str:+ """The request's depth mode: "none" | "last" | "frames" (2.2 field `depth`), or "legacy" for a 2.0/2.1 request that+ sets `include_depth: true` and no `depth` (answered as 2.1 did: `depth/<cam>` float16 (N,H,W) metres)."""+ d = meta.get("depth")+ if d is None or d is False:+ return "legacy" if meta.get("include_depth") is True else "none"+ if d is True:+ return "last"+ if isinstance(d, str) and d in DEPTH_MODES:+ return d+ raise ValueError(f"depth must be one of {'|'.join(DEPTH_MODES)} (got {d!r})")+++def clean_depth(z) -> np.ndarray:+ """float32 z-depth in metres: non-finite, negative and beyond-range pixels read 0 (no reading); the optional+ RCB_DEPTH_NOISE=realsense model (sigma = 2 mm + 2.5 mm * z^2, 1 % dropouts) is applied here, after rendering, so it+ never touches physics."""+ z = np.asarray(z, dtype=np.float32).copy()+ if z.ndim == 3 and z.shape[-1] == 1:+ z = z[..., 0]+ bad = ~np.isfinite(z) | (z <= 0) | (z > DEPTH_MAX_M)+ z[bad] = 0.0+ if DEPTH_NOISE == "realsense":+ valid = z > 0+ z = z + _RNG.normal(0.0, 1.0, z.shape).astype(np.float32) * (0.002 + 0.0025 * z * z)+ z[_RNG.random(z.shape) < 0.01] = 0.0+ z[~valid] = 0.0+ z[(z < 0) | (z > DEPTH_MAX_M)] = 0.0+ return z.astype(np.float32)+++def depth_frames_part(name: str, stack: np.ndarray) -> tuple[str, str, bytes, dict]:+ """(N,H,W) metres -> an RCB1 "bytes" part: zlib of C-order uint16 millimetres (0 = no reading). Clients that do not+ know it keep the raw bytes and ignore it; rcb_client decodes it back to float32 metres."""+ mm = np.rint(np.asarray(stack, dtype=np.float64) * 1000.0)+ mm[(mm < 0) | (mm > 65535)] = 0+ a = np.ascontiguousarray(mm.astype("<u2"))+ return (name, "bytes", zlib.compress(a.tobytes(), 1), {"codec": "zlib", "dtype": "uint16", "shape": list(a.shape), "unit": "mm"})+++def encode_mp4(frames: np.ndarray, fps: int) -> bytes:+ """H.264 mp4 (yuv420p, faststart) of uint8 (N,H,W,3) frames: the same encoding every 2.0 service used."""+ import imageio.v2 as imageio+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tf:+ path = tf.name+ try:+ with imageio.get_writer(path, format="FFMPEG", mode="I", fps=fps, codec="libx264", macro_block_size=1,+ output_params=["-movflags", "+faststart", "-pix_fmt", "yuv420p"]) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ return open(path, "rb").read()+ finally:+ try:+ os.unlink(path)+ except OSError:+ pass+++# ---------------------------------------------------------------- recording what the cameras see during one call+class Recorder:+ """Frames of the requested cameras every `every` clock ticks, plus forced first/last frames; for every frame the+ proprio row, the clock (step index), each camera's extrinsics and, if asked, its depth. All arrays share one frame+ axis N: frames/<cam>, the mp4's frames, proprio, frame_step, frame_time_s, extrinsic_cv/<cam>, depth_frames/<cam>."""++ def __init__(self, cameras, every: int, grab: Callable, proprio_row: Callable, extrinsics: Callable, clock: Callable,+ depth: str = "none", clock_hz: float = 1.0):+ if depth not in DEPTH_MODES + ("legacy",):+ raise ValueError(f"bad depth mode {depth!r}")+ self.cams = list(cameras); self.every = max(1, int(every)); self.mode = depth; self.hz = float(clock_hz)+ self._grab, self._prop, self._ext, self._clock = grab, proprio_row, extrinsics, clock+ self.frames: dict = {c: [] for c in self.cams}; self.depth: dict = {c: [] for c in self.cams}+ self.ext: dict = {c: [] for c in self.cams}; self.last_depth: dict = {}+ self.prop: list = []; self.steps: list = []; self.n = 0; self.missing = 0++ def tick(self, force: bool = False, last: bool = False) -> None:+ if force or last or self.n % self.every == 0:+ self._capture(last)+ self.n += 1++ def _capture(self, last: bool) -> None:+ want = self.mode in ("frames", "legacy") or (last and self.mode == "last")+ rgb, dep = self._grab(self.cams, want)+ ext = self._ext(self.cams)+ for c in self.cams:+ img = rgb.get(c)+ if img is not None:+ img = np.ascontiguousarray(np.asarray(img)[..., :3].astype(np.uint8))+ else: # a camera that failed to render: a black frame (sized in parts()) keeps one frame axis+ self.missing += 1+ self.frames[c].append(img)+ e = ext.get(c)+ self.ext[c].append(np.full((3, 4), np.nan) if e is None else np.asarray(e, dtype=np.float64).reshape(3, 4))+ if want:+ d = dep.get(c)+ if d is None:+ d = np.zeros(img.shape[:2] if img is not None else (1, 1), np.float32)+ else:+ d = clean_depth(d)+ if img is not None and d.shape != img.shape[:2]:+ raise RuntimeError(f"depth of {c} is {d.shape}, its RGB {img.shape[:2]}: they must be pixel-aligned")+ if self.mode in ("frames", "legacy"):+ self.depth[c].append(d)+ if last or self.mode == "frames":+ self.last_depth[c] = d+ self.prop.append(np.asarray(self._prop(), dtype=np.float32).reshape(-1))+ self.steps.append(int(self._clock()))++ def parts(self, video: str, fps: int) -> list:+ if self.mode == "last" and not self.last_depth and self.prop: # no last=True tick: the state has not moved since+ _, dep = self._grab(self.cams, True)+ self.last_depth = {c: clean_depth(dep[c]) for c in self.cams if c in dep}+ out = []+ for c in self.cams:+ good = [f for f in self.frames[c] if f is not None]+ hw = good[-1].shape[:2] if good else (1, 1)+ if len(good) < len(self.frames[c]):+ self.frames[c] = [f if f is not None else np.zeros(hw + (3,), np.uint8) for f in self.frames[c]]+ self.depth[c] = [d if d.shape == hw else np.zeros(hw, np.float32) for d in self.depth[c]]+ if c in self.last_depth and self.last_depth[c].shape != hw:+ self.last_depth[c] = np.zeros(hw, np.float32)+ fr = np.stack(self.frames[c]) if self.frames[c] else np.zeros((0, 1, 1, 3), np.uint8)+ if video in ("mp4", "both") and len(fr):+ out.append((f"video/{c}", "mp4", encode_mp4(fr, fps), {"fps": fps, "n": int(len(fr))}))+ if video in ("frames", "both"):+ out.append(rcb1.array_part(f"frames/{c}", fr))+ if len(fr):+ out.append(rcb1.array_part(f"last/{c}", fr[-1]))+ out.append(rcb1.array_part(f"extrinsic_cv/{c}", np.stack(self.ext[c]) if self.ext[c] else np.zeros((0, 3, 4))))+ if self.mode in ("last", "frames") and c in self.last_depth:+ out.append(rcb1.array_part(f"last_depth/{c}", self.last_depth[c]))+ if self.mode == "frames" and self.depth[c]:+ out.append(depth_frames_part(f"depth_frames/{c}", np.stack(self.depth[c])))+ if self.mode == "legacy" and self.depth[c]:+ out.append(rcb1.array_part(f"depth/{c}", np.stack(self.depth[c]).astype(np.float16)))+ out.append(rcb1.array_part("proprio", np.stack(self.prop) if self.prop else np.zeros((0, 0), np.float32)))+ st = np.asarray(self.steps, dtype=np.int64)+ out.append(rcb1.array_part("frame_step", st))+ out.append(rcb1.array_part("frame_time_s", st.astype(np.float64) / self.hz))+ return out+++def encode_response(meta: dict, parts: list, max_bytes: int = MAX_RESP) -> bytes:+ """The RCB1 body; over `max_bytes` the per-frame depth goes first, then the raw frames (mp4, last frames, last+ depth, proprio and the per-frame arrays always stay), and meta["degraded"] says what was dropped."""+ body = rcb1.encode(meta, parts)+ dropped = []+ for prefixes in (("depth_frames/", "depth/"), ("frames/",)):+ if len(body) <= max_bytes:+ break+ keep = [p for p in parts if not p[0].startswith(prefixes)]+ if len(keep) < len(parts):+ parts = keep; dropped += [x.rstrip("/") for x in prefixes]+ body = rcb1.encode({**meta, "degraded": f"response over {max_bytes} bytes: {', '.join(dropped)} dropped"}, parts)+ return body+++# ---------------------------------------------------------------- kinematics+def _vec(x, n: int, what: str) -> list:+ a = np.asarray(x, dtype=np.float64).reshape(-1) if x is not None else None+ if a is None or a.size != n or not np.all(np.isfinite(a)):+ raise ValueError(f"{what} must be {n} finite numbers")+ return a.tolist()+++def _pose(x, what: str) -> list:+ p = _vec(x, 7, what)+ nq = math.sqrt(sum(v * v for v in p[3:]))+ if nq < 1e-6:+ raise ValueError(f"{what}: quaternion has zero norm")+ return p[:3] + [v / nq for v in p[3:]]+++def parse_kinematics(body: dict, kin: dict) -> dict:+ """Validate a /kinematics request against spec["kinematics"] (ValueError -> 400). Returns+ {"op": "fk", "q", "links", "base_pose"} or {"op": "ik", "targets": {frame: pose7}, "seed", "base_pose", "tol_pos_m",+ "tol_rot_rad", "max_iters"}; poses are x y z + a unit quaternion in the spec's order; q follows kin["joint_names"]."""+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object")+ op = body.get("op"); n = len(kin["joint_names"])+ base = None+ if body.get("base_pose") is not None:+ if kin.get("frame") != "base":+ raise ValueError("base_pose is only accepted by a mobile robot (spec kinematics.frame == 'base')")+ base = _pose(body["base_pose"], "base_pose")+ if op == "fk":+ links = body.get("links") or list(kin["links"])+ if not isinstance(links, list) or any(l not in kin["links"] for l in links):+ raise ValueError(f"links must be a list of names from spec kinematics.links: {kin['links']}")+ return {"op": "fk", "q": _vec(body.get("q"), n, "q"), "links": links, "base_pose": base}+ if op == "ik":+ tg = body.get("targets")+ if not isinstance(tg, dict) or not tg or any(k not in kin["ik_targets"] for k in tg):+ raise ValueError(f"targets must map frames from spec kinematics.ik_targets {kin['ik_targets']} to poses")+ ik = kin.get("ik", {})+ seed = None if body.get("seed") is None else _vec(body["seed"], n, "seed")+ tol_p = float(body.get("tol_pos_m", ik.get("tol_pos_m", 0.005)))+ tol_r = float(body.get("tol_rot_rad", ik.get("tol_rot_rad", 0.05)))+ it = int(body.get("max_iters", ik.get("max_iters", 200)))+ if not (1e-5 <= tol_p <= 0.5 and 1e-4 <= tol_r <= 3.2 and 1 <= it <= 5000):+ raise ValueError("tol_pos_m in [1e-5, 0.5], tol_rot_rad in [1e-4, 3.2], max_iters in [1, 5000]")+ return {"op": "ik", "targets": {k: _pose(v, f"targets[{k}]") for k, v in tg.items()}, "seed": seed, "base_pose": base,+ "tol_pos_m": tol_p, "tol_rot_rad": tol_r, "max_iters": it}+ raise ValueError("op must be 'fk' or 'ik'")+++def fk_response(poses: dict, frame: str) -> dict:+ return {"ok": True, "op": "fk", "frame": frame, "poses": {k: [float(v) for v in np.asarray(p, dtype=np.float64).reshape(7)] for k, p in poses.items()}}+++def ik_response(q, ok: bool, errors: dict, frame: str, note: str | None = None) -> dict:+ """errors: {frame: (position error m, rotation error rad)} of the returned q (None / non-finite -> null: no solution)."""+ fin = lambda v: float(v) if v is not None and math.isfinite(float(v)) else None # noqa: E731+ out = {"ok": bool(ok), "op": "ik", "frame": frame, "q": None if q is None else [float(v) for v in np.asarray(q).reshape(-1)],+ "error": {k: {"pos_m": fin(e[0]), "rot_rad": fin(e[1])} for k, e in errors.items()}}+ if note:+ out["note"] = note+ return out+++def quat_angle(q1, q2) -> float:+ """Rotation angle (rad) between two unit quaternions of the same order."""+ d = abs(float(np.dot(np.asarray(q1, dtype=np.float64), np.asarray(q2, dtype=np.float64))))+ return 2.0 * math.acos(min(1.0, d))+++# ---------------------------------------------------------------- /spec self-check+FORBIDDEN_KEY = re.compile(r"mask|segment|semantic(?!s$)|instance_?id|bbox|bounding|categor|object|\bobj_|label|mass|friction|"+ r"restitution|inertia|density|damping|stiffness", re.I)+GAIN_PATHS = ("robot_spec.controller",) # joint drive gains (stiffness, damping) are the robot's own, and allowed there+POSITION_KEY = re.compile(r"(?:^|_)(?:pos|position|positions|pose|poses|origin|location|coords?|coordinates|world|translation)(?:_|$)|"+ r"(?:^|_)cent(?:er|re)s?(?:_|$)|(?:^|_)xyz?$|(?:^|_)(?:top|surface|floor|table|plane|height|elevation)?_?z$", re.I)+WORLD_TEXT = re.compile(r"\bworld\s+[xyz]\s*=", re.I)+COORDS = re.compile(r"\(\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*(?:,\s*-?\d+(?:\.\d+)?\s*)?\)")+++def world_text(s: str) -> bool:+ """A text that gives a world coordinate: a pixel-to-world formula, or a coordinate tuple with a decimal point that is+ not the robot's own pose ("robot base at (0, 0, 1.08)" stays)."""+ return bool(WORLD_TEXT.search(s)) or any("." in m.group(0) and not re.search(r"base|robot|origin", s[max(0, m.start() - 40):m.start()], re.I)+ for m in COORDS.finditer(s))+CONVENTIONS = {"static.floor_z": 0.0} # BEHAVIOR: the floor is the plane z = 0 (the world frame's definition)+++def static_positions(obj: Any, path: str = "static") -> list[str]:+ """Paths in /spec static that say WHERE something is (keys naming positions, heights, centres; texts with world+ coordinates). Names, inventories, sizes and colours may stay in static; positions never (docs § Never provided)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}"+ if POSITION_KEY.search(str(k)) and CONVENTIONS.get(p, object()) != v:+ out.append(p)+ else:+ out += static_positions(v, p)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += static_positions(v, f"{path}[{i}]")+ elif isinstance(obj, str) and world_text(obj):+ out.append(path)+ return out+++SPEC_REQUIRED = ("protocol", "protocol_compat", "simulator", "robot", "task_text", "control_hz", "cameras", "default_cameras",+ "action_types", "proprio_layout", "proprio_groups", "static", "world", "budget", "robot_spec", "kinematics", "depth")+++def forbidden_keys(obj: Any, path: str = "", skip: tuple = ()) -> list[str]:+ """Key paths that name something the protocol never provides (key paths in `skip` are not searched)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}" if path else str(k)+ if p in skip:+ continue+ if FORBIDDEN_KEY.search(str(k)) and not (re.search(r"damping|stiffness", str(k), re.I) and p.startswith(GAIN_PATHS)):+ out.append(p)+ out += forbidden_keys(v, p, skip)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += forbidden_keys(v, f"{path}[{i}]", skip)+ return out+++def check_spec(spec: dict) -> None:+ """Raise if /spec is not a complete 2.2 spec or names anything forbidden (run at startup, before binding :8000)."""+ miss = [k for k in SPEC_REQUIRED if k not in spec]+ if miss:+ raise RuntimeError(f"/spec misses {miss}")+ if spec["protocol"] != PROTOCOL:+ raise RuntimeError(f"/spec protocol {spec['protocol']!r} != {PROTOCOL}")+ bad = forbidden_keys(spec, skip=())+ if bad:+ raise RuntimeError(f"/spec names forbidden fields: {bad}")+ pos = static_positions(spec["static"])+ if pos:+ raise RuntimeError(f"/spec static says where things are (never provided): {pos}")+ lay = spec["proprio_layout"]+ if len(set(lay)) != len(lay):+ raise RuntimeError("proprio_layout names are not unique")+ for g in PROPRIO_GROUPS_REQUIRED:+ if g not in spec["proprio_groups"]:+ raise RuntimeError(f"proprio_groups misses {g}")+ for g, (first, n, _meaning) in spec["proprio_groups"].items():+ if not (0 <= first and first + n <= len(lay)):+ raise RuntimeError(f"proprio group {g} [{first}, +{n}) outside the {len(lay)} columns")+ kin = spec["kinematics"]+ for k in ("endpoint", "joint_names", "frame", "quaternion_order", "links", "tcp_frames", "ee_frames", "ik_targets"):+ if k not in kin:+ raise RuntimeError(f"kinematics misses {k}")+ if any(j not in lay for j in kin["joint_names"]):+ raise RuntimeError("kinematics.joint_names must be proprio_layout columns (the measured joint positions)")+ if any(f not in kin["links"] for f in list(kin["tcp_frames"]) + list(kin["ee_frames"]) + list(kin["ik_targets"])):+ raise RuntimeError("kinematics tcp_frames / ee_frames / ik_targets must be listed in kinematics.links")+ if spec["proprio_groups"]["tcp_pose"][1] != 7 * len(kin["tcp_frames"]):+ raise RuntimeError("proprio group tcp_pose must hold 7 columns per kinematics.tcp_frames entry")+ for c, cam in spec["cameras"].items():+ for k in ("rgb", "depth", "mounted", "resolution", "intrinsic_cv", "mount"):+ if k not in cam:+ raise RuntimeError(f"cameras.{c} misses {k}")+ if cam["mount"].get("type") not in ("static", "link"):+ raise RuntimeError(f"cameras.{c}.mount.type must be static|link")+ if any(c not in spec["cameras"] for c in spec["default_cameras"]):+ raise RuntimeError("default_cameras must be cameras")+++# ---------------------------------------------------------------- crash recovery (PROTOCOL §4.7; docs/STANDARD_MODE_2_2.md)+MAX_RESUMES = int(os.environ.get("RCB_MAX_RESUMES", "2"))+STARTUP_TIMEOUT_S = float(os.environ.get("RCB_STARTUP_TIMEOUT_S", "900")) # a task with a slower scene build sets more+MAX_CALL_WALL_S = float(os.environ.get("RCB_MAX_CALL_WALL_S", "900")) # < the client's 1800 s /submit read timeout+RESUME_MAX_DEV_M = float(os.environ.get("RCB_RESUME_MAX_DEV_M", "0.05")) # approx resumes: the gross-divergence guard+ON_SERVICE_ERROR = ("a connection error means the service crashed: it restarts and resumes the SAME episode (never a reset) "+ "in the state after the last call it completed, which you may not have received. Wait until GET /status "+ "answers again (rcb_client: Robot.wait_ready(); resuming replays the episode so far, which can take "+ "minutes in a long episode, and the wall clock keeps running), then check calls and control_steps "+ "before you continue. A 500 means the simulator failed: the episode is over (reason \"error\"). A call "+ "that runs longer than max_call_wall_s seconds stops at the next control step and returns what it "+ "executed (meta.stopped, executed_rows).")+++def _jsonable(v: Any) -> Any:+ if isinstance(v, np.ndarray):+ return v.tolist()+ if isinstance(v, (np.floating, np.integer, np.bool_)):+ return v.item()+ if isinstance(v, (list, tuple)):+ return [_jsonable(x) for x in v]+ if isinstance(v, dict):+ return {str(k): _jsonable(x) for k, x in v.items()}+ return v+++def _peer_closed(sock) -> bool:+ """True when the client of an HTTP request has closed its connection (it gave up on the call): the socket reads as+ end-of-file. A client never sends anything while it waits for the response, so readable means closed."""+ try:+ r, _, _ = select.select([sock], [], [], 0)+ return bool(r) and sock.recv(1, socket.MSG_PEEK) == b""+ except (OSError, ValueError):+ return True+++def _read_json(path: str) -> dict:+ try:+ with open(path) as f:+ d = json.load(f)+ return d if isinstance(d, dict) else {}+ except (OSError, ValueError):+ return {}+++def _write_json(path: str, obj: dict) -> None:+ tmp = f"{path}.{os.getpid()}.tmp"+ with open(tmp, "w") as f:+ json.dump(obj, f)+ os.replace(tmp, path)+++def final_verdict(data: str) -> dict | None:+ """final.json if it already holds a verdict that nothing may overwrite: the grading result (finalized, with+ `deterministic`) or the end of an episode the service gave up after crashes (`gave_up`)."""+ fin = _read_json(os.path.join(data, "final.json"))+ if fin.get("finalized") and (fin.get("gave_up") or fin.get("deterministic") is not None):+ return fin+ return None+++class Episode:+ """Crash-safe episode bookkeeping, the same rules as the RoboTwin and MuJoCo services (PROTOCOL §4.7):++ - startup(): before the scene is built. One line in startups.jsonl; a back-off of min(120, 20 (n - 1)) s when the+ earlier starts never began an episode (they crashed while building, e.g. GPU memory taken by other trials); the+ startup watchdog (faulthandler, a C thread: it fires even when a native scene build holds the GIL) dumps every+ thread's traceback and exits 1 after RCB_STARTUP_TIMEOUT_S, so compose restarts the build. Until begin() a SIGUSR1+ (the collect hook's "the agent phase is over") is only remembered.+ - journal(row): every executed control step (the exact row given to the simulator's step) goes to journal.f64.+ - checkpoint(): after every completed call (the HTTP layer calls it): the journal is flushed, then the call's+ checkpoint is logged in episode.jsonl (rows, control steps, state hash, the robot's proprio row, `persist` keys).+ - begin(): a fresh episode, or after a crash (run.sh exits non-zero, compose restarts the container, `restart:+ on-failure:N`) the SAME episode resumed: the journal is replayed up to the last checkpoint, the journal truncated+ there (the call that was in flight is lost as a whole: its caller got an error, not a result), the state hash+ compared, the service's counters restored; the wall clock keeps running from the first start.+ - Resume check, by the simulator's determinism class: `exact` (bit-exact in a fresh process): the hash must match,+ else the episode ends `resume_failed` (infra_error). `approx` (a simulator declared nondeterministic): a+ mismatch is recorded (resume_state_mismatch, and the robot's deviation from its checkpointed proprio: joint_pos and+ tcp_pose) and the episode continues, unless a TCP is more than RCB_RESUME_MAX_DEV_M from where it was+ (resume_failed, infra_error). The verdict never comes from the live state but from fresh replays of the complete+ recorded trajectory, so continuing cannot raise a score.+ - More than RCB_MAX_RESUMES crashes end the episode: `sim_crashed_on_call` if every crash happened while a call was+ being served (the agent's failure), else `sim_crashed` (infra_error = 1). A verdict already on disk is never+ overwritten; the service then idles with its PID file for the collect hook.+ - Per call, two bounds keep one call from holding the single-threaded service: a call that runs longer than+ max_call_wall_s, or whose client has hung up, stops at the next control step and returns what it executed+ (journal() returns True; meta.stopped says why). Neither bounds the episode: the wall clock is its only budget."""++ def __init__(self, data: str, dim: int, resume: str = "exact", persist: tuple = ()):+ if resume not in ("exact", "approx"):+ raise ValueError("resume must be 'exact' or 'approx'")+ self.data, self.dim, self.resume_class, self.persist = data, int(dim), resume, tuple(persist)+ os.makedirs(data, exist_ok=True)+ p = lambda n: os.path.join(data, n) # noqa: E731+ self.f_events, self.f_journal, self.f_final, self.f_pid, self.f_startups = (+ p("episode.jsonl"), p("journal.f64"), p("final.json"), p("server.pid"), p("startups.jsonl"))+ self.rows = 0 # control steps executed in this episode (journaled)+ self.max_call_wall_s = MAX_CALL_WALL_S+ self.n_startups = 0; self.resumes = 0; self.mismatches = 0; self.max_tcp_dev = 0.0; self.max_joint_dev = 0.0+ self._jf = None; self._call: dict | None = None; self._ids = 0; self._ck: tuple | None = None+ self._on_end: Callable | None = None; self._end_pending = False++ # ---- startup+ def startup(self) -> None:+ signal.signal(signal.SIGUSR1, self._usr1)+ try:+ os.remove(self.f_pid) # a PID file from before a crash would send the collect hook to a dead process+ except OSError:+ pass+ with open(self.f_startups, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid()}) + "\n")+ with open(self.f_startups) as f:+ self.n_startups = sum(1 for line in f if line.strip())+ if self.n_startups > 1 and not any(e.get("ev") == "start" for e in self.events()):+ time.sleep(min(120.0, 20.0 * (self.n_startups - 1)))+ faulthandler.dump_traceback_later(STARTUP_TIMEOUT_S, exit=True)++ def scene_built(self) -> None:+ faulthandler.cancel_dump_traceback_later() # the scene exists: a resume replay may take long, it is not a hang++ def _usr1(self, *_):+ if self._on_end is None:+ self._end_pending = True+ else:+ threading.Thread(target=self._on_end, daemon=True).start()++ # ---- the record+ def log(self, ev: dict) -> None:+ with open(self.f_events, "a") as f:+ f.write(json.dumps(_jsonable({"ts": time.time(), **ev})) + "\n")++ def events(self) -> list:+ out = []+ try:+ with open(self.f_events) as f:+ for line in f:+ try:+ out.append(json.loads(line))+ except ValueError: # a line cut by a crash+ pass+ except OSError:+ pass+ return [e for e in out if isinstance(e, dict)]++ def journal(self, row) -> bool:+ """One executed control step. True: the call in progress must stop at this step boundary (meta.stopped)."""+ a = np.asarray(row, dtype=np.float64).reshape(-1)+ if a.size != self.dim:+ raise ValueError(f"journal rows have {self.dim} entries, got {a.size}")+ if self._jf is None:+ self._jf = open(self.f_journal, "ab")+ self._jf.write(a.tobytes()); self.rows += 1+ c = self._call+ if c is None:+ return False+ if c["stopped"] is None:+ now = time.monotonic()+ if now - c["t0"] > self.max_call_wall_s:+ c["stopped"] = "max_call_wall_s"+ elif c["sock"] is not None and now - c["polled"] >= 0.2:+ c["polled"] = now+ if _peer_closed(c["sock"]):+ c["stopped"] = "client_disconnected"+ return c["stopped"] is not None++ @property+ def stopping(self) -> bool:+ """The call in progress must stop (adapters whose loops test E["done"] test this too)."""+ return bool(self._call and self._call["stopped"])++ @property+ def stop_reason(self) -> str | None:+ return self._call["stopped"] if self._call else None++ def call_begin(self, path: str, sock=None) -> int:+ self._ids += 1+ if path != "/kinematics":+ self._call = {"id": self._ids, "t0": time.monotonic(), "sock": sock, "polled": 0.0, "stopped": None}+ self.log({"ev": "call_begin", "id": self._ids, "path": path})+ return self._ids++ def call_end(self, cid: int, path: str, **extra) -> None:+ self.log({"ev": "call_end", "id": cid, "path": path, **extra})+ if path != "/kinematics":+ self._call = None++ def checkpoint(self, state: dict, state_sha: Callable | None, proprio: Callable | None) -> None:+ if self._jf is not None:+ self._jf.flush() # the rows reach the file before the checkpoint that counts them+ if self._ck is not None and self._ck[0] == self.rows:+ sha, pr = self._ck[1], self._ck[2] # no physics since the last checkpoint+ else:+ try:+ sha = state_sha() if state_sha else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); sha = None+ pr = self._proprio_row(proprio)+ self._ck = (self.rows, sha, pr)+ self.log({"ev": "checkpoint", "call": int(state.get("calls") or 0), "step": int(state.get("step") or 0),+ "control_steps": self.rows, "success": bool(state.get("success")), "done": bool(state.get("done")),+ "reason": state.get("reason"), "state_sha": sha, "proprio": pr,+ **({"persist": {k: state.get(k) for k in self.persist}} if self.persist else {})})++ @staticmethod+ def _proprio_row(proprio: Callable | None) -> list | None:+ try:+ return [round(float(v), 6) for v in np.asarray(proprio(), dtype=np.float64).reshape(-1)] if proprio else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); return None++ def final_fields(self) -> dict:+ """Crash-recovery fields for final.json / episode.json (all numeric, for reward.json)."""+ return {"sim_startups": self.n_startups, "resumes": self.resumes, "resume_state_mismatch": int(self.mismatches > 0),+ "resume_max_tcp_dev_m": round(self.max_tcp_dev, 6), "resume_max_joint_dev": round(self.max_joint_dev, 6)}++ # ---- start or resume+ def begin(self, *, state: dict, step: Callable, state_sha: Callable, proprio: Callable, spec: dict,+ start_event: dict | None = None, on_end: Callable | None = None) -> bool:+ """Start the episode, or resume it after a crash. `step(row)` executes one journaled row on the simulator (the+ recorder on, no rendering needed); `on_end` is what the collect hook's SIGUSR1 runs (in a thread). Returns True+ if the episode was resumed."""+ try: # a line cut by the crash must not swallow the next record+ with open(self.f_events, "rb+") as f:+ f.seek(0, os.SEEK_END)+ if f.tell():+ f.seek(-1, os.SEEK_END)+ if f.read(1) != b"\n":+ f.write(b"\n")+ except OSError:+ pass+ ev = self.events()+ starts = [e for e in ev if e.get("ev") == "start"]+ if not starts:+ try:+ os.remove(self.f_journal)+ except OSError:+ pass+ sha = state_sha()+ self._ck = (0, sha, self._proprio_row(proprio))+ self.log({**(start_event or {}), "ev": "start", "state_sha": sha, "protocol": PROTOCOL, "resume": self.resume_class,+ "journal_dim": self.dim})+ state["t0"] = time.time()+ self._arm(on_end)+ return False+ tries = [e for e in ev if e.get("ev") == "resuming"] # earlier resumes (a crash during one counts too)+ resumed = [e for e in ev if e.get("ev") == "resumed"]+ self.resumes = len(tries) # the record so far, also for a give-up below (final_fields)+ self.mismatches = sum(1 for e in resumed if e.get("exact") is False)+ self.max_tcp_dev = max([float(e.get("tcp_dev_m") or 0) for e in resumed] + [0.0])+ self.max_joint_dev = max([float(e.get("joint_dev") or 0) for e in resumed] + [0.0])+ if final_verdict(self.data):+ self.give_up("restarted after finalize", infra=False)+ k = max(i for i, e in enumerate(ev) if e.get("ev") in ("start", "resuming", "resumed"))+ tail = ev[k + 1:]+ in_call = bool({e.get("id") for e in tail if e.get("ev") == "call_begin"} - {e.get("id") for e in tail if e.get("ev") == "call_end"})+ if len(tries) >= MAX_RESUMES:+ agent = sum(1 for e in tries if e.get("crashed_in_call")) + int(in_call) == len(tries) + 1+ self.give_up("sim_crashed_on_call" if agent else "sim_crashed", infra=not agent)+ self.log({"ev": "resuming", "attempt": len(tries) + 1, "crashed_in_call": in_call,+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self.resumes = len(tries) + 1 # this attempt counts, whether or not it succeeds+ cps = [e for e in ev if e.get("ev") == "checkpoint"]+ last = cps[-1] if cps else {"call": 0, "step": 0, "control_steps": 0, "success": False, "state_sha": starts[0].get("state_sha")}+ n = int(last.get("control_steps") or 0)+ try:+ R = np.fromfile(self.f_journal, dtype=np.float64)+ except (OSError, ValueError):+ R = np.zeros(0)+ if R.size < n * self.dim:+ self.give_up("resume_failed: journal shorter than the log", infra=True)+ R = R[: n * self.dim].reshape(n, self.dim)+ t = time.time()+ for row in R:+ step(row)+ replay_s = time.time() - t+ R.tofile(self.f_journal) # drop the rows of the call that was in flight+ self.rows = n+ sha = state_sha(); want = last.get("state_sha")+ exact = None if want is None else sha == want+ dev = self._deviation(last.get("proprio"), proprio, spec)+ if exact is False: # recorded first: a give-up below reports it too+ self.mismatches += 1+ self.max_tcp_dev = max(self.max_tcp_dev, dev.get("tcp_m") or 0.0)+ self.max_joint_dev = max(self.max_joint_dev, dev.get("joint") or 0.0)+ if self.resume_class == "exact":+ self.give_up("resume_failed: replayed state differs from the logged one", infra=True)+ if dev.get("tcp_m") is not None and dev["tcp_m"] > RESUME_MAX_DEV_M:+ self.give_up(f"resume_failed: a replayed TCP is {dev['tcp_m']:.3f} m from its checkpoint (> {RESUME_MAX_DEV_M} m)", infra=True)+ state["calls"] = int(last.get("call") or 0); state["step"] = int(last.get("step") or 0)+ if "success" in state:+ state["success"] = bool(last.get("success"))+ for key, v in (last.get("persist") or {}).items():+ state[key] = v+ state["t0"] = float(starts[0]["ts"])+ ended = [e for e in ev if e.get("ev") == "end" and int(e.get("control_steps") or 0) <= n] # not the lost call's+ if ended:+ state["done"] = True; state["reason"] = ended[-1].get("reason"); state["t_end"] = float(ended[-1]["ts"])+ state["episode_control_steps"] = int(ended[-1].get("control_steps") or n)+ self._ck = (n, sha, self._proprio_row(proprio)) # the replayed state's row (it may differ under approx)+ self.log({"ev": "resumed", "attempt": self.resumes, "control_steps": n, "calls": state["calls"], "state_sha": sha,+ "logged_sha": want, "exact": exact, "class": self.resume_class, "tcp_dev_m": dev.get("tcp_m"),+ "joint_dev": dev.get("joint"), "crashed_in_call": in_call, "replay_s": round(replay_s, 1),+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self._arm(on_end)+ return True++ @staticmethod+ def _deviation(ref, proprio: Callable, spec: dict) -> dict:+ """The replayed robot against its checkpointed proprio row: max |joint_pos| difference (rad or m) and the largest+ TCP position error (m) over the tcp_pose frames (7 columns each: x y z + quaternion)."""+ if ref is None:+ return {}+ try:+ now = np.asarray(proprio(), dtype=np.float64).reshape(-1); ref = np.asarray(ref, dtype=np.float64).reshape(-1)+ except Exception: # noqa: BLE001+ return {}+ if now.shape != ref.shape:+ return {}+ g, out = spec.get("proprio_groups") or {}, {}+ if "joint_pos" in g:+ f, n = int(g["joint_pos"][0]), int(g["joint_pos"][1])+ out["joint"] = float(np.max(np.abs(now[f:f + n] - ref[f:f + n]))) if n else 0.0+ if "tcp_pose" in g:+ f, n = int(g["tcp_pose"][0]), int(g["tcp_pose"][1]); m = n // 7+ d = (now[f:f + 7 * m] - ref[f:f + 7 * m]).reshape(m, 7)[:, :3]+ out["tcp_m"] = float(np.max(np.linalg.norm(d, axis=1))) if m else 0.0+ return out++ def _arm(self, on_end: Callable | None) -> None:+ self._on_end = on_end+ signal.signal(signal.SIGUSR1, self._usr1)+ if on_end is not None and self._end_pending:+ self._end_pending = False+ threading.Thread(target=on_end, daemon=True).start()++ def give_up(self, reason: str, infra: bool) -> None:+ """End the trial's episode without a new one (never a reset): log it, write the verdict unless one is on disk,+ leave the PID file for the collect hook, and idle until the container is removed."""+ faulthandler.cancel_dump_traceback_later()+ self.log({"ev": "restart_refused", "reason": reason})+ if not final_verdict(self.data):+ fin = _read_json(self.f_final)+ fin.update({"success": False, "done": True, "reason": reason, "finalized": True, "gave_up": True, "protocol": PROTOCOL,+ **self.final_fields(), **({"infra_error": 1} if infra else {})})+ _write_json(self.f_final, fin)+ with open(self.f_pid, "w") as f:+ f.write(str(os.getpid()))+ signal.signal(signal.SIGUSR1, lambda *_: None)+ print(f"[{PROTOCOL}] restart refused: {reason}", flush=True)+ while True:+ time.sleep(3600)+++# ---------------------------------------------------------------- the HTTP layer+class Service:+ """What a sim service hands to serve(): spec (dict), lock, state (the service's E dict: done, reason, exiting, error),+ submit(meta, actions) and observe(meta) -> (meta_out, rcb1 parts), kinematics(req) -> dict, status() -> dict,+ on_submit_error(exc) (a simulator error in /submit or /observe: it ends the episode, reason "error"), log(event dict),+ and for crash recovery the Episode with the simulator's state_sha() and proprio row()."""++ def __init__(self, *, spec: dict, lock, state: dict, submit: Callable, observe: Callable, kinematics: Callable,+ status: Callable, on_submit_error: Callable, log: Callable, max_resp: int = MAX_RESP,+ episode: Episode | None = None, state_sha: Callable | None = None, proprio: Callable | None = None):+ self.spec, self.lock, self.state, self.submit, self.observe = spec, lock, state, submit, observe+ self.kinematics, self.status, self.on_submit_error, self.log, self.max_resp = kinematics, status, on_submit_error, log, max_resp+ self.episode, self.state_sha, self.proprio = episode, state_sha, proprio+ self.kin_calls = 0+++def make_handler(svc: Service):+ class H(BaseHTTPRequestHandler):+ def _send(self, code: int, ctype: str, body: bytes) -> None:+ try:+ self.send_response(code); self.send_header("Content-Type", ctype); self.send_header("Content-Length", str(len(body)))+ self.end_headers(); self.wfile.write(body)+ except (BrokenPipeError, ConnectionResetError): # the client hung up (its call was abandoned)+ pass++ def _json(self, code: int, obj: dict) -> None:+ self._send(code, "application/json", json.dumps(obj).encode())++ def _rcb1(self, meta: dict, parts: list) -> None:+ self._send(200, "application/x-rcb1", encode_response(meta, parts, svc.max_resp))++ def log_message(self, *a):+ pass++ def _body(self):+ try:+ n = int(self.headers.get("Content-Length", 0))+ except ValueError:+ raise ValueError("bad Content-Length")+ if n > MAX_BODY:+ raise ValueError("request too large")+ raw = self.rfile.read(n) if n else b""+ if raw[:4] == rcb1.MAGIC:+ return rcb1.decode(raw)+ body = json.loads(raw or b"{}")+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object or an RCB1 frame")+ return body, {}++ def do_GET(self):+ if self.path == "/spec":+ return self._json(200, svc.spec)+ if self.path == "/status":+ st = svc.status()+ return self._json(200, {**st, "resumes": svc.episode.resumes} if svc.episode else st)+ return self._json(404, {"error": "no such endpoint"})++ def do_POST(self):+ if self.path not in ("/submit", "/observe", "/kinematics"):+ return self._json(404, {"error": "no such endpoint"})+ try:+ meta, parts = self._body()+ except Exception as exc: # noqa: BLE001+ return self._json(413 if "too large" in str(exc) else 400, {"error": str(exc)[:200]})+ E, ep = svc.state, svc.episode+ if self.path == "/kinematics": # stateless: never steps physics, never waits for the episode lock+ cid = ep.call_begin(self.path) if ep else 0+ try:+ req = parse_kinematics(meta, svc.spec["kinematics"])+ out = svc.kinematics(req); svc.kin_calls += 1+ except ValueError as exc:+ return self._json(400, {"error": str(exc)[:300]})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); return self._json(500, {"error": "kinematics error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ ep.call_end(cid, self.path)+ return self._json(200, out)+ with svc.lock:+ if E.get("exiting") or (self.path == "/submit" and E.get("done")):+ return self._json(409, {"error": "episode finished", "reason": E.get("reason")})+ cid = ep.call_begin(self.path, self.connection) if ep else 0+ rows0 = ep.rows if ep else 0+ out = blobs = err = None; stopped = None+ try:+ if self.path == "/submit":+ A = np.asarray(parts["actions"]["data"] if "actions" in parts else meta.get("actions", []), dtype=np.float64)+ out, blobs = svc.submit(meta, A)+ else:+ out, blobs = svc.observe(meta)+ except ValueError as exc:+ err = (400, {"error": str(exc)})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); E["error"] = repr(exc); svc.log({"ev": "error", "path": self.path, "error": repr(exc)})+ try:+ svc.on_submit_error(exc) # PROTOCOL §4.6: a simulator error ends the episode (reason "error")+ except Exception: # noqa: BLE001+ traceback.print_exc()+ err = (500, {"error": "simulator error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ stopped = ep.stop_reason+ if err is None or ep.rows != rows0:+ try:+ ep.checkpoint(E, svc.state_sha, svc.proprio)+ except Exception: # noqa: BLE001+ traceback.print_exc()+ ep.call_end(cid, self.path, **({"stopped": stopped} if stopped else {}))+ if err is not None:+ return self._json(*err)+ return self._rcb1({**out, "stopped": stopped}, blobs)+ return H+++def serve(svc: Service, port: int = 8000) -> None:+ """Check the spec, then serve forever (one request at a time, as every 2.x service)."""+ svc.spec.setdefault("on_service_error", ON_SERVICE_ERROR)+ if svc.episode is not None:+ svc.spec.setdefault("max_call_wall_s", svc.episode.max_call_wall_s)+ check_spec(svc.spec)+ HTTPServer(("0.0.0.0", port), make_handler(svc)).serve_forever()+++# ---------------------------------------------------------------- the collect hook's first half+def _alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ try: # a zombie (exited, not yet reaped) counts as gone+ with open(f"/proc/{pid}/stat") as f:+ return f.read().rsplit(")", 1)[-1].split()[0] != "Z"+ except OSError:+ return True+++def end_episode(data: str, timeout: float = 21600.0, wait_key: str | None = None, resend_s: float = 30.0) -> int:+ """Tell the service that the agent phase is over and wait until it has ended the episode. The service may be+ resuming after a crash (no PID file until it is ready again), so there is no fixed start-up wait, and a signal goes+ only to the process that wrote the newest line of startups.jsonl (its SIGUSR1 handler is installed by then).+ Returns 2: final.json already holds the verdict (the service gave up after crashes, or graded in-process; with+ `wait_key`, also waits for that final.json key, e.g. video_done): keep it, run no replays.+ Returns 0: the service dumped the episode (episode.json) and exited: the hook replays it next.+ Returns 1: timed out."""+ t0, sent = time.time(), 0.0+ f_pid, f_dump, f_starts = (os.path.join(data, n) for n in ("server.pid", "episode.json", "startups.jsonl"))+ while time.time() - t0 < timeout:+ fin = final_verdict(data)+ if fin is not None:+ if not wait_key or fin.get(wait_key) or fin.get("gave_up"):+ return 2+ time.sleep(2); continue+ try:+ with open(f_pid) as f:+ pid = int(f.read().strip())+ except (OSError, ValueError):+ pid = None+ try:+ with open(f_starts) as f:+ cur = json.loads([x for x in f if x.strip()][-1]).get("pid")+ except (OSError, ValueError, IndexError):+ cur = None # a service without Episode.startup(): signal what the PID file names+ if pid is not None and (cur is None or pid == cur):+ if not _alive(pid):+ if os.path.exists(f_dump):+ return 0+ elif time.time() - sent >= resend_s:+ try:+ os.kill(pid, signal.SIGUSR1); sent = time.time()+ except OSError:+ pass+ time.sleep(2)+ return 1+++if __name__ == "__main__":+ a = sys.argv[1:]+ if len(a) >= 2 and a[0] == "end":+ wk = a[a.index("--wait-key") + 1] if "--wait-key" in a else None+ to = float(a[a.index("--timeout") + 1]) if "--timeout" in a else 21600.0+ rc = end_episode(a[1], timeout=to, wait_key=wk)+ print({0: "[collect] episode dumped by the service", 1: "[collect] timed out waiting for the service",+ 2: "[collect] final.json already holds the verdict"}[rc], flush=True)+ sys.exit(rc)+ if len(a) == 2 and a[0] == "final-verdict":+ fin = final_verdict(a[1])+ print(json.dumps(fin) if fin else "no final verdict")+ sys.exit(0 if fin else 1)+ print("usage: rcb_limited.py end <data dir> [--wait-key KEY] [--timeout S] | final-verdict <data dir>")+ sys.exit(2)diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/rcb_quadruped.py b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/run.sh b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/run.shnew file mode 100755index 0000000000..49d4d045d4--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/run.sh@@ -0,0 +1,22 @@+#!/bin/sh+# eai-standard/2.2 sidecar entrypoint: PID 1 of the `sim` container, shared by every 2.2 service+# (scripts/eai_standard/run.sh, copied unchanged into each standard task's environment/sim/).+# - The service crashed (a non-zero exit: an exception, a signal, the startup watchdog): exit with its code, so compose+# restarts the container (`restart: on-failure:6`) and the service resumes the same episode from its journal+# (rcb_limited.Episode). The container keeps its /data (or /out) across the restart.+# - The service exited cleanly (0: it dumped its episode on the collect hook's SIGUSR1 and released the simulator): keep+# the container up for the collect hook's fresh-process replays. If the service were PID 1 itself, that exit would+# stop the container and kill the hook with it (Harbor reports exit 137).+# - Everything the service prints also goes to $RCB_DATA/server.log (an artifact: Harbor keeps no sidecar output, and a+# simulator that dies while it loads leaves no other trace).+DATA="${RCB_DATA:-/data}"+mkdir -p "$DATA"+rm -f "$DATA/.service_rc"+{ python -u "${RCB_SERVER:-/srv/server.py}" 2>&1; echo "$?" > "$DATA/.service_rc"; } | tee -a "$DATA/server.log"+rc="$(cat "$DATA/.service_rc" 2>/dev/null)"; rc="${rc:-1}"+if [ "$rc" != 0 ]; then+ echo "[sim] service exited ($rc): leaving, so compose restarts the container (the service resumes the episode if one began)" | tee -a "$DATA/server.log"+ exit "$rc"+fi+echo "[sim] service exited (0); holding the container open for the collect hook" | tee -a "$DATA/server.log"+while true; do sleep 3600; donediff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/server.py b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/server.pynew file mode 100644index 0000000000..b0c774b183--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/environment/sim/server.py@@ -0,0 +1,478 @@+"""eai-standard/2.2 sim service for MuJoCo Playground's quadruped tasks (docs/STANDARD_MODE_2_2.md): the adapter of the+shared layer rcb_limited.py; the simulator is rcb_quadruped.Session (plain MuJoCo on the CPU).+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to+/data/episode.jsonl.++The episode is the frozen instance's: one control step = 1/50 s. A joystick episode ends after the whole command schedule+(the horizon), when the robot meets Playground's termination rule (it falls over: a failure), when the agent submits+`done`, or when its time is over; success = the task's check on the steps executed. A getup episode ends the moment the+check holds (success), after the horizon, on `done` or on timeout.++Crash recovery (rcb_limited.Episode, resume class `exact`: MuJoCo on the CPU repeats bit for bit in a fresh process):+every executed row is journaled; after a crash the service rebuilds the episode and replays the journal. When the+episode ends the service writes /data/trajectory.npz + /data/episode.json; the collect hook (finalize.sh) makes it exit+and replays the trajectory in two fresh processes."""++import math+import os+import sys+import threading+import time+import traceback++import numpy as np++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import rcb_limited as L # noqa: E402++DATA = os.environ.get("RCB_DATA", "/data")+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.json"))+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "3600"))+MAX_CHUNK_S = float(os.environ.get("RCB_MAX_CHUNK_S", "10"))+MAX_WATCH_S = float(os.environ.get("RCB_MAX_WATCH_S", "30"))+CAM_W, CAM_H = 320, 240+LOCK = threading.Lock()+PID_FILE = os.path.join(DATA, "server.pid")+E = {"ready": False, "step": 0, "calls": 0, "done": False, "reason": None, "success": False, "t0": time.time(), "error": None}++os.environ["RCB_SESSION_LOG"] = ""+os.environ["RCB_AGENT_TRACE_DIR"] = ""+import rcb_quadruped as Q # noqa: E402 (first: it picks the rendering backend before mujoco loads)+import mujoco # noqa: E402++EP = L.Episode(DATA, dim=Q.N, resume="exact")+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()+S = Q.Session(INSTANCE)+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz+DT = S.control_dt # one control step of simulated time (Barkour: 10 ms, as Playground steps it)+CTRL_HZ = 1.0 / DT+SUBSTEPS = S.substeps+M = S.model+CAMS = list(S.cameras)+FEET = S.robot["feet"]+LIMITS = np.stack([S.lower, S.upper], axis=1)+GROUPS = [+ ("joint_pos", S.joint_names, "measured joint positions (rad), in the action's order"),+ ("joint_vel", [f"{j}_vel" for j in S.joint_names], "measured joint velocities (rad/s)"),+ ("joint_effort", [f"{j}_effort" for j in S.joint_names], "actuator torques of those joints (N m)"),+ ("gripper_opening", [], "none (no gripper)"),+ ("tcp_pose", [], "none (no gripper)"),+ ("imu_gyro", ["gyro_x", "gyro_y", "gyro_z"], "angular velocity of the trunk, IMU frame (rad/s)"),+ ("imu_accelerometer", ["acc_x", "acc_y", "acc_z"], "specific force at the IMU, IMU frame (m/s^2; +9.81 up at rest)"),+ ("imu_gravity", ["gravity_x", "gravity_y", "gravity_z"], "unit vector of gravity's direction in the IMU frame "+ "([0, 0, -1] when the trunk is level)"),+ ("imu_linvel", ["linvel_x", "linvel_y", "linvel_z"], "linear velocity of the trunk at the IMU, IMU frame (m/s; the "+ "IMU's velocimeter, what a state estimator gives)"),+ ("foot_contact", [f"{f}_contact" for f in FEET], "1 when the foot touches the ground, else 0"),+]+PROPRIO_LAYOUT = [n for _, names, _ in GROUPS for n in names]+PROPRIO_GROUPS, _i = {}, 0+for _g, _names, _meaning in GROUPS:+ PROPRIO_GROUPS[_g] = [_i, len(_names), _meaning]+ _i += len(_names)+++# ------------------------------------------------------------------------------------------------- cameras+def _intrinsic(cam: str) -> list:+ fovy = math.radians(float(M.cam_fovy[M.camera(cam).id]))+ f = 0.5 * CAM_H / math.tan(fovy / 2)+ return [[f, 0.0, CAM_W / 2], [0.0, f, CAM_H / 2], [0.0, 0.0, 1.0]]+++def camera_info(cam: str) -> dict:+ """World -> camera (OpenCV axes) and camera -> world (OpenGL axes) at the current state."""+ i = M.camera(cam).id+ R_gl = S.data.cam_xmat[i].reshape(3, 3) # camera axes (OpenGL: x right, y up, z back) in the world+ p = S.data.cam_xpos[i].copy()+ R_cv = R_gl @ np.diag([1.0, -1.0, -1.0])+ ext = np.zeros((3, 4))+ ext[:, :3] = R_cv.T+ ext[:, 3] = -R_cv.T @ p+ c2w = np.eye(4)+ c2w[:3, :3] = R_gl+ c2w[:3, 3] = p+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": ext.tolist(), "cam2world_gl": c2w.tolist(),+ "image_size": [CAM_W, CAM_H]}+++# ------------------------------------------------------------------------------------------------- kinematics+KD = mujoco.MjData(M) # kinematics only: the trunk at the origin, level; never stepped+_FOOT = {f: M.site(f).id for f in FEET}+_LEG_DOF = {f: [6 + 3 * k + j for j in range(3)] for k, f in enumerate(FEET)} # actuator order = leg order = FEET+++def _fk_kd(q) -> None:+ KD.qpos[:] = 0.0+ KD.qpos[3] = 1.0+ KD.qpos[7:] = q+ mujoco.mj_kinematics(M, KD)+++def _foot_pose(f: str) -> list:+ quat = np.zeros(4)+ mujoco.mju_mat2Quat(quat, KD.site_xmat[_FOOT[f]])+ return [*KD.site_xpos[_FOOT[f]].tolist(), *quat.tolist()]+++def do_kinematics(req: dict) -> dict:+ """Feet in the trunk frame (the trunk body's origin and axes; x forward, y left, z up). IK solves positions only, one+ leg (3 joints) per foot target, damped least squares within the joint ranges; a foot's orientation is ignored."""+ if req["op"] == "fk":+ _fk_kd(np.asarray(req["q"]))+ return L.fk_response({f: _foot_pose(f) for f in req["links"]}, "trunk")+ q = np.array(req["seed"] if req["seed"] is not None else S.data.qpos[7:], dtype=np.float64)+ errors = {}+ jac = np.zeros((3, M.nv))+ for f, pose in req["targets"].items():+ tgt = np.asarray(pose[:3])+ idx = _LEG_DOF[f]+ for _ in range(req["max_iters"]):+ _fk_kd(q)+ err = tgt - KD.site_xpos[_FOOT[f]]+ if np.linalg.norm(err) < req["tol_pos_m"]:+ break+ mujoco.mj_jacSite(M, KD, jac, None, _FOOT[f])+ J = jac[:, idx]+ dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(3), err)+ q[[i - 6 for i in idx]] = np.clip(q[[i - 6 for i in idx]] + dq, S.lower[[i - 6 for i in idx]],+ S.upper[[i - 6 for i in idx]])+ _fk_kd(q)+ errors[f] = (float(np.linalg.norm(tgt - KD.site_xpos[_FOOT[f]])), 0.0)+ ok = all(e[0] <= req["tol_pos_m"] for e in errors.values())+ return L.ik_response(q, ok, errors, "trunk", note="feet: position only (a foot is a sphere; its orientation is ignored)")+++# ------------------------------------------------------------------------------------------------- spec+def schedule_text() -> list:+ if S.commands is None:+ return []+ return [{"from_s": round(int(c["start_step"]) * DT, 2), "vx_mps": round(c["vx"], 4), "vy_mps": round(c["vy"], 4),+ "wz_radps": round(c["wz"], 4)} for c in S.inst["commands"]]+++TASK_EPISODE = {+ "joystick": f"one episode, no reset: it ends after {S.horizon} control steps (the {S.horizon * DT:g} s command "+ f"schedule), when the robot meets its termination rule ({S.spec.get('term_text')}: a failure), when you "+ "submit `done`, or when your time is over",+ "getup": f"one episode, no reset: it ends the moment the robot has stood upright for {Q.HOLD_STEPS} control steps in a "+ f"row (success), after {S.horizon} control steps, when you submit `done`, or when your time is over",+ "stand_on_two": f"one episode, no reset: it ends the moment the pose has been held for {Q.POSE_HOLD_STEPS} control steps "+ "in a row (success), when the robot meets the termination rule (a failure: its trunk's up axis below "+ f"-0.25, or {'a leg' if S.spec.get('hind_leg_contact') else 'a front leg'}'s thigh, calf or hip on the "+ f"floor), after {S.horizon} control steps, when you "+ "submit `done`, or when your time is over",+}[S.kind]+_ctl = {"type": "joint position actuators (PD)", "kp_nm_per_rad": float(M.actuator_gainprm[0, 0]),+ "kd_nms_per_rad": float(M.dof_damping[6] - M.actuator_biasprm[0, 2])}+SPEC = {+ "protocol": L.PROTOCOL,+ "protocol_compat": list(L.COMPAT),+ "simulator": "MuJoCo 3.3.7 (MuJoCo Playground's scene, plain MuJoCo on the CPU)",+ "robot": S.robot["name"],+ "task_text": S.inst["text"],+ "control_hz": CTRL_HZ,+ "physics_substeps": SUBSTEPS,+ "max_chunk_s": MAX_CHUNK_S,+ "max_watch_s": MAX_WATCH_S,+ "cameras": {c: {"rgb": True, "depth": True, "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),+ **({"mounted": "follows the robot", "mount": {"type": "link", "link": S.robot["root"], "note":+ "follows the robot's centre of mass at a fixed offset; it does not turn with the robot"}}+ if int(M.cam_mode[M.camera(c).id]) != 0 else+ {"mounted": "on the robot's head", "mount": {"type": "link", "link": M.body(M.cam_bodyid[M.camera(c).id]).name+ or S.robot["root"], "note": "fixed to the robot: moves and turns with it"}})}+ for c in CAMS},+ "default_cameras": ["track"],+ "action_types": {+ "joint_position": {+ "dim": Q.N,+ "layout": S.joint_names,+ "limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "units": "rad",+ "semantics": "absolute targets of the 12 joint position actuators, one per control step (1/50 s); rows `dt` "+ "apart (a multiple of the control period, at most 0.5 s), `hold` or `linear` between rows; values "+ "outside the limits are clipped and reported",+ },+ "done": {"dim": 0, "layout": [], "semantics": 'ends the episode now, in the current state (no physics); r.submit("done", [])'},+ "not_yet": ["joint_velocity", "joint_torque", "joint_delta"],+ },+ "proprio_layout": PROPRIO_LAYOUT,+ "proprio_groups": PROPRIO_GROUPS,+ "static": {},+ "world": {"frame": "z up; the robot starts where the episode puts it (no world coordinates are given)", "up": "+z",+ "units": {"length": "m", "angle": "rad", "time": "s"}, "quaternion_order": "wxyz",+ "camera_axes": "intrinsic_cv / extrinsic_cv: OpenCV camera axes (x right, y down, z forward); cam2world_gl: OpenGL axes"},+ "budget": {"reset": 0, "steps": None, "wall_clock_s": WALL_CLOCK_S},+ "max_control_steps": S.horizon,+ "episode": TASK_EPISODE,+ "command_schedule": schedule_text(),+ **({"gait": {k: S.gait[k] for k in ("name", "frequency_hz", "foot_height_m", "phase0", "phase_dt")} | {+ "feet": FEET, "rule": "foot i's target height at control step t is get_rz(wrap(phase0[i] + t * phase_dt)) with "+ "Playground's gait.get_rz (a cubic Bezier from 0 up to foot_height_m over the first half of the phase, then "+ "down); phases in rad, wrapped to [-pi, pi)"}} if S.gait else {}),+ "robot_spec": {"name": S.robot["name"], "joints": S.joint_names, "joint_limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "joint_order": S.robot["joint_text"], "home_pose": dict(zip(S.joint_names, S.home.tolist())),+ "feet": FEET, "controller": _ctl},+ "kinematics": {"endpoint": "/kinematics", "joint_names": S.joint_names, "frame": "trunk", "quaternion_order": "wxyz",+ "links": FEET, "tcp_frames": [], "ee_frames": FEET, "ik_targets": FEET,+ "ik": {"tol_pos_m": 0.002, "tol_rot_rad": 3.2, "max_iters": 100},+ "note": "poses of the feet in the trunk frame (x forward, y left, z up, metres) for joint positions q; "+ "ik: one leg per foot, positions only"},+ "depth": {"modes": list(L.DEPTH_MODES), "default": "none", "kind": "z-depth", "unit": "m", "invalid": 0,+ "max_m": L.DEPTH_MAX_M, "frames_encoding": "uint16 mm, zlib", "noise": L.DEPTH_NOISE},+}+L.check_spec(SPEC) # a spec that misses a 2.2 field or names a forbidden one never starts the episode+EP.scene_built()++_RENDER = {}+++def _renderer():+ if "r" not in _RENDER:+ _RENDER["r"] = mujoco.Renderer(M, CAM_H, CAM_W)+ return _RENDER["r"]+++def ctrl_steps() -> int:+ return S.steps+++def proprio_row() -> np.ndarray:+ d = S.data+ return np.concatenate([d.qpos[7:], d.qvel[6:], d.actuator_force, S.sensor("gyro"), S.sensor("accelerometer"), S.gravity(),+ S.sensor("local_linvel"), S.foot_contacts()]).astype(np.float32)+++def grab(cams, want_depth: bool):+ r = _renderer()+ rgb, dep = {}, {}+ for c in cams:+ r.update_scene(S.data, camera=c)+ rgb[c] = r.render().copy()+ if want_depth:+ r.enable_depth_rendering()+ r.update_scene(S.data, camera=c)+ dep[c] = r.render().astype(np.float32).copy()+ r.disable_depth_rendering()+ return rgb, dep+++def extrinsics(cams) -> dict:+ return {c: np.asarray(camera_info(c)["extrinsic_cv"], dtype=np.float64) for c in cams}+++def write_final() -> None:+ if L.final_verdict(DATA): # finalize.sh's verdict, or a give-up after crashes: never overwritten+ return+ L._write_json(os.path.join(DATA, "final.json"), {**summary(), "finalized": False, "live_sha": E.get("live_sha")})+++def summary() -> dict:+ n = int(E.get("episode_control_steps") or ctrl_steps())+ chk = E.get("check") or {}+ return {"success": bool(E["success"]), "steps": E["step"], "calls": E["calls"], "control_steps": n,+ "physics_steps": n * SUBSTEPS, "elapsed_s": round((E.get("t_end") or time.time()) - E["t0"], 1),+ "reason": E["reason"], "done": E["done"], "env": S.env, "protocol": L.PROTOCOL, "n_actions": len(ROWS),+ "fell_at": chk.get("fell_at"), "worst_lin_err": chk.get("worst_lin_err"), "worst_yaw_err": chk.get("worst_yaw_err"),+ "tilt_deg": chk.get("tilt_deg"), "imu_height": chk.get("imu_height"), "pose_angle_deg": chk.get("pose_angle_deg"),+ **EP.final_fields()}+++def finish(reason: str) -> None:+ """The episode is over: the task's check on the steps executed, then the record for the collect hook."""+ if E["done"]:+ return+ E["done"] = True+ E["reason"] = reason+ E["t_end"] = time.time()+ E["episode_control_steps"] = ctrl_steps()+ try:+ chk = S.check()+ E["check"] = {k: v for k, v in chk.items() if k != "segments"}+ E["success"] = bool(chk["success"])+ except Exception: # noqa: BLE001+ traceback.print_exc()+ EP.log({"ev": "end", "reason": reason, "step": E["step"], "control_steps": ctrl_steps(), "success": bool(E["success"])})+ dump()+++def dump() -> None:+ if E.get("dumped"):+ return+ E["dumped"] = True+ E["live_sha"] = S.state_sha()+ np.savez(os.path.join(DATA, "trajectory.npz"), actions=np.asarray(ROWS, dtype=np.float64).reshape(-1, Q.N),+ env=S.env, action_layout=",".join(S.joint_names))+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})+ write_final()+++def after_step() -> None:+ if S.kind in ("joystick", "stand_on_two") and S.fell_at is not None:+ finish("fell")+ elif S.kind in ("getup", "stand_on_two") and S.check()["success"]:+ finish("success")+ elif S.done:+ finish("horizon")+++def ctrl_step(a, rec) -> bool:+ """One executed control step, journaled. True when the call must stop here."""+ S.step(a)+ ROWS.append(np.asarray(a, dtype=np.float64))+ stop = EP.journal(a)+ rec.tick()+ after_step()+ return E["done"] or stop+++def recorder(cams, fps: int, meta: dict) -> L.Recorder:+ return L.Recorder(cams, max(1, int(round(CTRL_HZ / max(1, fps)))), grab, proprio_row, extrinsics, ctrl_steps,+ depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+++def video_fps(meta: dict) -> int:+ fps = meta.get("video_fps")+ if fps is None:+ return 10+ if isinstance(fps, bool) or not isinstance(fps, (int, float)) or not (1 <= fps <= 50):+ raise ValueError("video_fps must be in [1, 50]")+ return int(fps)+++def cameras_of(meta: dict) -> list:+ cams = meta.get("cameras") or ["track"]+ bad = [c for c in cams if c not in CAMS]+ if bad:+ raise ValueError(f"unknown cameras {bad}; cameras: {CAMS}")+ return list(cams)+++def meta_common(cams) -> dict:+ n = ctrl_steps()+ out = {"step": E["step"], "calls": E["calls"], "control_steps": n, "physics_steps": n * SUBSTEPS,+ "sim_time_s": round(n * DT, 3), "time_s": round(time.time() - E["t0"], 2),+ "time_left_s": max(0.0, round(WALL_CLOCK_S - (time.time() - E["t0"]), 1)),+ "proprio": {"layout": PROPRIO_LAYOUT, "now": proprio_row().tolist()}, "done": E["done"], "reason": E["reason"],+ "cameras": {c: camera_info(c) for c in cams}}+ if S.kind == "joystick":+ out["command_now"] = dict(zip(("vx_mps", "vy_mps", "wz_radps"), S.command_now().round(4).tolist()))+ return out+++def do_submit(meta: dict, A: np.ndarray):+ typ = meta.get("type")+ if typ == "done":+ rec = recorder(cameras_of(meta), 5, meta)+ rec.tick(force=True, last=True) # every response carries the last frames+ E["calls"] += 1+ finish("done")+ return {**meta_common(cameras_of(meta)), "chunk_id": E["calls"], "type": typ, "executed_rows": 0, "ok": True}, rec.parts("none", 5)+ if typ != "joint_position":+ raise ValueError(f"type must be joint_position or done (not yet: {SPEC['action_types']['not_yet']})")+ dt = float(meta.get("dt", DT))+ interp = meta.get("interpolate", "linear")+ video = meta.get("video", "mp4")+ cams, fps = cameras_of(meta), video_fps(meta)+ k = dt / DT+ if A.ndim != 2 or A.shape[1] != Q.N:+ raise ValueError(f"joint_position actions must be (T, {Q.N}), got {list(A.shape)}")+ if not np.all(np.isfinite(A)):+ raise ValueError("actions contain NaN/inf")+ if not (math.isfinite(dt) and dt <= 0.5 + 1e-9 and round(k) >= 1 and abs(k - round(k)) < 1e-6):+ raise ValueError(f"dt must be a whole multiple of the {DT:g} s control period and at most 0.5 s; got {dt}")+ if A.shape[0] * dt > MAX_CHUNK_S + 1e-9:+ raise ValueError(f"chunk longer than max_chunk_s={MAX_CHUNK_S}: {A.shape[0]} rows x {dt} s")+ if interp not in ("hold", "linear"):+ raise ValueError("interpolate must be hold|linear")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, clipped = recorder(cams, fps, meta), []+ E["calls"] += 1+ step0, before = E["step"], ctrl_steps()+ rec.tick(force=True)+ prev = S.targets.copy()+ for ri, row in enumerate(A):+ E["step"] += 1+ target = np.clip(row, LIMITS[:, 0], LIMITS[:, 1])+ for j in np.flatnonzero(target != row)[:20]:+ clipped.append({"row": ri, "index": int(j), "reason": f"{S.joint_names[j]} limit [{LIMITS[j, 0]:g}, {LIMITS[j, 1]:g}]"})+ n = int(round(k))+ stop = False+ for s in range(1, n + 1):+ a = target if interp == "hold" else prev + (target - prev) * (s / n)+ if ctrl_step(a, rec):+ stop = True+ break+ prev = target+ if stop:+ break+ rec.tick(force=True, last=True)+ out = {**meta_common(cams), "chunk_id": E["calls"], "type": typ, "executed_rows": E["step"] - step0,+ "control_steps_chunk": ctrl_steps() - before, "physics_steps_chunk": (ctrl_steps() - before) * SUBSTEPS,+ "clipped": clipped[:200], "n_clipped": len(clipped), "plan": [], "ok": True}+ EP.log({"ev": "submit", "call": E["calls"], "rows": E["step"] - step0, "dt": dt, "interpolate": interp, "cameras": cams,+ "control_steps": ctrl_steps() - before, "n_clipped": len(clipped), "note": (meta.get("note") or "")[:500],+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video, fps)+++def do_observe(meta: dict):+ cams, fps = cameras_of(meta), video_fps(meta)+ seconds = float(meta.get("seconds", 0))+ video = meta.get("video", "frames")+ if not math.isfinite(seconds) or seconds < 0 or seconds > MAX_WATCH_S:+ raise ValueError(f"seconds must be in [0, {MAX_WATCH_S}]")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, before = recorder(cams, fps, meta), ctrl_steps()+ if seconds > 0 and not E["done"]:+ rec.tick(force=True)+ hold = S.targets.copy()+ for _ in range(int(round(seconds / DT))):+ if ctrl_step(hold, rec):+ break+ rec.tick(force=True, last=True)+ E["calls"] += 1+ out = {**meta_common(cams), "obs_id": E["calls"], "seconds": seconds, "control_steps_watch": ctrl_steps() - before,+ "physics_steps_watch": (ctrl_steps() - before) * SUBSTEPS, "ok": True}+ EP.log({"ev": "observe", "call": E["calls"], "seconds": seconds, "cameras": cams, "control_steps": ctrl_steps() - before,+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video if seconds > 0 else ("frames" if video == "mp4" else video), fps)+++def status() -> dict:+ return {"step": E["step"], "calls": E["calls"], "control_steps": ctrl_steps(), "done": E["done"], "reason": E["reason"],+ "elapsed_s": round(time.time() - E["t0"], 1)}+++def end_from_signal() -> None:+ """The collect hook's SIGUSR1: end the episode (the agent's time is over), dump it, exit so the replays can start."""+ with LOCK:+ E["exiting"] = True+ if not E["done"]:+ finish("timeout")+ EP.log({"ev": "exit", "reason": "collect hook: episode dumped"})+ if not os.path.exists(PID_FILE):+ open(PID_FILE, "w").write(str(os.getpid()))+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(0)+++def replay_row(row) -> None:+ """A journaled row during a resume."""+ S.step(row)+ ROWS.append(np.asarray(row, dtype=np.float64))+++EP.begin(state=E, step=replay_row, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, on_end=end_from_signal,+ start_event={"env": S.env, "seed": S.inst.get("seed"), "cameras": CAMS})+if E["done"]:+ dump() # resumed after the episode had ended: the record is rewritten from the replay+E["ready"] = True+write_final()+open(PID_FILE, "w").write(str(os.getpid()))+print(f"{L.PROTOCOL} MuJoCo Playground quadruped sim ready ({S.env}; startup {EP.n_startups}, resumes {EP.resumes})", flush=True)+L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics, status=status,+ on_submit_error=lambda exc: finish("error"), log=EP.log, episode=EP, state_sha=S.state_sha,+ proprio=proprio_row), port=int(os.environ.get("RCB_PORT", "8000")))diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/instruction.md b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/instruction.mdnew file mode 100644index 0000000000..512040536f--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/instruction.md@@ -0,0 +1,56 @@+# MuJoCo Playground · Go1JoystickFlatTerrain — STANDARD MODE (robot as a service, eai-standard/2.2)++**Task:** Make the Unitree Go1 follow the joystick command schedule on flat ground for the whole 20 s episode without falling over.++You control the Unitree Go1 quadruped — **as if it were real hardware** — in one episode of MuJoCo Playground's+`Go1JoystickFlatTerrain` environment (plain MuJoCo 3.3.7 with Playground's scene, commit 4057c14). The simulator runs in a service you+cannot open. You get one client and one episode.++## The episode+The robot starts at Playground's `home` pose, its base moved to (-0.493, -0.479) m and turned to a yaw of -142.4 deg, with a random base velocity (Playground's reset). The ground is flat.+For 20 s (1000 control steps) it is given this command schedule, drawn by Playground's command process (a new draw after Exp(1) x 5 s; a draw may keep a component). A command is a velocity in the robot's own frame: vx forward, vy to the left (the trunk's planar velocity), and the yaw rate:++| from (s) | vx (m/s) | vy (m/s) | yaw rate (rad/s) |+|---:|---:|---:|---:|+| 0.00 | +1.413 | -0.611 | +0.712 |+| 0.84 | -0.253 | -0.611 | +0.712 |+| 4.76 | -0.253 | -0.611 | +0.000 |+| 5.96 | -0.552 | -0.611 | +0.000 |++The same schedule is `spec["command_schedule"]`; every response's `meta["command_now"]` is the current command.++## Rules (real-robot rules)+- **No reset.** One episode. You see four cameras that follow the robot (RGB, depth if you ask) and the robot's own+ sensors: joint positions, velocities and torques, the IMU (gyro, accelerometer, gravity's direction, the trunk's+ velocity), foot contacts. No world positions, no success check.+- **The episode ends** after 1000 control steps, the whole schedule (`spec["max_control_steps"]`, counted by `meta["control_steps"]`), when the robot meets its termination rule (the trunk's up axis pointing below the horizon (the z component of the IMU frame's z axis negative): a failure), when you submit `done`, or when your time is up (before the end of the schedule, both are failures).+- **Success** is judged on the whole schedule: no termination, and in every command segment, after its first 25 control steps, a mean |v_xy - cmd_xy| of at most 0.2 m/s (`imu_linvel`) and a mean |w_z - cmd_wz| of at most 0.3 rad/s (`imu_gyro`).+- Your wall-clock budget is 3600 s from your start. Simulated time only advances with your commands (and+ `get_obs(seconds=...)`, which holds the current targets).+- Nothing to hand in: the service records the episode and grades it. Leave your script at `/app/output/gen.py`.+- **If the service crashes**, a call fails with a connection error: it restarts and resumes the SAME episode (never a+ reset) in the state after the last call it completed. `r.wait_ready()` waits for it; then check `r.status()`.+- Nothing is put into your context automatically: images come back as arrays in Python objects.++## Client (`/opt/tools/rcb_client.py`)+```python+from rcb_client import Robot+r = Robot() # connects (waits while the service starts)+spec = r.spec() # action types, limits, cameras, robot_spec (home pose, gains), kinematics, command_schedule+obs = r.get_obs() # obs.last[cam] -> uint8 (240, 320, 3); obs.meta["proprio"] {"layout", "now"}+res = r.submit("joint_position", A, dt=0.02) # A: (T, 12) rows dt apart; res.proprio (one row per frame), res.meta+obs = r.get_obs(seconds=1.0, video="mp4") # hold the current targets and watch for 1 s (max 30)+r.fk(q); r.ik({"FR": [x, y, z, 1, 0, 0, 0]}, seed=q) # feet in the trunk frame <-> joints (no physics)+r.submit("done", []) # end the episode now+r.status() # calls, control steps, done, reason, elapsed time+```+Cameras: `track`, `side`, `back`, `top` (they follow the robot); `spec["cameras"]` gives each one's mounting and intrinsics, and every response carries its pose. Proprioception (`spec["proprio_groups"]`): `joint_pos`, `joint_vel`, `joint_effort` (12 each, action+order), `imu_gyro`, `imu_accelerometer`, `imu_gravity`, `imu_linvel` (3 each, IMU frame: x forward, y left, z up),+`foot_contact` (FR, FL, RR, RL).++### `joint_position` (12)+FR, FL, RR, RL legs, each hip (abduction), thigh (hip pitch), calf (knee): absolute targets of the joint position actuators (rad; kp = 35 N m/rad, joint damping 0.5 N m s/rad).+Rows are `dt` apart (a whole multiple of the 0.02 s control period, at most 0.5 s), `interpolate="linear"` (default) or+`"hold"` between rows; a chunk covers at most 10 s; values outside the limits+(`spec["action_types"]["joint_position"]["limits"]`) are clipped and listed in `res.meta["clipped"]`. Feedback control+means short chunks: each response tells you where the robot is now.diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/solution/oracle.npy b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/solution/oracle.npynew file mode 100644index 0000000000..0e3688d4fbBinary files /dev/null and b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/solution/oracle_replay.py b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/solution/oracle_replay.pynew file mode 100644index 0000000000..b6a9824592--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/solution/oracle_replay.py@@ -0,0 +1,42 @@+"""Oracle (standard mode): streams the reference rows (one per 1/50 s control step, `hold`) as `joint_position` chunks+through the client, the same interface an agent has. Uses no privileged information at run time; the service's recorded+trajectory is then exactly the privileged reference. If the service crashes it resumes the same episode+(spec["on_service_error"]): the oracle waits until it answers again and goes on from the control step it reports."""+import os+import sys+import time++import numpy as np+import requests++sys.path.insert(0, "/opt/tools")+from rcb_client import EpisodeOver, Robot # noqa: E402++Q = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy")).astype(np.float64)+r = Robot()+spec = r.spec()+dt = 1.0 / float(spec["control_hz"])+per_chunk = max(1, int(spec.get("max_chunk_s", 10) / dt + 1e-9))+print("spec:", spec["protocol"], "rows:", len(Q), flush=True)+t0, i = time.time(), 0+while i < len(Q):+ chunk = Q[i:i + per_chunk]+ try:+ res = r.submit("joint_position", chunk, dt=dt, interpolate="hold", cameras=["track"], video="none", note=f"oracle rows {i}+")+ except EpisodeOver as e:+ print("episode over:", e)+ break+ except requests.exceptions.RequestException as e: # the service crashed: it restarts and resumes the same episode+ print("service unreachable:", repr(e)[:200], "- waiting for it to resume", flush=True)+ st = r.wait_ready()+ n = int(st["control_steps"])+ if not i <= n <= i + len(chunk):+ raise SystemExit(f"resumed at control step {n}: outside the chunk in flight (rows {i}..{i + len(chunk)})")+ i = n+ continue+ n = int(res.meta["control_steps"])+ print(f"rows {i}..{n}: clipped={res.meta['n_clipped']} done={res.meta['done']} reason={res.meta['reason']}", flush=True)+ if res.meta["done"] or n <= i:+ break+ i = n+print("status:", r.status(), "wall %.0fs" % (time.time() - t0))diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/solution/solve.sh b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/solution/solve.shnew file mode 100755index 0000000000..ecb1f6c954--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/solution/solve.sh@@ -0,0 +1,8 @@+#!/bin/bash+# Oracle (standard mode): streams the reference trajectory's joint targets (solution/oracle.npy, one row per control step)+# as `joint_position` chunks through the client. Uses no privileged information at run time (only the pre-recorded+# targets); the service's recorded trajectory is then exactly the privileged reference.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/task.toml b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/task.tomlnew file mode 100644index 0000000000..33ed968823--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/task.toml@@ -0,0 +1,54 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = [+ { source = "/data/final.json", service = "sim" },+ { source = "/data/episode.jsonl", service = "sim" },+ { source = "/data/trajectory.npz", service = "sim" },+ { source = "/data/replay.mp4", service = "sim" },+ { source = "/data/server.log", service = "sim" }, # the service's own output (Harbor keeps none)+ { source = "/data/journal.f64", service = "sim" }, # crash recovery: every executed control step (float64 rows)+ { source = "/data/startups.jsonl", service = "sim" }, # crash recovery: one line per service start+ { source = "/data/replay1.log", service = "sim" }, # the collect hook's two fresh-process replays+ { source = "/data/replay2.log", service = "sim" },+ { source = "/data/replay3.log", service = "sim" }, # and its third, which renders replay.mp4+ "/app/output/",+]++[task]+name = "robot-coding-bench/mujoco_playground_go1_joystick_flat_terrain-standard"+description = "STANDARD MODE (robot as a service, eai-standard/2.2): MuJoCo Playground Go1JoystickFlatTerrain (Unitree Go1) on the same frozen instance as mujoco_playground_go1_joystick_flat_terrain-privileged: Make the Unitree Go1 follow the joystick command schedule on flat ground for the whole 20 s episode without falling over. The agent only gets a client: four cameras that follow the robot (RGB, optional depth), the robot's joints and IMU, joint position chunks at 50 Hz, the feet's kinematics; one episode, no reset, no world state; the sim service records the episode, replays it in fresh processes and grades it."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "unitree-go1", "quadruped", "locomotion", "joystick", "code-as-policy", "trajectory", "standard-mode"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "unitree-go1"+family = "mujoco_playground/Go1JoystickFlatTerrain"+mode = "standard"+protocol = "eai-standard/2.2"+oracle = "full"+instance_seed = 0+expert_time_estimate_hours = 4.0++[verifier]+timeout_sec = 600.0+environment_mode = "separate"+network_mode = "no-network"++[[verifier.collect]]+service = "sim"+command = "sh /srv/finalize.sh" # end + dump + exit the service, replay twice in fresh processes, write final.json, video+timeout_sec = 1200++[agent]+timeout_sec = 3600.0+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/tests/Dockerfile b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/tests/Dockerfilenew file mode 100644index 0000000000..26bc699ebe--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/tests/Dockerfile@@ -0,0 +1,5 @@+# Separate verifier sandbox: grades the sim service's own artifacts; needs nothing but python (the shared client base).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY test.sh /tests/test.sh+COPY grade.py /tests/grade.py+RUN chmod +x /tests/test.shdiff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/tests/grade.py b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/tests/grade.pynew file mode 100644index 0000000000..5b990bf458--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/tests/grade.py@@ -0,0 +1,64 @@+"""Standard-mode verifier (MuJoCo Playground quadrupeds): reads what the sim service (which the agent could not touch) wrote:+/data/final.json (live success, two fresh-process replays of the recorded trajectory, determinism, crash-recovery+fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, the+replays having started in the instance's t = 0 state. Numeric-only reward.json."""++import json, os, shutil++LOG = "/logs/verifier"+os.makedirs(LOG, exist_ok=True)+++def write(ok, out):+ open(f"{LOG}/reward.txt", "w").write("1\n" if ok else "0\n")+ json.dump(out, open(f"{LOG}/reward.json", "w"))+ print(out)+++p = "/data/final.json"+if not os.path.exists(p):+ write(False, {"success": 0, "missing_log": 1, "grader_error": 0, "infra_error": 0})+ raise SystemExit+d = json.load(open(p))+for f in ("replay.mp4", "trajectory.npz", "episode.jsonl"):+ if os.path.exists(f"/data/{f}"):+ shutil.copy(f"/data/{f}", f"{LOG}/{f}")+ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic"))+ok = ok and not d.get("instance_mismatch")+num = lambda k: float(d.get(k) or 0) # noqa: E731+write(+ ok,+ {+ "success": int(ok),+ "live_success": int(bool(d.get("success"))),+ "replay_success": int(bool(d.get("replay_success"))),+ "deterministic": int(bool(d.get("deterministic"))),+ "live_matches_replay": int(bool(d.get("live_matches_replay"))),+ "finalized": int(bool(d.get("finalized"))),+ "n_actions": int(d.get("n_actions") or 0),+ "sim_steps": int(d.get("control_steps") or 0),+ "physics_steps": int(d.get("physics_steps") or 0),+ "steps": int(d.get("steps") or 0),+ "elapsed_s": float(d.get("elapsed_s") or 0),+ "video_rendered": int(bool(d.get("video"))),+ "fell": int(d.get("fell_at") is not None),+ "worst_lin_err": float(d["worst_lin_err"]) if d.get("worst_lin_err") is not None else -1.0,+ "worst_yaw_err": float(d["worst_yaw_err"]) if d.get("worst_yaw_err") is not None else -1.0,+ "end_tilt_deg": float(d["tilt_deg"]) if d.get("tilt_deg") is not None else -1.0,+ "end_imu_height": float(d["imu_height"]) if d.get("imu_height") is not None else -1.0,+ "end_pose_angle_deg": float(d["pose_angle_deg"]) if d.get("pose_angle_deg") is not None else -1.0,+ # a replay process gave no result, or the image no longer builds the frozen start: not the agent's 0+ "grader_error": int(bool(d.get("replay_failed") or d.get("instance_mismatch"))),+ "instance_mismatch": int(bool(d.get("instance_mismatch"))),+ # an infrastructure failure, not the agent's (PROTOCOL §2.6): a give-up after crashes between calls or a failed+ # resume (docs/STANDARD_MODE_2_2.md §13), the service not ending its episode for the collect hook, a replay+ # process that gave no result, replays that did not start in the instance's t = 0 state+ "infra_error": int(bool(d.get("infra_error"))),+ "gave_up": int(bool(d.get("gave_up"))),+ "sim_error": int(d.get("reason") == "error"),+ "sim_startups": int(d.get("sim_startups") or 0),+ "resumes": int(d.get("resumes") or 0),+ "resume_state_mismatch": int(d.get("resume_state_mismatch") or 0),+ "resume_max_joint_dev": num("resume_max_joint_dev"),+ },+)diff --git a/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/tests/test.sh b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/tests/test.shnew file mode 100755index 0000000000..bc608aa8b9--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_flat_terrain-standard/tests/test.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Verifier (separate sandbox): the sim sidecar's artifacts were uploaded to /data by Harbor.+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)+mkdir -p /logs/verifier+python /tests/grade.py 2> /logs/verifier/grade.logdiff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/README.md b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/README.mdnew file mode 100644index 0000000000..f494a1db98--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/README.md@@ -0,0 +1,42 @@+# mujoco_playground_go1_joystick_rough_terrain-privileged++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | privileged |+| Twin | `mujoco_playground_go1_joystick_rough_terrain-standard` |+| Simulator / robot | `mujoco` / `unitree-go1` |+| Family / instance | `mujoco_playground/Go1JoystickRoughTerrain` / seed 1 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `Go1JoystickRoughTerrain` (Unitree Go1), rebuilt in plain MuJoCo from Playground's scene files: Make the Unitree Go1 follow the joystick command schedule on rough terrain (a 20 x 20 m heightfield, up to 5 cm high) for the whole 20 s episode without falling over.+For 20 s the robot gets a joystick command schedule (7 segments: planar velocity and yaw rate in its own frame) and must track it without falling over. The ground is a 20 x 20 m heightfield with bumps up to 5 cm. The deliverable is one replayable trajectory of joint position targets+(`/app/output/trajectory.npz`, `(T, 12)`, T = 1000 (the whole schedule)).++## Difficulty+Velocity tracking for 20 s: the agent has to make a 12-joint quadruped walk (a gait, not one motion) and steer it through the schedule's changes of speed, direction and turning rate, and an open-loop trajectory of 1000 steps only works if it is computed against the simulator. Torque limits and a soft PD drive leave little margin; Playground trains a neural policy with 200 M steps of PPO for this. On the heightfield the feet land at unpredictable heights: Playground's own Go1 policy, which made the reference, falls or loses track on some of the candidate seeds (select_instances.py skips them).++## Reference solution+MuJoCo Playground's own Go1 joystick policy (`experimental/sim2sim/onnx/go1_policy.onnx` @4057c14, not in the image) run closed loop on this instance with the observation of Playground's `play_go1_joystick.py`, its targets recorded (`scripts/mujoco-playground/oracle.py`): worst segment errors 0.079 m/s and 0.114 rad/s. Replayed by `solution/solve.sh` (`solution/oracle.npy`, 1000 rows); the rows are float32-exact, so the+standard twin's client executes the same targets. Re-verified by `scripts/mujoco-playground/select_instances.py`: two+fresh-process replays succeed and end in the same state.++## Verification+`tests/grade.py` in a separate sandbox without network: two replays, each in a fresh process, from the verifier's own+copy of the instance (`tests/instance.json`; the start state is checked against its hash on every load); pass iff both+succeed and end in the same state (`deterministic`). Oracle: success, worst segment errors 0.079 m/s and 0.114 rad/s. `nop`: no trajectory, reward 0.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml`; MuJoCo Menagerie @ 1b86ece (`unitree_go1`); simulated in MuJoCo 3.3.7 on the CPU |+| Instance | Playground's `reset` with `jax.random.PRNGKey(1)` and Playground's command process over the 1000 steps; chosen by `scripts/mujoco-playground/select_instances.py` (seed 1; skipped 0: reference fails) |+| Actions | 12 joint position targets per control step (0.02 s of simulated time); kp = 35 N m/rad, joint damping 0.5 N m s/rad |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py` from `scripts/mujoco-playground/instances/Go1JoystickRoughTerrain.json`+(`make_instances.py`, `select_instances.py`) and `scripts/mujoco-playground/oracles/Go1JoystickRoughTerrain.npy` (`oracle.py`).diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/environment/Dockerfile b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/environment/Dockerfilenew file mode 100644index 0000000000..7bdd7d2938--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/environment/Dockerfile@@ -0,0 +1,8 @@+# MuJoCo Playground quadruped task (privileged): plain MuJoCo with Playground's and Menagerie's assets+# (images/mujoco/prepare_assets.sh), the task's tooling and its frozen instance.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY instance.json /app/instance.json+COPY rcb_quadruped.py /opt/tools/rcb_quadruped.py+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/environment/instance.json b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/environment/instance.jsonnew file mode 100644index 0000000000..dc3a670238--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/environment/instance.json@@ -0,0 +1,111 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1JoystickRoughTerrain",+ "seed": 1,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ -0.09635365009307861,+ 0.04889500141143799,+ 0.3499999940395355,+ 0.5138856768608093,+ 0.0,+ 0.0,+ 0.8578586578369141,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842+ ],+ "qvel0": [+ 0.043613314628601074,+ -0.24152767658233643,+ -0.45936477184295654,+ -0.09444129467010498,+ -0.01504206657409668,+ -0.4573014974594116,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 1.136733055114746,+ "vy": 0.16791878640651703,+ "wz": -0.7027067542076111+ },+ {+ "start_step": 17,+ "vx": 1.136733055114746,+ "vy": 0.0,+ "wz": -0.7027067542076111+ },+ {+ "start_step": 138,+ "vx": -1.078402042388916,+ "vy": -0.701647937297821,+ "wz": 0.0+ },+ {+ "start_step": 548,+ "vx": -1.078402042388916,+ "vy": 0.0,+ "wz": 0.7865484356880188+ },+ {+ "start_step": 594,+ "vx": 0.0,+ "vy": -0.35900041460990906,+ "wz": 0.7865484356880188+ },+ {+ "start_step": 611,+ "vx": 0.0,+ "vy": -0.35900041460990906,+ "wz": 0.0+ },+ {+ "start_step": 674,+ "vx": -0.03617405891418457,+ "vy": 0.0,+ "wz": -0.08692560344934464+ }+ ],+ "text": "Make the Unitree Go1 follow the joystick command schedule on rough terrain (a 20 x 20 m heightfield, up to 5 cm high) for the whole 20 s episode without falling over.",+ "facts": {+ "start_xy_m": [+ -0.096,+ 0.049+ ],+ "start_yaw_deg": 118.2,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.344,+ "reference_rows": 1000,+ "reference_worst_lin_err": 0.0788,+ "reference_worst_yaw_err": 0.1137+ },+ "state_sha": "4e94a33d805a",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.",+ "candidates_tried": 2+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/environment/rcb_quadruped.py b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/environment/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/environment/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/instruction.md b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/instruction.mdnew file mode 100644index 0000000000..fb76c8ca6d--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/instruction.md@@ -0,0 +1,65 @@+# MuJoCo Playground · Go1JoystickRoughTerrain — frozen episode++**Task:** Make the Unitree Go1 follow the joystick command schedule on rough terrain (a 20 x 20 m heightfield, up to 5 cm high) for the whole 20 s episode without falling over.++You control the Unitree Go1 quadruped in one episode of MuJoCo Playground's `Go1JoystickRoughTerrain` environment, rebuilt in plain+MuJoCo 3.3.7 from Playground's own scene files (Apache-2.0, commit 4057c14) and the robot from MuJoCo Menagerie. The+episode is frozen: it starts the same way after every reset (Playground's `reset` with seed 1), and you may reset+as often as you like. Your deliverable is **one open-loop trajectory**, not a general policy.++## The episode+The robot starts at Playground's `home` pose, its base moved to (-0.096, 0.049) m and turned to a yaw of 118.2 deg, with a random base velocity (Playground's reset). The ground is Playground's rough terrain: a 20 x 20 m heightfield (`hfield.png`, up to 5 cm high) centred on the world origin, with nothing beyond its edge.+For 20 s (1000 control steps) it is given this command schedule, drawn by Playground's command process (a new draw after Exp(1) x 5 s; a draw may keep a component). A command is a velocity in the robot's own frame: vx forward, vy to the left (the trunk's planar velocity), and the yaw rate:++| from (s) | vx (m/s) | vy (m/s) | yaw rate (rad/s) |+|---:|---:|---:|---:|+| 0.00 | +1.137 | +0.168 | -0.703 |+| 0.34 | +1.137 | +0.000 | -0.703 |+| 2.76 | -1.078 | -0.702 | +0.000 |+| 10.96 | -1.078 | +0.000 | +0.787 |+| 11.88 | +0.000 | -0.359 | +0.787 |+| 12.22 | +0.000 | -0.359 | +0.000 |+| 13.48 | -0.036 | +0.000 | -0.087 |++`s.commands` holds the schedule per control step; `s.state()["command"]` is the current one.++## Success+The episode lasts exactly 1000 control steps: the trajectory must have T = 1000 rows. Success iff+1. the robot never meets Playground's termination rule for this environment: the trunk's up axis pointing below the horizon (the z component of the IMU frame's z axis negative); and+2. in every command segment, over its control steps after the first 25 (0.5 s): the mean planar velocity error |v_xy - cmd_xy| is at most 0.2 m/s, with v the IMU's velocimeter (`local_linvel`, trunk frame), and the mean yaw-rate error |w_z - cmd_wz| at most 0.3 rad/s, with w the IMU's gyro.++`s.check()` reports `fell_at`, each segment's errors and `success`.++## Deliverable+`/app/output/trajectory.npz` with `actions`: float64 (T, 12), one row per control step (0.02 s): absolute targets of+the 12 joint position actuators, in `s.joint_names` order (FR, FL, RR, RL legs, each hip (abduction), thigh (hip pitch), calf (knee)), in radians; T = 1000 (the whole schedule). Values+outside the actuator ranges (`s.lower`, `s.upper`) are clipped. `s.save_trajectory(rows)` writes it. Also leave the+script that produced it at `/app/output/gen.py`. Save a working trajectory as soon as you have one and overwrite it as+you improve it: whatever is in `/app/output/` when your 3600 s are up is graded. The tooling logs your sessions and+resets (cost accounting, not graded).++## Tooling (installed; `python` from any directory)+```python+from rcb_quadruped import Session+s = Session("/app/instance.json") # the frozen episode at t = 0 (checked against the instance's state hash)+s.joint_names; s.lower; s.upper # the actuator order and ranges (rad)+s.home # Playground's standing pose (its `home` keyframe), in that order+s.step(row) # one control step: 12 joint targets, 5 physics steps of 0.004 s; returns s.check()+s.check() # the task's check on the steps so far (see Success)+s.state() # qpos, qvel, IMU (local_linvel, gyro, gravity, accelerometer, pose), feet, contacts, command+s.sensor(name); s.gravity() # one MuJoCo sensor; gravity's direction in the IMU frame+s.model, s.data # the live MuJoCo model and data (read them; changing them is not part of the replay)+s.render(cam); s.cameras # uint8 (240, 320, 3) from cameras that follow the robot: `track`, `side`, `back`, `top` (they follow the robot)+s.reset() # back to t = 0+s.replay(rows) # reset, run the rows, return the check and the final state's hash+s.render_video(rows, "/app/output/try.mp4")+s.save_trajectory(rows, "/app/output/trajectory.npz")+```+The grader runs exactly this CLI in two fresh processes, so run it to check yourself:+`python /opt/tools/rcb_quadruped.py replay --instance /app/instance.json --traj /app/output/trajectory.npz`++## Conventions+- Joint position actuators (PD): kp = 35 N m/rad, joint damping 0.5 N m s/rad, as Playground's environment sets them; the physics step is 0.004 s,+ the control step 0.02 s (5 physics steps); a row holds until the next one.+- World frame z up, metres; quaternions **wxyz**. The IMU frame is the trunk's: x forward, y left, z up.+- Physics is MuJoCo on the CPU: the same rows from the same start give the same result in every fresh process.diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/solution/oracle.npy b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/solution/oracle.npynew file mode 100644index 0000000000..7ca581e9d7Binary files /dev/null and b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/solution/oracle_replay.py b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/solution/oracle_replay.pynew file mode 100644index 0000000000..46987df1d0--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/solution/oracle_replay.py@@ -0,0 +1,15 @@+"""Oracle (privileged): replay the reference rows in the tooling, check them, and save them as the deliverable."""+import json+import os+import sys++import numpy as np++sys.path.insert(0, "/opt/tools")+from rcb_quadruped import Session # noqa: E402++rows = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy"))+s = Session("/app/instance.json")+r = s.replay(rows)+s.save_trajectory(rows, "/app/output/trajectory.npz", meta={"source": "reference trajectory (solution/oracle.npy)"})+print(json.dumps({k: v for k, v in r.items() if k != "segments"}))diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/solution/solve.sh b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/solution/solve.shnew file mode 100755index 0000000000..430ffb6017--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/solution/solve.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Oracle (privileged): write the reference trajectory frozen at generation time (solution/oracle.npy; how it was made:+# scripts/mujoco-playground/oracle.py) as the deliverable.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/task.toml b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/task.tomlnew file mode 100644index 0000000000..3e77cd2fb8--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/task.toml@@ -0,0 +1,43 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = ["/app/output/", "/logs/agent/rcb/"]++[task]+name = "robot-coding-bench/mujoco_playground_go1_joystick_rough_terrain-privileged"+description = "MuJoCo Playground Go1JoystickRoughTerrain in plain MuJoCo (Unitree Go1, joint position control every 0.02 s): Make the Unitree Go1 follow the joystick command schedule on rough terrain (a 20 x 20 m heightfield, up to 5 cm high) for the whole 20 s episode without falling over. Produce one replayable trajectory of joint position targets on a frozen instance (Playground's reset with seed 1); graded by velocity tracking over the whole 20 s schedule without a fall (two fresh-process replays)."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "unitree-go1", "quadruped", "locomotion", "joystick", "code-as-policy", "trajectory", "privileged"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "unitree-go1"+family = "mujoco_playground/Go1JoystickRoughTerrain"+mode = "privileged"+oracle = "full"+instance_seed = 1 # the PRNGKey of Playground's reset (and, for the joystick tasks, its command process)+expert_time_estimate_hours = 3.0++[verifier]+timeout_sec = 1200.0+environment_mode = "separate"+network_mode = "no-network"++[verifier.environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192++[agent]+timeout_sec = 3600.0+# MuJoCo Playground's trained policies are public upstream, so the agent reaches the model APIs and nothing else+# (scripts/set_agent_egress.py HOSTS).+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/tests/Dockerfile b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/tests/Dockerfilenew file mode 100644index 0000000000..f49c79154d--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/tests/Dockerfile@@ -0,0 +1,7 @@+# Separate verifier sandbox (PROTOCOL §4): the same image with the verifier's own copies of the tooling and the frozen+# instance. Nothing the agent did in its container reaches this one: Harbor uploads only the declared artifacts.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY grade.py instance.json rcb_quadruped.py test.sh /tests/+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier+ENV PYTHONPATH=/tests+WORKDIR /testsdiff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/tests/grade.py b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/tests/grade.pynew file mode 100644index 0000000000..e5668de85f--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/tests/grade.py@@ -0,0 +1,126 @@+"""Verifier (privileged): replay /app/output/trajectory.npz from the frozen instance and write Harbor's rewards.++ python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz++Two replays, each in its own fresh process (`rcb_quadruped.py replay`: the frozen start, one control step per row, the+task's success check on the whole trajectory). success = both replays succeed and end in the same state. Writes+/logs/verifier/reward.txt (1/0) and reward.json (numbers only); then a third replay renders replay.mp4, after the+verdict is on disk (it never changes it).+"""+import argparse+import json+import os+import subprocess+import sys+import tempfile+import traceback++import numpy as np++LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")+TOOL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_quadruped.py")+REPLAY_TIMEOUT_S = 300 # a 1000-step replay takes a few seconds; the video replay renders 4 views every 2nd step+++def write(ok: bool, out: dict) -> None:+ os.makedirs(LOG_DIR, exist_ok=True)+ open(os.path.join(LOG_DIR, "reward.txt"), "w").write("1\n" if ok else "0\n")+ json.dump(out, open(os.path.join(LOG_DIR, "reward.json"), "w"))+ print(json.dumps(out), flush=True)+++def agent_cost() -> dict:+ """Self-reported cost from the tooling's log in the agent's container (accounting, not evidence)."""+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_replays": 0, "agent_cost_self_reported": 1}+ for path in ("/logs/agent/rcb/rcb_session_log.jsonl", "/app/output/rcb_session_log.jsonl"):+ if not os.path.exists(path):+ continue+ try:+ with open(path) as f:+ for i, line in enumerate(f):+ if i > 200_000 or len(line) > 10_000:+ break+ try:+ e = json.loads(line)+ ev = e.get("ev") if isinstance(e, dict) else None+ if ev == "session_start":+ cost["agent_sessions"] += 1+ elif ev == "reset":+ cost["agent_resets"] += 1+ elif ev == "replay":+ cost["agent_replays"] += 1+ elif ev == "session_end":+ cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)+ except Exception: # noqa: BLE001 -- one bad line must not sink the verdict+ continue+ except OSError:+ pass+ break+ return cost+++def replay(instance: str, traj: str, video: str | None) -> dict:+ """One replay in a fresh process; its result (`--out`), or {"error": ...}."""+ with tempfile.NamedTemporaryFile(suffix=".json") as out:+ cmd = [sys.executable, TOOL, "replay", "--instance", instance, "--traj", traj, "--out", out.name]+ try:+ p = subprocess.run(cmd + (["--video", video] if video else []), stdout=subprocess.DEVNULL, stderr=sys.stderr,+ timeout=REPLAY_TIMEOUT_S, env={**os.environ, "RCB_SESSION_LOG": "", "RCB_AGENT_TRACE_DIR": ""})+ except subprocess.TimeoutExpired:+ return {"error": f"replay took over {REPLAY_TIMEOUT_S} s"}+ try:+ return json.load(open(out.name))+ except ValueError:+ return {"error": f"replay process rc={p.returncode}"}+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--instance", required=True)+ ap.add_argument("--traj", default="/app/output/trajectory.npz")+ a = ap.parse_args()+ cost = agent_cost()+ if not os.path.isfile(a.traj):+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost})+ return 0+ try:+ horizon = int(json.load(open(a.instance))["horizon"])+ d = np.load(a.traj, allow_pickle=False)+ acts = np.asarray(d["actions"], dtype=np.float64) if "actions" in d.files else np.zeros((0, 0))+ if acts.ndim != 2 or acts.shape[1] != 12 or len(acts) > horizon or not np.all(np.isfinite(acts)):+ write(False, {"success": 0, "bad_trajectory": 1, "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0,+ "grader_error": 0, **cost})+ return 0+ runs = [replay(a.instance, a.traj, None), replay(a.instance, a.traj, None)]+ if any("error" in r and not r.get("bad_trajectory") for r in runs):+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ if not all(r.get("instance_ok") for r in runs): # the image no longer builds the frozen start: not the agent's 0+ write(False, {"success": 0, "grader_error": 1, "instance_mismatch": 1, **cost})+ return 0+ all_success = all(bool(r.get("success")) for r in runs)+ deterministic = runs[0].get("state_sha") == runs[1].get("state_sha")+ ok = all_success and deterministic+ r = runs[0]+ num = lambda k: float(r.get(k) if r.get(k) is not None else -1) # noqa: E731+ out = {"success": int(ok), "replay_success": int(all_success), "deterministic": int(deterministic),+ "n_actions": int(len(acts)), "horizon": horizon, "fell": int(r.get("fell_at") is not None),+ "fell_at_step": num("fell_at"), "worst_lin_err": num("worst_lin_err"), "worst_yaw_err": num("worst_yaw_err"),+ "end_tilt_deg": num("tilt_deg"), "end_imu_height": num("imu_height"), "end_pose_angle_deg": num("pose_angle_deg"),+ "grader_error": 0,+ "video_rendered": 0, **cost}+ write(ok, out) # the verdict, before any video+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ try: # the video, for humans: it never changes the verdict+ if replay(a.instance, a.traj, os.path.join(LOG_DIR, "replay.mp4")).get("video"):+ write(ok, {**out, "video_rendered": 1})+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/tests/instance.json b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/tests/instance.jsonnew file mode 100644index 0000000000..dc3a670238--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/tests/instance.json@@ -0,0 +1,111 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1JoystickRoughTerrain",+ "seed": 1,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ -0.09635365009307861,+ 0.04889500141143799,+ 0.3499999940395355,+ 0.5138856768608093,+ 0.0,+ 0.0,+ 0.8578586578369141,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842+ ],+ "qvel0": [+ 0.043613314628601074,+ -0.24152767658233643,+ -0.45936477184295654,+ -0.09444129467010498,+ -0.01504206657409668,+ -0.4573014974594116,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 1.136733055114746,+ "vy": 0.16791878640651703,+ "wz": -0.7027067542076111+ },+ {+ "start_step": 17,+ "vx": 1.136733055114746,+ "vy": 0.0,+ "wz": -0.7027067542076111+ },+ {+ "start_step": 138,+ "vx": -1.078402042388916,+ "vy": -0.701647937297821,+ "wz": 0.0+ },+ {+ "start_step": 548,+ "vx": -1.078402042388916,+ "vy": 0.0,+ "wz": 0.7865484356880188+ },+ {+ "start_step": 594,+ "vx": 0.0,+ "vy": -0.35900041460990906,+ "wz": 0.7865484356880188+ },+ {+ "start_step": 611,+ "vx": 0.0,+ "vy": -0.35900041460990906,+ "wz": 0.0+ },+ {+ "start_step": 674,+ "vx": -0.03617405891418457,+ "vy": 0.0,+ "wz": -0.08692560344934464+ }+ ],+ "text": "Make the Unitree Go1 follow the joystick command schedule on rough terrain (a 20 x 20 m heightfield, up to 5 cm high) for the whole 20 s episode without falling over.",+ "facts": {+ "start_xy_m": [+ -0.096,+ 0.049+ ],+ "start_yaw_deg": 118.2,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.344,+ "reference_rows": 1000,+ "reference_worst_lin_err": 0.0788,+ "reference_worst_yaw_err": 0.1137+ },+ "state_sha": "4e94a33d805a",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.",+ "candidates_tried": 2+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/tests/rcb_quadruped.py b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/tests/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/tests/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/tests/test.sh b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/tests/test.shnew file mode 100755index 0000000000..1c3d2f767b--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-privileged/tests/test.sh@@ -0,0 +1,9 @@+#!/bin/bash+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in two fresh processes (the+# verdict), then a third that renders replay.mp4.+# Writes /logs/verifier/reward.txt (1/0) and reward.json (numeric fields, docs/PROTOCOL.md §2.6).+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/*+mkdir -p /logs/verifier+python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz 2> /logs/verifier/grade.logdiff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/README.md b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/README.mdnew file mode 100644index 0000000000..a58ecb8dc8--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/README.md@@ -0,0 +1,44 @@+# mujoco_playground_go1_joystick_rough_terrain-standard++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | standard (`eai-standard/2.2`) |+| Twin | `mujoco_playground_go1_joystick_rough_terrain-privileged` |+| Simulator / robot | `mujoco` / `unitree-go1` |+| Family / instance | `mujoco_playground/Go1JoystickRoughTerrain` / seed 1 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `Go1JoystickRoughTerrain` (Unitree Go1) on the same frozen instance as `mujoco_playground_go1_joystick_rough_terrain-privileged`: Make the Unitree Go1 follow the joystick command schedule on rough terrain (a 20 x 20 m heightfield, up to 5 cm high) for the whole 20 s episode without falling over.+For 20 s the robot gets a joystick command schedule (7 segments: planar velocity and yaw rate in its own frame) and must track it without falling over. The ground is a 20 x 20 m heightfield with bumps up to 5 cm. Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with only+the robot's own sensors and four cameras that follow it.++## Difficulty+Same instance and success check as `mujoco_playground_go1_joystick_rough_terrain-privileged`. In standard mode the agent loses resets, the simulator and+the world state: it sees camera images and proprioception (joints, IMU, foot contacts), acts in joint position chunks,+and gets one episode, so it has to close the loop on the robot's own sensors and recover from its own mistakes without+starting over.++## Reference solution+`solution/oracle_replay.py` streams the privileged reference's rows (`solution/oracle.npy`, 1000 rows, float32-exact)+through the client in `hold` chunks; it uses no privileged information at run time. The service's recorded trajectory+is then exactly the privileged reference, and the episode ends after the 1000 steps of the schedule, with success.++## Verification+The sim service judges the episode live and records every executed control step; the collect hook+(`environment/sim/finalize.sh`) ends the service, replays the recorded trajectory in two fresh processes and writes+`final.json`; `tests/grade.py` (separate sandbox, no network) passes iff the live check succeeded, both replays succeed,+and they end in the same state. Oracle: success, worst segment errors 0.079 m/s and 0.114 rad/s.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml`; MuJoCo Menagerie @ 1b86ece (`unitree_go1`); MuJoCo 3.3.7 on the CPU |+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); cameras `track`, `side`, `back`, `top` (they follow the robot) (320 x 240), the feet's kinematics in the trunk frame |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py`, as its privileged twin.diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/Dockerfile b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/Dockerfilenew file mode 100644index 0000000000..ed5eee3703--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/Dockerfile@@ -0,0 +1,9 @@+# Standard mode: the agent container has NO simulator and no Playground code, only Python and the client, on the shared+# pinned client base with the shared pins (scripts/eai_standard/client.env, client-requirements.txt).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY client-requirements.txt /tmp/client-requirements.txt+RUN pip install --no-cache-dir -r /tmp/client-requirements.txt+COPY rcb_client.py rcb1.py /opt/tools/+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/client-requirements.txt b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/client-requirements.txtnew file mode 100644index 0000000000..8aa73a968f--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/client-requirements.txt@@ -0,0 +1,11 @@+# Exact pins for what the standard agent container installs (and a verifier, if it installs anything): the closure of+# `pip install requests numpy pillow scipy`, the unpinned line of every standard task at 9eb18edf, resolved on+# 2026-10-01 in CLIENT_IMAGE (client.env: Python 3.12.14, pip 25.0.1). A change here is a shared-files PR.+certifi==2026.7.22+charset-normalizer==3.5.2+idna==3.20+numpy==2.5.3+pillow==12.3.0+requests==2.34.2+scipy==1.18.1+urllib3==2.8.0diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/docker-compose.yaml b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/docker-compose.yamlnew file mode 100644index 0000000000..8ec63c582e--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/docker-compose.yaml@@ -0,0 +1,23 @@+# Standard mode: the simulator runs in the `sim` sidecar (the agent cannot open it); the agent only reaches port 8000.+# No `expose`/`ports` on sim: under Harbor's egress control it shares main's network namespace (localhost:8000).+# CPU only: MuJoCo physics and rendering (EGL when a GPU is there, else OSMesa); no GPU reservation.+# Crash recovery (docs/STANDARD_MODE_2_2.md §13): run.sh exits non-zero when the service crashes, compose restarts the+# container (same container, same /data) and the service replays its journal into the same episode, never a reset.+services:+ main:+ depends_on: [sim]+ sim:+ image: ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+ volumes:+ - ./sim:/srv:ro+ working_dir: /tmp+ command: sh /srv/run.sh+ restart: on-failure:6 # N >= 3 (PROTOCOL §4.1); a resume continues the episode+ environment:+ RCB_INSTANCE: /srv/instance.json+ RCB_TOOL: /srv/rcb_quadruped.py+ RCB_DATA: /data+ RCB_WALL_CLOCK_S: "3600"+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in about a second+ PYTHONPATH: /srv+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction logdiff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/rcb1.py b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/rcb_client.py b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/rcb_client.pynew file mode 100644index 0000000000..aa25b0e050--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/rcb_client.py@@ -0,0 +1,211 @@+"""eai-standard/2.2 client (formerly rcb-limited/2.x) — the only thing a standard-mode agent gets (installed at+/opt/tools/rcb_client.py).++ from rcb_client import Robot+ r = Robot() # finds the service (sim:8000, then localhost:8000), waits for warm-up+ spec = r.spec() # actions, cameras (+ intrinsics, mounting), robot_spec, world, budget, kinematics+ obs = r.get_obs() # current frames: obs.last[cam] -> uint8 (H,W,3); obs.meta["proprio"]+ obs = r.get_obs(depth=True) # + obs.last_depth[cam] -> float32 (H,W) z-depth in metres, 0 = no reading+ res = r.submit("joint_position", A, dt=0.1) # A: (T, dim) rows dt apart; returns the execution video+ res = r.submit("ee_pose", P) # (T, dim) end-effector targets (see spec()["action_types"])+ res.video[cam] -> mp4 bytes res.frames[cam] -> uint8 (N,H,W,3) if video="frames"/"both" res.last[cam]+ res.proprio -> float32 (N, D), one row per frame (names: spec()["proprio_layout"]; res.group("tcp_pose"))+ res.frame_step -> int64 (N,) control step of each frame res.frame_time_s -> float64 (N,) simulated time+ res.extrinsic_cv[cam] -> float64 (N,3,4) world->camera per frame (res.meta["cameras"]: intrinsics + the last frame's pose)+ res = r.submit(..., depth="frames") # + res.depth[cam] -> float32 (N,H,W) metres, one per frame (1 mm steps)+ r.fk(q) # {"ok", "poses": {frame: [x,y,z, quaternion]}}: forward kinematics, no physics+ r.ik({frame: pose}, seed=q) # {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}: inverse kinematics+ res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, frames/<cam>/NNN.jpg, proprio.npy, depth, frame_meta.npz+ obs = r.get_obs(seconds=3, video="both") # hold the last command, let physics run 3 s, return the video+ r.status() # calls, control steps, done, reason, elapsed time++Nothing is put into your context automatically: what you look at, and where you store it, is your code's decision.++If a call fails with a connection error or a 5xx, the service may have crashed; it restarts and resumes the SAME episode+(never a reset) in the state after the last call it completed, which you may not have received. r.wait_ready() waits+until it answers again (resuming replays the episode so far: long episodes can take minutes); then check r.status()+before you continue (spec()["on_service_error"]).+"""+from __future__ import annotations+import json, os, pathlib, sys, time, zlib+import numpy as np+import requests+import rcb1++PROTOCOL = "eai-standard/2.2" # also talks to 2.0 / 2.1 services (they ignore depth and send no frame metadata)+ACCEPTED = ("eai-standard/2.", "rcb-limited/2.") # every 2.x service, under the protocol's current and former name+++class EpisodeOver(RuntimeError):+ pass+++def _decode_depth_frames(p: dict) -> np.ndarray:+ a = np.frombuffer(zlib.decompress(p["data"]), dtype="<u2").reshape(p["shape"])+ return a.astype(np.float32) / 1000.0+++class Result:+ """Decoded RCB1 response: meta (dict), video (cam -> mp4 bytes), frames (cam -> uint8 (N,H,W,3)), last (cam -> uint8+ (H,W,3)), last_depth (cam -> float32 (H,W) m), depth (cam -> float32 (N,H,W) m, one per frame), proprio (float32 (N,D)),+ frame_step (int64 (N,)), frame_time_s (float64 (N,)), extrinsic_cv (cam -> float64 (N,3,4)). save(dir) writes it out;+ show(cam, k) returns one frame; group(name) the proprio columns of one spec()["proprio_groups"] group. stopped: None,+ or why the service stopped the call early ("max_call_wall_s": it ran longer than spec()["max_call_wall_s"]); then+ meta["executed_rows"] < the rows sent, and meta["proprio"]["now"] is where the robot is."""+ def __init__(self, meta: dict, parts: dict, spec: dict | None = None):+ self.meta = meta; self.raw = parts; self._spec = spec or {}; self.stopped = meta.get("stopped")+ self.video, self.frames, self.last, self.last_depth, self.depth, self.extrinsic_cv = {}, {}, {}, {}, {}, {}+ self.proprio = None; self.frame_step = None; self.frame_time_s = None+ for name, p in parts.items():+ kind, data = p["kind"], p["data"]+ if name.startswith("video/") and kind == "mp4": self.video[name[6:]] = data+ elif name.startswith("frames/") and kind == "array": self.frames[name[7:]] = data+ elif name.startswith("last/") and kind == "array": self.last[name[5:]] = data+ elif name.startswith("last_depth/") and kind == "array": self.last_depth[name[11:]] = np.asarray(data, dtype=np.float32)+ elif name.startswith("depth_frames/") and p.get("codec") == "zlib": self.depth[name[13:]] = _decode_depth_frames(p)+ elif name.startswith("depth/") and kind == "array": self.depth[name[6:]] = np.asarray(data, dtype=np.float32) # 2.1 form+ elif name.startswith("extrinsic_cv/") and kind == "array": self.extrinsic_cv[name[13:]] = data+ elif name == "proprio": self.proprio = data+ elif name == "frame_step": self.frame_step = data+ elif name == "frame_time_s": self.frame_time_s = data++ @property+ def done(self) -> bool: return bool(self.meta.get("done"))++ def show(self, camera: str, k: int = -1) -> np.ndarray:+ if camera in self.frames: return self.frames[camera][k]+ return self.last[camera]++ def group(self, name: str, now: bool = False) -> np.ndarray:+ """Columns of proprio group `name` (spec()["proprio_groups"]): (N, n) over the frames, or (n,) of meta["proprio"]["now"]."""+ first, n = self._spec["proprio_groups"][name][:2]+ if now: return np.asarray(self.meta["proprio"]["now"], dtype=np.float64)[first:first + n]+ return self.proprio[:, first:first + n]++ def save(self, out_dir: str) -> str:+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ (out / "meta.json").write_text(json.dumps(self.meta, indent=1))+ for cam, b in self.video.items(): (out / f"{cam}.mp4").write_bytes(b)+ try:+ from PIL import Image+ for cam, img in self.last.items():+ (out / "last").mkdir(exist_ok=True); Image.fromarray(np.ascontiguousarray(img)).save(out / "last" / f"{cam}.jpg", quality=90)+ for cam, arr in self.frames.items():+ d = out / "frames" / cam; d.mkdir(parents=True, exist_ok=True)+ for i, f in enumerate(arr): Image.fromarray(np.ascontiguousarray(f)).save(d / f"{i:03d}.jpg", quality=85)+ except ImportError:+ for cam, img in self.last.items(): np.save(out / f"last_{cam}.npy", img)+ for cam, arr in self.frames.items(): np.save(out / f"frames_{cam}.npy", arr)+ for cam, arr in self.last_depth.items(): np.save(out / f"last_depth_{cam}.npy", arr)+ for cam, arr in self.depth.items(): np.savez_compressed(out / f"depth_{cam}.npz", depth_mm=np.rint(arr * 1000).astype(np.uint16))+ if self.proprio is not None: np.save(out / "proprio.npy", self.proprio)+ if self.frame_step is not None:+ np.savez(out / "frame_meta.npz", frame_step=self.frame_step, frame_time_s=self.frame_time_s,+ **{f"extrinsic_cv/{c}": e for c, e in self.extrinsic_cv.items()})+ return str(out)+++class Robot:+ def __init__(self, base: str | None = None, timeout: float = 600.0):+ cands = [base or os.environ.get("SIM_URL"), "http://sim:8000", "http://localhost:8000"]+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ for b in [c for c in cands if c]:+ try:+ r = requests.get(b + "/spec", timeout=(5, 30))+ if r.status_code == 503: last = "warming up"; break+ r.raise_for_status(); self.base = b; self._spec = r.json()+ if not str(self._spec.get("protocol", "")).startswith(ACCEPTED):+ raise RuntimeError(f"not a 2.x service: protocol {self._spec.get('protocol')!r}")+ return+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(2)+ raise RuntimeError(f"sim service unavailable: {last}")++ def spec(self) -> dict:+ return self._spec++ def _post(self, path: str, meta: dict, parts: list, timeout: float) -> Result:+ body = rcb1.encode(meta, parts)+ r = requests.post(self.base + path, data=body, headers={"Content-Type": "application/x-rcb1"}, timeout=(5, timeout))+ if r.status_code == 409:+ raise EpisodeOver(r.json().get("reason") if r.headers.get("Content-Type", "").startswith("application/json") else "episode finished")+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ m, p = rcb1.decode(r.content); return Result(m, p, self._spec)++ def _common(self, cameras, video_fps, depth, include_depth) -> dict:+ cams = list(cameras) if cameras is not None else self._spec.get("default_cameras")+ if depth is None or depth is False: depth = "frames" if include_depth else "none"+ elif depth is True: depth = "last"+ m = {"cameras": cams, "video_fps": None if video_fps is None else int(video_fps), "depth": depth}+ return {k: v for k, v in m.items() if v is not None}++ def submit(self, action_type: str, actions, dt: float | None = None, interpolate: str = "linear", cameras=None,+ video_fps: int | None = None, video: str = "mp4", depth=None, include_depth: bool = False, note: str = "") -> Result:+ """Execute a chunk of low-level actions (T, dim); see spec()['action_types'] for dims, layouts, limits and semantics.+ dt defaults to one control period, cameras to spec()['default_cameras']; depth: None | True (= "last") | "frames"."""+ a = np.asarray(actions, dtype=np.float32)+ if a.ndim == 1: a = a[None, :]+ if dt is None and self._spec.get("control_hz"): dt = 1.0 / float(self._spec["control_hz"])+ meta = {"type": action_type, "interpolate": interpolate, "video": video, "note": note,+ **({} if dt is None else {"dt": float(dt)}), **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/submit", meta, [rcb1.array_part("actions", a)], timeout=1800)+ if res.stopped:+ print(f"[rcb_client] the service stopped this call early ({res.stopped}): {res.meta.get('executed_rows')} of {len(a)} rows "+ "executed; meta['proprio']['now'] is where the robot is", file=sys.stderr)+ return res++ def get_obs(self, cameras=None, seconds: float = 0.0, video_fps: int | None = None, depth=None, include_depth: bool = False,+ video: str = "frames") -> Result:+ """Current frames (seconds=0, free) or hold the last command and watch for `seconds` (returns the video).+ depth: None | True (= "last": the last frame's depth) | "frames" (one depth map per frame)."""+ meta = {"seconds": float(seconds), "video": video, **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/observe", meta, [], timeout=600)+ if res.stopped:+ print(f"[rcb_client] the service stopped this watch early ({res.stopped}) after {res.meta.get('control_steps_watch')} control "+ "steps", file=sys.stderr)+ return res++ def status(self) -> dict:+ r = requests.get(self.base + "/status", timeout=(5, 60)); r.raise_for_status(); return r.json()++ def wait_ready(self, timeout: float = 3600.0) -> dict:+ """After a connection error: wait until the service answers GET /status again (it resumes the same episode after a+ crash), then return the status. Raises RuntimeError after `timeout` seconds."""+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ try:+ return self.status()+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(5)+ raise RuntimeError(f"sim service did not come back within {timeout:.0f} s: {last}")++ def kinematics(self, body: dict) -> dict:+ """POST /kinematics (stateless: never moves the robot, never advances time). Raises ValueError on a bad request."""+ r = requests.post(self.base + "/kinematics", json=body, timeout=(5, 120))+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ return r.json()++ def fk(self, q, links=None, base_pose=None) -> dict:+ """Forward kinematics: q in spec()['kinematics']['joint_names'] order -> {"ok", "frame", "poses": {link: [x,y,z, quat]}}+ (quaternion order spec()['world']['quaternion_order']; a mobile robot answers in its base frame unless base_pose is given)."""+ body = {"op": "fk", "q": [float(v) for v in np.asarray(q).reshape(-1)]}+ if links is not None: body["links"] = list(links)+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)++ def ik(self, targets: dict, seed=None, base_pose=None, **opts) -> dict:+ """Inverse kinematics: {frame: [x,y,z, quat]} (frames from spec()['kinematics']['ik_targets']) and an optional seed q ->+ {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}. opts: tol_pos_m, tol_rot_rad, max_iters."""+ body = {"op": "ik", "targets": {k: [float(v) for v in p] for k, p in targets.items()}, **opts}+ if seed is not None: body["seed"] = [float(v) for v in np.asarray(seed).reshape(-1)]+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/finalize.sh b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/finalize.shnew file mode 100755index 0000000000..02048ddc74--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/finalize.sh@@ -0,0 +1,80 @@+#!/bin/sh+# [[verifier.collect]] hook, run inside the `sim` sidecar once Harbor has stopped the agent's container.+# 1. `rcb_limited.py end` (docs/STANDARD_MODE_2_2.md §13.3): SIGUSR1 to the service, which ends the episode if the+# agent had not (reason "timeout"), writes trajectory.npz + episode.json (live verdict, final-state hash) and exits.+# It exits 2 when final.json already holds the verdict (the service gave up after crashes): that verdict stays.+# 2. replay the trajectory from the frozen instance in TWO fresh processes (`rcb_quadruped.py replay`, the privileged+# verifier's replay): determinism = fresh process == fresh process; live_matches_replay = live == replay.+# 3. merge everything into final.json, the only thing the verifier sandbox grades;+# 4. a third replay renders replay.mp4, after the verdict is on disk (it never changes it).+set -u+DATA="${RCB_DATA:-/data}"; TOOL="${RCB_TOOL:?}"; INSTANCE="${RCB_INSTANCE:?}"+python /srv/rcb_limited.py end "$DATA" --timeout "${RCB_COLLECT_END_TIMEOUT_S:-900}"; rc=$?+if [ "$rc" = 2 ]; then+ echo "[finalize] final.json already holds the verdict; no replay"; exit 0+fi+if [ "$rc" != 0 ]; then+ echo "[finalize] the service did not end and dump the episode in time (rc $rc): an infrastructure failure"+ python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data"); p = os.path.join(d, "final.json")+try:+ out = json.load(open(p))+except Exception:+ out = {}+out.update({"finalized": True, "success": False, "replay_success": False, "deterministic": False, "infra_error": 1,+ "error": "collect hook: the sim service did not end and dump the episode in time"})+json.dump(out, open(p, "w"))+print(json.dumps(out))+PY+ exit 0+fi+replay() { # <n> [--video FILE]: one replay in a fresh process, its result in $DATA/replay<n>.json+ n=$1; shift+ RCB_SESSION_LOG= python "$TOOL" replay --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --out "$DATA/replay$n.json" \+ "$@" > /dev/null 2> "$DATA/replay$n.log"+ echo "[finalize] replay $n exit $?"+}+echo "[finalize] episode dumped; replaying twice in fresh processes"+rm -f "$DATA/replay1.json" "$DATA/replay2.json" "$DATA/replay3.json"+replay 1+replay 2+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+def result(name):+ try:+ v = json.load(open(os.path.join(d, name)))+ except (OSError, ValueError):+ return {}+ return v if isinstance(v, dict) else {}+out = {"replay_success": False, "deterministic": False, "video": False}+try:+ out.update(json.load(open(os.path.join(d, "episode.json"))))+except Exception as exc:+ out["error"] = f"no episode.json: {exc!r}"+a, b = result("replay1.json"), result("replay2.json")+out["replay_success"] = bool(a.get("success")) and bool(b.get("success"))+out["replay_sha"], out["replay_sha2"] = a.get("state_sha"), b.get("state_sha")+out["deterministic"] = bool(a.get("state_sha")) and a.get("state_sha") == b.get("state_sha")+out["live_matches_replay"] = bool(a.get("state_sha")) and a.get("state_sha") == out.get("live_sha")+if not (a.get("state_sha") and b.get("state_sha")): # a replay process died (it crashed or timed out): not the agent's 0+ out.update({"replay_failed": 1, "infra_error": 1,+ "error": "a replay process gave no result (replay1.log / replay2.log)"})+elif not (a.get("instance_ok") and b.get("instance_ok")): # the image no longer builds the frozen start: not the agent's 0+ out.update({"instance_mismatch": 1, "infra_error": 1, "error": "a replay did not start in the instance's t = 0 state"})+out["finalized"] = True+json.dump(out, open(os.path.join(d, "final.json"), "w"))+print(json.dumps(out))+PY+replay 3 --video "$DATA/replay.mp4"+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+try:+ shown = json.load(open(os.path.join(d, "replay3.json"))).get("video")+except (OSError, ValueError):+ shown = False+if shown:+ p = os.path.join(d, "final.json"); out = json.load(open(p)); out["video"] = True; json.dump(out, open(p, "w"))+PYdiff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/instance.json b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/instance.jsonnew file mode 100644index 0000000000..dc3a670238--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/instance.json@@ -0,0 +1,111 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "Go1JoystickRoughTerrain",+ "seed": 1,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ -0.09635365009307861,+ 0.04889500141143799,+ 0.3499999940395355,+ 0.5138856768608093,+ 0.0,+ 0.0,+ 0.8578586578369141,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ 0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842,+ -0.10000000149011612,+ 0.8999999761581421,+ -1.7999999523162842+ ],+ "qvel0": [+ 0.043613314628601074,+ -0.24152767658233643,+ -0.45936477184295654,+ -0.09444129467010498,+ -0.01504206657409668,+ -0.4573014974594116,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 1.136733055114746,+ "vy": 0.16791878640651703,+ "wz": -0.7027067542076111+ },+ {+ "start_step": 17,+ "vx": 1.136733055114746,+ "vy": 0.0,+ "wz": -0.7027067542076111+ },+ {+ "start_step": 138,+ "vx": -1.078402042388916,+ "vy": -0.701647937297821,+ "wz": 0.0+ },+ {+ "start_step": 548,+ "vx": -1.078402042388916,+ "vy": 0.0,+ "wz": 0.7865484356880188+ },+ {+ "start_step": 594,+ "vx": 0.0,+ "vy": -0.35900041460990906,+ "wz": 0.7865484356880188+ },+ {+ "start_step": 611,+ "vx": 0.0,+ "vy": -0.35900041460990906,+ "wz": 0.0+ },+ {+ "start_step": 674,+ "vx": -0.03617405891418457,+ "vy": 0.0,+ "wz": -0.08692560344934464+ }+ ],+ "text": "Make the Unitree Go1 follow the joystick command schedule on rough terrain (a 20 x 20 m heightfield, up to 5 cm high) for the whole 20 s episode without falling over.",+ "facts": {+ "start_xy_m": [+ -0.096,+ 0.049+ ],+ "start_yaw_deg": 118.2,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.344,+ "reference_rows": 1000,+ "reference_worst_lin_err": 0.0788,+ "reference_worst_yaw_err": 0.1137+ },+ "state_sha": "4e94a33d805a",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.",+ "candidates_tried": 2+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/rcb1.py b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/rcb_limited.py b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/rcb_limited.pynew file mode 100644index 0000000000..1ce1171787--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/rcb_limited.py@@ -0,0 +1,930 @@+"""eai-standard/2.2 (formerly rcb-limited/2.2): the HTTP layer, the protocol helpers and the crash recovery that every+2.2 sim service shares (docs/STANDARD_MODE_2_2.md; the 2.1 base is docs/LIMITED_MODE_PROTOCOL.md).++The source is scripts/eai_standard/rcb_limited.py; the generators copy it unchanged into every standard task's+environment/sim/ (ci_checks/check-tooling-identity.sh). A service keeps its simulator to itself (scene, action+execution, cameras, kinematic model) and hands this module plain callables:++ import rcb_limited as L+ EP = L.Episode(DATA, dim=N, resume="exact") # before the scene is built; "approx" for a nondeterministic simulator+ EP.startup() # start count, back-off after failed starts, startup watchdog+ S = <build the scene>; EP.scene_built() # the watchdog stands down+ def ctrl_step(a, rec): # every executed control step+ S.step(a); stop = EP.journal(a); rec.tick(); return E["done"] or stop+ rec = L.Recorder(cams, every, grab, proprio_row, extrinsics, clock, depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+ rec.tick(force=True) # first frame (before the chunk / watch)+ ...; rec.tick(); ... # after every control step: a frame every `every` steps+ rec.tick(force=True, last=True) # last frame (+ its depth)+ parts = rec.parts(video, fps) # RCB1 parts: video/ frames/ last/ extrinsic_cv/ last_depth/ depth_frames/ depth/ proprio frame_*+ S.record_start()+ EP.begin(state=E, step=S.step, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, start_event={...}, on_end=end_fn)+ L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics,+ status=status, on_submit_error=lambda exc: finish("error"), log=EP.log,+ episode=EP, state_sha=S.state_sha, proprio=proprio_row))++ grab(cams, want_depth) -> ({cam: uint8 (H,W,3)}, {cam: float32 (H,W) z-depth in metres, 0 = no reading})+ extrinsics(cams) -> {cam: (3,4) world -> camera, OpenCV axes (x right, y down, z forward)}+ proprio_row() -> float32 (len(spec["proprio_layout"]),)+ clock() -> int, control steps since the episode start (the frame's step index)+ do_kinematics(req) -> dict; `req` is parse_kinematics(body, spec["kinematics"]); it must never step physics++None of the callables may step physics. check_spec(SPEC) runs in serve(): a service whose /spec misses a 2.2 field, or+carries a field the protocol forbids (segmentation, object identities or sizes, physical parameters), does not start.+Crash recovery (class Episode; PROTOCOL §4.7): every executed control step is journaled, every completed call+checkpointed (rows, state hash, the robot's proprio row); after a crash compose restarts the container and the service+replays the journal and continues the SAME episode, never a reset. `python rcb_limited.py end <data dir>` is the shared+first half of a collect hook."""+from __future__ import annotations+import faulthandler, json, math, os, re, select, signal, socket, sys, tempfile, threading, time, traceback, zlib+from http.server import BaseHTTPRequestHandler, HTTPServer+from typing import Any, Callable++import numpy as np++import rcb1++PROTOCOL = "eai-standard/2.2"+COMPAT = ["rcb-limited/2.0", "rcb-limited/2.1", "eai-standard/2.1"] # requests written for these are served unchanged+MAX_BODY = 64 * 1024 * 1024+MAX_RESP = 256 * 1024 * 1024+DEPTH_MODES = ("none", "last", "frames")+DEPTH_MAX_M = 65.535 # uint16 millimetres; a farther surface reads 0 (no reading)+DEPTH_NOISE = os.environ.get("RCB_DEPTH_NOISE", "off").strip().lower() # off | realsense (as rcb-limited/2.1)+_RNG = np.random.default_rng(int(os.environ.get("RCB_DEPTH_NOISE_SEED", "0")))+PROPRIO_GROUPS_REQUIRED = ("joint_pos", "joint_vel", "gripper_opening", "tcp_pose", "joint_effort")+PART_PREFIXES = ("video/", "frames/", "last/", "last_depth/", "depth_frames/", "depth/", "extrinsic_cv/")+PART_NAMES = ("proprio", "frame_step", "frame_time_s")+++# ---------------------------------------------------------------- depth+def depth_mode(meta: dict) -> str:+ """The request's depth mode: "none" | "last" | "frames" (2.2 field `depth`), or "legacy" for a 2.0/2.1 request that+ sets `include_depth: true` and no `depth` (answered as 2.1 did: `depth/<cam>` float16 (N,H,W) metres)."""+ d = meta.get("depth")+ if d is None or d is False:+ return "legacy" if meta.get("include_depth") is True else "none"+ if d is True:+ return "last"+ if isinstance(d, str) and d in DEPTH_MODES:+ return d+ raise ValueError(f"depth must be one of {'|'.join(DEPTH_MODES)} (got {d!r})")+++def clean_depth(z) -> np.ndarray:+ """float32 z-depth in metres: non-finite, negative and beyond-range pixels read 0 (no reading); the optional+ RCB_DEPTH_NOISE=realsense model (sigma = 2 mm + 2.5 mm * z^2, 1 % dropouts) is applied here, after rendering, so it+ never touches physics."""+ z = np.asarray(z, dtype=np.float32).copy()+ if z.ndim == 3 and z.shape[-1] == 1:+ z = z[..., 0]+ bad = ~np.isfinite(z) | (z <= 0) | (z > DEPTH_MAX_M)+ z[bad] = 0.0+ if DEPTH_NOISE == "realsense":+ valid = z > 0+ z = z + _RNG.normal(0.0, 1.0, z.shape).astype(np.float32) * (0.002 + 0.0025 * z * z)+ z[_RNG.random(z.shape) < 0.01] = 0.0+ z[~valid] = 0.0+ z[(z < 0) | (z > DEPTH_MAX_M)] = 0.0+ return z.astype(np.float32)+++def depth_frames_part(name: str, stack: np.ndarray) -> tuple[str, str, bytes, dict]:+ """(N,H,W) metres -> an RCB1 "bytes" part: zlib of C-order uint16 millimetres (0 = no reading). Clients that do not+ know it keep the raw bytes and ignore it; rcb_client decodes it back to float32 metres."""+ mm = np.rint(np.asarray(stack, dtype=np.float64) * 1000.0)+ mm[(mm < 0) | (mm > 65535)] = 0+ a = np.ascontiguousarray(mm.astype("<u2"))+ return (name, "bytes", zlib.compress(a.tobytes(), 1), {"codec": "zlib", "dtype": "uint16", "shape": list(a.shape), "unit": "mm"})+++def encode_mp4(frames: np.ndarray, fps: int) -> bytes:+ """H.264 mp4 (yuv420p, faststart) of uint8 (N,H,W,3) frames: the same encoding every 2.0 service used."""+ import imageio.v2 as imageio+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tf:+ path = tf.name+ try:+ with imageio.get_writer(path, format="FFMPEG", mode="I", fps=fps, codec="libx264", macro_block_size=1,+ output_params=["-movflags", "+faststart", "-pix_fmt", "yuv420p"]) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ return open(path, "rb").read()+ finally:+ try:+ os.unlink(path)+ except OSError:+ pass+++# ---------------------------------------------------------------- recording what the cameras see during one call+class Recorder:+ """Frames of the requested cameras every `every` clock ticks, plus forced first/last frames; for every frame the+ proprio row, the clock (step index), each camera's extrinsics and, if asked, its depth. All arrays share one frame+ axis N: frames/<cam>, the mp4's frames, proprio, frame_step, frame_time_s, extrinsic_cv/<cam>, depth_frames/<cam>."""++ def __init__(self, cameras, every: int, grab: Callable, proprio_row: Callable, extrinsics: Callable, clock: Callable,+ depth: str = "none", clock_hz: float = 1.0):+ if depth not in DEPTH_MODES + ("legacy",):+ raise ValueError(f"bad depth mode {depth!r}")+ self.cams = list(cameras); self.every = max(1, int(every)); self.mode = depth; self.hz = float(clock_hz)+ self._grab, self._prop, self._ext, self._clock = grab, proprio_row, extrinsics, clock+ self.frames: dict = {c: [] for c in self.cams}; self.depth: dict = {c: [] for c in self.cams}+ self.ext: dict = {c: [] for c in self.cams}; self.last_depth: dict = {}+ self.prop: list = []; self.steps: list = []; self.n = 0; self.missing = 0++ def tick(self, force: bool = False, last: bool = False) -> None:+ if force or last or self.n % self.every == 0:+ self._capture(last)+ self.n += 1++ def _capture(self, last: bool) -> None:+ want = self.mode in ("frames", "legacy") or (last and self.mode == "last")+ rgb, dep = self._grab(self.cams, want)+ ext = self._ext(self.cams)+ for c in self.cams:+ img = rgb.get(c)+ if img is not None:+ img = np.ascontiguousarray(np.asarray(img)[..., :3].astype(np.uint8))+ else: # a camera that failed to render: a black frame (sized in parts()) keeps one frame axis+ self.missing += 1+ self.frames[c].append(img)+ e = ext.get(c)+ self.ext[c].append(np.full((3, 4), np.nan) if e is None else np.asarray(e, dtype=np.float64).reshape(3, 4))+ if want:+ d = dep.get(c)+ if d is None:+ d = np.zeros(img.shape[:2] if img is not None else (1, 1), np.float32)+ else:+ d = clean_depth(d)+ if img is not None and d.shape != img.shape[:2]:+ raise RuntimeError(f"depth of {c} is {d.shape}, its RGB {img.shape[:2]}: they must be pixel-aligned")+ if self.mode in ("frames", "legacy"):+ self.depth[c].append(d)+ if last or self.mode == "frames":+ self.last_depth[c] = d+ self.prop.append(np.asarray(self._prop(), dtype=np.float32).reshape(-1))+ self.steps.append(int(self._clock()))++ def parts(self, video: str, fps: int) -> list:+ if self.mode == "last" and not self.last_depth and self.prop: # no last=True tick: the state has not moved since+ _, dep = self._grab(self.cams, True)+ self.last_depth = {c: clean_depth(dep[c]) for c in self.cams if c in dep}+ out = []+ for c in self.cams:+ good = [f for f in self.frames[c] if f is not None]+ hw = good[-1].shape[:2] if good else (1, 1)+ if len(good) < len(self.frames[c]):+ self.frames[c] = [f if f is not None else np.zeros(hw + (3,), np.uint8) for f in self.frames[c]]+ self.depth[c] = [d if d.shape == hw else np.zeros(hw, np.float32) for d in self.depth[c]]+ if c in self.last_depth and self.last_depth[c].shape != hw:+ self.last_depth[c] = np.zeros(hw, np.float32)+ fr = np.stack(self.frames[c]) if self.frames[c] else np.zeros((0, 1, 1, 3), np.uint8)+ if video in ("mp4", "both") and len(fr):+ out.append((f"video/{c}", "mp4", encode_mp4(fr, fps), {"fps": fps, "n": int(len(fr))}))+ if video in ("frames", "both"):+ out.append(rcb1.array_part(f"frames/{c}", fr))+ if len(fr):+ out.append(rcb1.array_part(f"last/{c}", fr[-1]))+ out.append(rcb1.array_part(f"extrinsic_cv/{c}", np.stack(self.ext[c]) if self.ext[c] else np.zeros((0, 3, 4))))+ if self.mode in ("last", "frames") and c in self.last_depth:+ out.append(rcb1.array_part(f"last_depth/{c}", self.last_depth[c]))+ if self.mode == "frames" and self.depth[c]:+ out.append(depth_frames_part(f"depth_frames/{c}", np.stack(self.depth[c])))+ if self.mode == "legacy" and self.depth[c]:+ out.append(rcb1.array_part(f"depth/{c}", np.stack(self.depth[c]).astype(np.float16)))+ out.append(rcb1.array_part("proprio", np.stack(self.prop) if self.prop else np.zeros((0, 0), np.float32)))+ st = np.asarray(self.steps, dtype=np.int64)+ out.append(rcb1.array_part("frame_step", st))+ out.append(rcb1.array_part("frame_time_s", st.astype(np.float64) / self.hz))+ return out+++def encode_response(meta: dict, parts: list, max_bytes: int = MAX_RESP) -> bytes:+ """The RCB1 body; over `max_bytes` the per-frame depth goes first, then the raw frames (mp4, last frames, last+ depth, proprio and the per-frame arrays always stay), and meta["degraded"] says what was dropped."""+ body = rcb1.encode(meta, parts)+ dropped = []+ for prefixes in (("depth_frames/", "depth/"), ("frames/",)):+ if len(body) <= max_bytes:+ break+ keep = [p for p in parts if not p[0].startswith(prefixes)]+ if len(keep) < len(parts):+ parts = keep; dropped += [x.rstrip("/") for x in prefixes]+ body = rcb1.encode({**meta, "degraded": f"response over {max_bytes} bytes: {', '.join(dropped)} dropped"}, parts)+ return body+++# ---------------------------------------------------------------- kinematics+def _vec(x, n: int, what: str) -> list:+ a = np.asarray(x, dtype=np.float64).reshape(-1) if x is not None else None+ if a is None or a.size != n or not np.all(np.isfinite(a)):+ raise ValueError(f"{what} must be {n} finite numbers")+ return a.tolist()+++def _pose(x, what: str) -> list:+ p = _vec(x, 7, what)+ nq = math.sqrt(sum(v * v for v in p[3:]))+ if nq < 1e-6:+ raise ValueError(f"{what}: quaternion has zero norm")+ return p[:3] + [v / nq for v in p[3:]]+++def parse_kinematics(body: dict, kin: dict) -> dict:+ """Validate a /kinematics request against spec["kinematics"] (ValueError -> 400). Returns+ {"op": "fk", "q", "links", "base_pose"} or {"op": "ik", "targets": {frame: pose7}, "seed", "base_pose", "tol_pos_m",+ "tol_rot_rad", "max_iters"}; poses are x y z + a unit quaternion in the spec's order; q follows kin["joint_names"]."""+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object")+ op = body.get("op"); n = len(kin["joint_names"])+ base = None+ if body.get("base_pose") is not None:+ if kin.get("frame") != "base":+ raise ValueError("base_pose is only accepted by a mobile robot (spec kinematics.frame == 'base')")+ base = _pose(body["base_pose"], "base_pose")+ if op == "fk":+ links = body.get("links") or list(kin["links"])+ if not isinstance(links, list) or any(l not in kin["links"] for l in links):+ raise ValueError(f"links must be a list of names from spec kinematics.links: {kin['links']}")+ return {"op": "fk", "q": _vec(body.get("q"), n, "q"), "links": links, "base_pose": base}+ if op == "ik":+ tg = body.get("targets")+ if not isinstance(tg, dict) or not tg or any(k not in kin["ik_targets"] for k in tg):+ raise ValueError(f"targets must map frames from spec kinematics.ik_targets {kin['ik_targets']} to poses")+ ik = kin.get("ik", {})+ seed = None if body.get("seed") is None else _vec(body["seed"], n, "seed")+ tol_p = float(body.get("tol_pos_m", ik.get("tol_pos_m", 0.005)))+ tol_r = float(body.get("tol_rot_rad", ik.get("tol_rot_rad", 0.05)))+ it = int(body.get("max_iters", ik.get("max_iters", 200)))+ if not (1e-5 <= tol_p <= 0.5 and 1e-4 <= tol_r <= 3.2 and 1 <= it <= 5000):+ raise ValueError("tol_pos_m in [1e-5, 0.5], tol_rot_rad in [1e-4, 3.2], max_iters in [1, 5000]")+ return {"op": "ik", "targets": {k: _pose(v, f"targets[{k}]") for k, v in tg.items()}, "seed": seed, "base_pose": base,+ "tol_pos_m": tol_p, "tol_rot_rad": tol_r, "max_iters": it}+ raise ValueError("op must be 'fk' or 'ik'")+++def fk_response(poses: dict, frame: str) -> dict:+ return {"ok": True, "op": "fk", "frame": frame, "poses": {k: [float(v) for v in np.asarray(p, dtype=np.float64).reshape(7)] for k, p in poses.items()}}+++def ik_response(q, ok: bool, errors: dict, frame: str, note: str | None = None) -> dict:+ """errors: {frame: (position error m, rotation error rad)} of the returned q (None / non-finite -> null: no solution)."""+ fin = lambda v: float(v) if v is not None and math.isfinite(float(v)) else None # noqa: E731+ out = {"ok": bool(ok), "op": "ik", "frame": frame, "q": None if q is None else [float(v) for v in np.asarray(q).reshape(-1)],+ "error": {k: {"pos_m": fin(e[0]), "rot_rad": fin(e[1])} for k, e in errors.items()}}+ if note:+ out["note"] = note+ return out+++def quat_angle(q1, q2) -> float:+ """Rotation angle (rad) between two unit quaternions of the same order."""+ d = abs(float(np.dot(np.asarray(q1, dtype=np.float64), np.asarray(q2, dtype=np.float64))))+ return 2.0 * math.acos(min(1.0, d))+++# ---------------------------------------------------------------- /spec self-check+FORBIDDEN_KEY = re.compile(r"mask|segment|semantic(?!s$)|instance_?id|bbox|bounding|categor|object|\bobj_|label|mass|friction|"+ r"restitution|inertia|density|damping|stiffness", re.I)+GAIN_PATHS = ("robot_spec.controller",) # joint drive gains (stiffness, damping) are the robot's own, and allowed there+POSITION_KEY = re.compile(r"(?:^|_)(?:pos|position|positions|pose|poses|origin|location|coords?|coordinates|world|translation)(?:_|$)|"+ r"(?:^|_)cent(?:er|re)s?(?:_|$)|(?:^|_)xyz?$|(?:^|_)(?:top|surface|floor|table|plane|height|elevation)?_?z$", re.I)+WORLD_TEXT = re.compile(r"\bworld\s+[xyz]\s*=", re.I)+COORDS = re.compile(r"\(\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*(?:,\s*-?\d+(?:\.\d+)?\s*)?\)")+++def world_text(s: str) -> bool:+ """A text that gives a world coordinate: a pixel-to-world formula, or a coordinate tuple with a decimal point that is+ not the robot's own pose ("robot base at (0, 0, 1.08)" stays)."""+ return bool(WORLD_TEXT.search(s)) or any("." in m.group(0) and not re.search(r"base|robot|origin", s[max(0, m.start() - 40):m.start()], re.I)+ for m in COORDS.finditer(s))+CONVENTIONS = {"static.floor_z": 0.0} # BEHAVIOR: the floor is the plane z = 0 (the world frame's definition)+++def static_positions(obj: Any, path: str = "static") -> list[str]:+ """Paths in /spec static that say WHERE something is (keys naming positions, heights, centres; texts with world+ coordinates). Names, inventories, sizes and colours may stay in static; positions never (docs § Never provided)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}"+ if POSITION_KEY.search(str(k)) and CONVENTIONS.get(p, object()) != v:+ out.append(p)+ else:+ out += static_positions(v, p)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += static_positions(v, f"{path}[{i}]")+ elif isinstance(obj, str) and world_text(obj):+ out.append(path)+ return out+++SPEC_REQUIRED = ("protocol", "protocol_compat", "simulator", "robot", "task_text", "control_hz", "cameras", "default_cameras",+ "action_types", "proprio_layout", "proprio_groups", "static", "world", "budget", "robot_spec", "kinematics", "depth")+++def forbidden_keys(obj: Any, path: str = "", skip: tuple = ()) -> list[str]:+ """Key paths that name something the protocol never provides (key paths in `skip` are not searched)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}" if path else str(k)+ if p in skip:+ continue+ if FORBIDDEN_KEY.search(str(k)) and not (re.search(r"damping|stiffness", str(k), re.I) and p.startswith(GAIN_PATHS)):+ out.append(p)+ out += forbidden_keys(v, p, skip)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += forbidden_keys(v, f"{path}[{i}]", skip)+ return out+++def check_spec(spec: dict) -> None:+ """Raise if /spec is not a complete 2.2 spec or names anything forbidden (run at startup, before binding :8000)."""+ miss = [k for k in SPEC_REQUIRED if k not in spec]+ if miss:+ raise RuntimeError(f"/spec misses {miss}")+ if spec["protocol"] != PROTOCOL:+ raise RuntimeError(f"/spec protocol {spec['protocol']!r} != {PROTOCOL}")+ bad = forbidden_keys(spec, skip=())+ if bad:+ raise RuntimeError(f"/spec names forbidden fields: {bad}")+ pos = static_positions(spec["static"])+ if pos:+ raise RuntimeError(f"/spec static says where things are (never provided): {pos}")+ lay = spec["proprio_layout"]+ if len(set(lay)) != len(lay):+ raise RuntimeError("proprio_layout names are not unique")+ for g in PROPRIO_GROUPS_REQUIRED:+ if g not in spec["proprio_groups"]:+ raise RuntimeError(f"proprio_groups misses {g}")+ for g, (first, n, _meaning) in spec["proprio_groups"].items():+ if not (0 <= first and first + n <= len(lay)):+ raise RuntimeError(f"proprio group {g} [{first}, +{n}) outside the {len(lay)} columns")+ kin = spec["kinematics"]+ for k in ("endpoint", "joint_names", "frame", "quaternion_order", "links", "tcp_frames", "ee_frames", "ik_targets"):+ if k not in kin:+ raise RuntimeError(f"kinematics misses {k}")+ if any(j not in lay for j in kin["joint_names"]):+ raise RuntimeError("kinematics.joint_names must be proprio_layout columns (the measured joint positions)")+ if any(f not in kin["links"] for f in list(kin["tcp_frames"]) + list(kin["ee_frames"]) + list(kin["ik_targets"])):+ raise RuntimeError("kinematics tcp_frames / ee_frames / ik_targets must be listed in kinematics.links")+ if spec["proprio_groups"]["tcp_pose"][1] != 7 * len(kin["tcp_frames"]):+ raise RuntimeError("proprio group tcp_pose must hold 7 columns per kinematics.tcp_frames entry")+ for c, cam in spec["cameras"].items():+ for k in ("rgb", "depth", "mounted", "resolution", "intrinsic_cv", "mount"):+ if k not in cam:+ raise RuntimeError(f"cameras.{c} misses {k}")+ if cam["mount"].get("type") not in ("static", "link"):+ raise RuntimeError(f"cameras.{c}.mount.type must be static|link")+ if any(c not in spec["cameras"] for c in spec["default_cameras"]):+ raise RuntimeError("default_cameras must be cameras")+++# ---------------------------------------------------------------- crash recovery (PROTOCOL §4.7; docs/STANDARD_MODE_2_2.md)+MAX_RESUMES = int(os.environ.get("RCB_MAX_RESUMES", "2"))+STARTUP_TIMEOUT_S = float(os.environ.get("RCB_STARTUP_TIMEOUT_S", "900")) # a task with a slower scene build sets more+MAX_CALL_WALL_S = float(os.environ.get("RCB_MAX_CALL_WALL_S", "900")) # < the client's 1800 s /submit read timeout+RESUME_MAX_DEV_M = float(os.environ.get("RCB_RESUME_MAX_DEV_M", "0.05")) # approx resumes: the gross-divergence guard+ON_SERVICE_ERROR = ("a connection error means the service crashed: it restarts and resumes the SAME episode (never a reset) "+ "in the state after the last call it completed, which you may not have received. Wait until GET /status "+ "answers again (rcb_client: Robot.wait_ready(); resuming replays the episode so far, which can take "+ "minutes in a long episode, and the wall clock keeps running), then check calls and control_steps "+ "before you continue. A 500 means the simulator failed: the episode is over (reason \"error\"). A call "+ "that runs longer than max_call_wall_s seconds stops at the next control step and returns what it "+ "executed (meta.stopped, executed_rows).")+++def _jsonable(v: Any) -> Any:+ if isinstance(v, np.ndarray):+ return v.tolist()+ if isinstance(v, (np.floating, np.integer, np.bool_)):+ return v.item()+ if isinstance(v, (list, tuple)):+ return [_jsonable(x) for x in v]+ if isinstance(v, dict):+ return {str(k): _jsonable(x) for k, x in v.items()}+ return v+++def _peer_closed(sock) -> bool:+ """True when the client of an HTTP request has closed its connection (it gave up on the call): the socket reads as+ end-of-file. A client never sends anything while it waits for the response, so readable means closed."""+ try:+ r, _, _ = select.select([sock], [], [], 0)+ return bool(r) and sock.recv(1, socket.MSG_PEEK) == b""+ except (OSError, ValueError):+ return True+++def _read_json(path: str) -> dict:+ try:+ with open(path) as f:+ d = json.load(f)+ return d if isinstance(d, dict) else {}+ except (OSError, ValueError):+ return {}+++def _write_json(path: str, obj: dict) -> None:+ tmp = f"{path}.{os.getpid()}.tmp"+ with open(tmp, "w") as f:+ json.dump(obj, f)+ os.replace(tmp, path)+++def final_verdict(data: str) -> dict | None:+ """final.json if it already holds a verdict that nothing may overwrite: the grading result (finalized, with+ `deterministic`) or the end of an episode the service gave up after crashes (`gave_up`)."""+ fin = _read_json(os.path.join(data, "final.json"))+ if fin.get("finalized") and (fin.get("gave_up") or fin.get("deterministic") is not None):+ return fin+ return None+++class Episode:+ """Crash-safe episode bookkeeping, the same rules as the RoboTwin and MuJoCo services (PROTOCOL §4.7):++ - startup(): before the scene is built. One line in startups.jsonl; a back-off of min(120, 20 (n - 1)) s when the+ earlier starts never began an episode (they crashed while building, e.g. GPU memory taken by other trials); the+ startup watchdog (faulthandler, a C thread: it fires even when a native scene build holds the GIL) dumps every+ thread's traceback and exits 1 after RCB_STARTUP_TIMEOUT_S, so compose restarts the build. Until begin() a SIGUSR1+ (the collect hook's "the agent phase is over") is only remembered.+ - journal(row): every executed control step (the exact row given to the simulator's step) goes to journal.f64.+ - checkpoint(): after every completed call (the HTTP layer calls it): the journal is flushed, then the call's+ checkpoint is logged in episode.jsonl (rows, control steps, state hash, the robot's proprio row, `persist` keys).+ - begin(): a fresh episode, or after a crash (run.sh exits non-zero, compose restarts the container, `restart:+ on-failure:N`) the SAME episode resumed: the journal is replayed up to the last checkpoint, the journal truncated+ there (the call that was in flight is lost as a whole: its caller got an error, not a result), the state hash+ compared, the service's counters restored; the wall clock keeps running from the first start.+ - Resume check, by the simulator's determinism class: `exact` (bit-exact in a fresh process): the hash must match,+ else the episode ends `resume_failed` (infra_error). `approx` (a simulator declared nondeterministic): a+ mismatch is recorded (resume_state_mismatch, and the robot's deviation from its checkpointed proprio: joint_pos and+ tcp_pose) and the episode continues, unless a TCP is more than RCB_RESUME_MAX_DEV_M from where it was+ (resume_failed, infra_error). The verdict never comes from the live state but from fresh replays of the complete+ recorded trajectory, so continuing cannot raise a score.+ - More than RCB_MAX_RESUMES crashes end the episode: `sim_crashed_on_call` if every crash happened while a call was+ being served (the agent's failure), else `sim_crashed` (infra_error = 1). A verdict already on disk is never+ overwritten; the service then idles with its PID file for the collect hook.+ - Per call, two bounds keep one call from holding the single-threaded service: a call that runs longer than+ max_call_wall_s, or whose client has hung up, stops at the next control step and returns what it executed+ (journal() returns True; meta.stopped says why). Neither bounds the episode: the wall clock is its only budget."""++ def __init__(self, data: str, dim: int, resume: str = "exact", persist: tuple = ()):+ if resume not in ("exact", "approx"):+ raise ValueError("resume must be 'exact' or 'approx'")+ self.data, self.dim, self.resume_class, self.persist = data, int(dim), resume, tuple(persist)+ os.makedirs(data, exist_ok=True)+ p = lambda n: os.path.join(data, n) # noqa: E731+ self.f_events, self.f_journal, self.f_final, self.f_pid, self.f_startups = (+ p("episode.jsonl"), p("journal.f64"), p("final.json"), p("server.pid"), p("startups.jsonl"))+ self.rows = 0 # control steps executed in this episode (journaled)+ self.max_call_wall_s = MAX_CALL_WALL_S+ self.n_startups = 0; self.resumes = 0; self.mismatches = 0; self.max_tcp_dev = 0.0; self.max_joint_dev = 0.0+ self._jf = None; self._call: dict | None = None; self._ids = 0; self._ck: tuple | None = None+ self._on_end: Callable | None = None; self._end_pending = False++ # ---- startup+ def startup(self) -> None:+ signal.signal(signal.SIGUSR1, self._usr1)+ try:+ os.remove(self.f_pid) # a PID file from before a crash would send the collect hook to a dead process+ except OSError:+ pass+ with open(self.f_startups, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid()}) + "\n")+ with open(self.f_startups) as f:+ self.n_startups = sum(1 for line in f if line.strip())+ if self.n_startups > 1 and not any(e.get("ev") == "start" for e in self.events()):+ time.sleep(min(120.0, 20.0 * (self.n_startups - 1)))+ faulthandler.dump_traceback_later(STARTUP_TIMEOUT_S, exit=True)++ def scene_built(self) -> None:+ faulthandler.cancel_dump_traceback_later() # the scene exists: a resume replay may take long, it is not a hang++ def _usr1(self, *_):+ if self._on_end is None:+ self._end_pending = True+ else:+ threading.Thread(target=self._on_end, daemon=True).start()++ # ---- the record+ def log(self, ev: dict) -> None:+ with open(self.f_events, "a") as f:+ f.write(json.dumps(_jsonable({"ts": time.time(), **ev})) + "\n")++ def events(self) -> list:+ out = []+ try:+ with open(self.f_events) as f:+ for line in f:+ try:+ out.append(json.loads(line))+ except ValueError: # a line cut by a crash+ pass+ except OSError:+ pass+ return [e for e in out if isinstance(e, dict)]++ def journal(self, row) -> bool:+ """One executed control step. True: the call in progress must stop at this step boundary (meta.stopped)."""+ a = np.asarray(row, dtype=np.float64).reshape(-1)+ if a.size != self.dim:+ raise ValueError(f"journal rows have {self.dim} entries, got {a.size}")+ if self._jf is None:+ self._jf = open(self.f_journal, "ab")+ self._jf.write(a.tobytes()); self.rows += 1+ c = self._call+ if c is None:+ return False+ if c["stopped"] is None:+ now = time.monotonic()+ if now - c["t0"] > self.max_call_wall_s:+ c["stopped"] = "max_call_wall_s"+ elif c["sock"] is not None and now - c["polled"] >= 0.2:+ c["polled"] = now+ if _peer_closed(c["sock"]):+ c["stopped"] = "client_disconnected"+ return c["stopped"] is not None++ @property+ def stopping(self) -> bool:+ """The call in progress must stop (adapters whose loops test E["done"] test this too)."""+ return bool(self._call and self._call["stopped"])++ @property+ def stop_reason(self) -> str | None:+ return self._call["stopped"] if self._call else None++ def call_begin(self, path: str, sock=None) -> int:+ self._ids += 1+ if path != "/kinematics":+ self._call = {"id": self._ids, "t0": time.monotonic(), "sock": sock, "polled": 0.0, "stopped": None}+ self.log({"ev": "call_begin", "id": self._ids, "path": path})+ return self._ids++ def call_end(self, cid: int, path: str, **extra) -> None:+ self.log({"ev": "call_end", "id": cid, "path": path, **extra})+ if path != "/kinematics":+ self._call = None++ def checkpoint(self, state: dict, state_sha: Callable | None, proprio: Callable | None) -> None:+ if self._jf is not None:+ self._jf.flush() # the rows reach the file before the checkpoint that counts them+ if self._ck is not None and self._ck[0] == self.rows:+ sha, pr = self._ck[1], self._ck[2] # no physics since the last checkpoint+ else:+ try:+ sha = state_sha() if state_sha else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); sha = None+ pr = self._proprio_row(proprio)+ self._ck = (self.rows, sha, pr)+ self.log({"ev": "checkpoint", "call": int(state.get("calls") or 0), "step": int(state.get("step") or 0),+ "control_steps": self.rows, "success": bool(state.get("success")), "done": bool(state.get("done")),+ "reason": state.get("reason"), "state_sha": sha, "proprio": pr,+ **({"persist": {k: state.get(k) for k in self.persist}} if self.persist else {})})++ @staticmethod+ def _proprio_row(proprio: Callable | None) -> list | None:+ try:+ return [round(float(v), 6) for v in np.asarray(proprio(), dtype=np.float64).reshape(-1)] if proprio else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); return None++ def final_fields(self) -> dict:+ """Crash-recovery fields for final.json / episode.json (all numeric, for reward.json)."""+ return {"sim_startups": self.n_startups, "resumes": self.resumes, "resume_state_mismatch": int(self.mismatches > 0),+ "resume_max_tcp_dev_m": round(self.max_tcp_dev, 6), "resume_max_joint_dev": round(self.max_joint_dev, 6)}++ # ---- start or resume+ def begin(self, *, state: dict, step: Callable, state_sha: Callable, proprio: Callable, spec: dict,+ start_event: dict | None = None, on_end: Callable | None = None) -> bool:+ """Start the episode, or resume it after a crash. `step(row)` executes one journaled row on the simulator (the+ recorder on, no rendering needed); `on_end` is what the collect hook's SIGUSR1 runs (in a thread). Returns True+ if the episode was resumed."""+ try: # a line cut by the crash must not swallow the next record+ with open(self.f_events, "rb+") as f:+ f.seek(0, os.SEEK_END)+ if f.tell():+ f.seek(-1, os.SEEK_END)+ if f.read(1) != b"\n":+ f.write(b"\n")+ except OSError:+ pass+ ev = self.events()+ starts = [e for e in ev if e.get("ev") == "start"]+ if not starts:+ try:+ os.remove(self.f_journal)+ except OSError:+ pass+ sha = state_sha()+ self._ck = (0, sha, self._proprio_row(proprio))+ self.log({**(start_event or {}), "ev": "start", "state_sha": sha, "protocol": PROTOCOL, "resume": self.resume_class,+ "journal_dim": self.dim})+ state["t0"] = time.time()+ self._arm(on_end)+ return False+ tries = [e for e in ev if e.get("ev") == "resuming"] # earlier resumes (a crash during one counts too)+ resumed = [e for e in ev if e.get("ev") == "resumed"]+ self.resumes = len(tries) # the record so far, also for a give-up below (final_fields)+ self.mismatches = sum(1 for e in resumed if e.get("exact") is False)+ self.max_tcp_dev = max([float(e.get("tcp_dev_m") or 0) for e in resumed] + [0.0])+ self.max_joint_dev = max([float(e.get("joint_dev") or 0) for e in resumed] + [0.0])+ if final_verdict(self.data):+ self.give_up("restarted after finalize", infra=False)+ k = max(i for i, e in enumerate(ev) if e.get("ev") in ("start", "resuming", "resumed"))+ tail = ev[k + 1:]+ in_call = bool({e.get("id") for e in tail if e.get("ev") == "call_begin"} - {e.get("id") for e in tail if e.get("ev") == "call_end"})+ if len(tries) >= MAX_RESUMES:+ agent = sum(1 for e in tries if e.get("crashed_in_call")) + int(in_call) == len(tries) + 1+ self.give_up("sim_crashed_on_call" if agent else "sim_crashed", infra=not agent)+ self.log({"ev": "resuming", "attempt": len(tries) + 1, "crashed_in_call": in_call,+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self.resumes = len(tries) + 1 # this attempt counts, whether or not it succeeds+ cps = [e for e in ev if e.get("ev") == "checkpoint"]+ last = cps[-1] if cps else {"call": 0, "step": 0, "control_steps": 0, "success": False, "state_sha": starts[0].get("state_sha")}+ n = int(last.get("control_steps") or 0)+ try:+ R = np.fromfile(self.f_journal, dtype=np.float64)+ except (OSError, ValueError):+ R = np.zeros(0)+ if R.size < n * self.dim:+ self.give_up("resume_failed: journal shorter than the log", infra=True)+ R = R[: n * self.dim].reshape(n, self.dim)+ t = time.time()+ for row in R:+ step(row)+ replay_s = time.time() - t+ R.tofile(self.f_journal) # drop the rows of the call that was in flight+ self.rows = n+ sha = state_sha(); want = last.get("state_sha")+ exact = None if want is None else sha == want+ dev = self._deviation(last.get("proprio"), proprio, spec)+ if exact is False: # recorded first: a give-up below reports it too+ self.mismatches += 1+ self.max_tcp_dev = max(self.max_tcp_dev, dev.get("tcp_m") or 0.0)+ self.max_joint_dev = max(self.max_joint_dev, dev.get("joint") or 0.0)+ if self.resume_class == "exact":+ self.give_up("resume_failed: replayed state differs from the logged one", infra=True)+ if dev.get("tcp_m") is not None and dev["tcp_m"] > RESUME_MAX_DEV_M:+ self.give_up(f"resume_failed: a replayed TCP is {dev['tcp_m']:.3f} m from its checkpoint (> {RESUME_MAX_DEV_M} m)", infra=True)+ state["calls"] = int(last.get("call") or 0); state["step"] = int(last.get("step") or 0)+ if "success" in state:+ state["success"] = bool(last.get("success"))+ for key, v in (last.get("persist") or {}).items():+ state[key] = v+ state["t0"] = float(starts[0]["ts"])+ ended = [e for e in ev if e.get("ev") == "end" and int(e.get("control_steps") or 0) <= n] # not the lost call's+ if ended:+ state["done"] = True; state["reason"] = ended[-1].get("reason"); state["t_end"] = float(ended[-1]["ts"])+ state["episode_control_steps"] = int(ended[-1].get("control_steps") or n)+ self._ck = (n, sha, self._proprio_row(proprio)) # the replayed state's row (it may differ under approx)+ self.log({"ev": "resumed", "attempt": self.resumes, "control_steps": n, "calls": state["calls"], "state_sha": sha,+ "logged_sha": want, "exact": exact, "class": self.resume_class, "tcp_dev_m": dev.get("tcp_m"),+ "joint_dev": dev.get("joint"), "crashed_in_call": in_call, "replay_s": round(replay_s, 1),+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self._arm(on_end)+ return True++ @staticmethod+ def _deviation(ref, proprio: Callable, spec: dict) -> dict:+ """The replayed robot against its checkpointed proprio row: max |joint_pos| difference (rad or m) and the largest+ TCP position error (m) over the tcp_pose frames (7 columns each: x y z + quaternion)."""+ if ref is None:+ return {}+ try:+ now = np.asarray(proprio(), dtype=np.float64).reshape(-1); ref = np.asarray(ref, dtype=np.float64).reshape(-1)+ except Exception: # noqa: BLE001+ return {}+ if now.shape != ref.shape:+ return {}+ g, out = spec.get("proprio_groups") or {}, {}+ if "joint_pos" in g:+ f, n = int(g["joint_pos"][0]), int(g["joint_pos"][1])+ out["joint"] = float(np.max(np.abs(now[f:f + n] - ref[f:f + n]))) if n else 0.0+ if "tcp_pose" in g:+ f, n = int(g["tcp_pose"][0]), int(g["tcp_pose"][1]); m = n // 7+ d = (now[f:f + 7 * m] - ref[f:f + 7 * m]).reshape(m, 7)[:, :3]+ out["tcp_m"] = float(np.max(np.linalg.norm(d, axis=1))) if m else 0.0+ return out++ def _arm(self, on_end: Callable | None) -> None:+ self._on_end = on_end+ signal.signal(signal.SIGUSR1, self._usr1)+ if on_end is not None and self._end_pending:+ self._end_pending = False+ threading.Thread(target=on_end, daemon=True).start()++ def give_up(self, reason: str, infra: bool) -> None:+ """End the trial's episode without a new one (never a reset): log it, write the verdict unless one is on disk,+ leave the PID file for the collect hook, and idle until the container is removed."""+ faulthandler.cancel_dump_traceback_later()+ self.log({"ev": "restart_refused", "reason": reason})+ if not final_verdict(self.data):+ fin = _read_json(self.f_final)+ fin.update({"success": False, "done": True, "reason": reason, "finalized": True, "gave_up": True, "protocol": PROTOCOL,+ **self.final_fields(), **({"infra_error": 1} if infra else {})})+ _write_json(self.f_final, fin)+ with open(self.f_pid, "w") as f:+ f.write(str(os.getpid()))+ signal.signal(signal.SIGUSR1, lambda *_: None)+ print(f"[{PROTOCOL}] restart refused: {reason}", flush=True)+ while True:+ time.sleep(3600)+++# ---------------------------------------------------------------- the HTTP layer+class Service:+ """What a sim service hands to serve(): spec (dict), lock, state (the service's E dict: done, reason, exiting, error),+ submit(meta, actions) and observe(meta) -> (meta_out, rcb1 parts), kinematics(req) -> dict, status() -> dict,+ on_submit_error(exc) (a simulator error in /submit or /observe: it ends the episode, reason "error"), log(event dict),+ and for crash recovery the Episode with the simulator's state_sha() and proprio row()."""++ def __init__(self, *, spec: dict, lock, state: dict, submit: Callable, observe: Callable, kinematics: Callable,+ status: Callable, on_submit_error: Callable, log: Callable, max_resp: int = MAX_RESP,+ episode: Episode | None = None, state_sha: Callable | None = None, proprio: Callable | None = None):+ self.spec, self.lock, self.state, self.submit, self.observe = spec, lock, state, submit, observe+ self.kinematics, self.status, self.on_submit_error, self.log, self.max_resp = kinematics, status, on_submit_error, log, max_resp+ self.episode, self.state_sha, self.proprio = episode, state_sha, proprio+ self.kin_calls = 0+++def make_handler(svc: Service):+ class H(BaseHTTPRequestHandler):+ def _send(self, code: int, ctype: str, body: bytes) -> None:+ try:+ self.send_response(code); self.send_header("Content-Type", ctype); self.send_header("Content-Length", str(len(body)))+ self.end_headers(); self.wfile.write(body)+ except (BrokenPipeError, ConnectionResetError): # the client hung up (its call was abandoned)+ pass++ def _json(self, code: int, obj: dict) -> None:+ self._send(code, "application/json", json.dumps(obj).encode())++ def _rcb1(self, meta: dict, parts: list) -> None:+ self._send(200, "application/x-rcb1", encode_response(meta, parts, svc.max_resp))++ def log_message(self, *a):+ pass++ def _body(self):+ try:+ n = int(self.headers.get("Content-Length", 0))+ except ValueError:+ raise ValueError("bad Content-Length")+ if n > MAX_BODY:+ raise ValueError("request too large")+ raw = self.rfile.read(n) if n else b""+ if raw[:4] == rcb1.MAGIC:+ return rcb1.decode(raw)+ body = json.loads(raw or b"{}")+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object or an RCB1 frame")+ return body, {}++ def do_GET(self):+ if self.path == "/spec":+ return self._json(200, svc.spec)+ if self.path == "/status":+ st = svc.status()+ return self._json(200, {**st, "resumes": svc.episode.resumes} if svc.episode else st)+ return self._json(404, {"error": "no such endpoint"})++ def do_POST(self):+ if self.path not in ("/submit", "/observe", "/kinematics"):+ return self._json(404, {"error": "no such endpoint"})+ try:+ meta, parts = self._body()+ except Exception as exc: # noqa: BLE001+ return self._json(413 if "too large" in str(exc) else 400, {"error": str(exc)[:200]})+ E, ep = svc.state, svc.episode+ if self.path == "/kinematics": # stateless: never steps physics, never waits for the episode lock+ cid = ep.call_begin(self.path) if ep else 0+ try:+ req = parse_kinematics(meta, svc.spec["kinematics"])+ out = svc.kinematics(req); svc.kin_calls += 1+ except ValueError as exc:+ return self._json(400, {"error": str(exc)[:300]})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); return self._json(500, {"error": "kinematics error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ ep.call_end(cid, self.path)+ return self._json(200, out)+ with svc.lock:+ if E.get("exiting") or (self.path == "/submit" and E.get("done")):+ return self._json(409, {"error": "episode finished", "reason": E.get("reason")})+ cid = ep.call_begin(self.path, self.connection) if ep else 0+ rows0 = ep.rows if ep else 0+ out = blobs = err = None; stopped = None+ try:+ if self.path == "/submit":+ A = np.asarray(parts["actions"]["data"] if "actions" in parts else meta.get("actions", []), dtype=np.float64)+ out, blobs = svc.submit(meta, A)+ else:+ out, blobs = svc.observe(meta)+ except ValueError as exc:+ err = (400, {"error": str(exc)})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); E["error"] = repr(exc); svc.log({"ev": "error", "path": self.path, "error": repr(exc)})+ try:+ svc.on_submit_error(exc) # PROTOCOL §4.6: a simulator error ends the episode (reason "error")+ except Exception: # noqa: BLE001+ traceback.print_exc()+ err = (500, {"error": "simulator error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ stopped = ep.stop_reason+ if err is None or ep.rows != rows0:+ try:+ ep.checkpoint(E, svc.state_sha, svc.proprio)+ except Exception: # noqa: BLE001+ traceback.print_exc()+ ep.call_end(cid, self.path, **({"stopped": stopped} if stopped else {}))+ if err is not None:+ return self._json(*err)+ return self._rcb1({**out, "stopped": stopped}, blobs)+ return H+++def serve(svc: Service, port: int = 8000) -> None:+ """Check the spec, then serve forever (one request at a time, as every 2.x service)."""+ svc.spec.setdefault("on_service_error", ON_SERVICE_ERROR)+ if svc.episode is not None:+ svc.spec.setdefault("max_call_wall_s", svc.episode.max_call_wall_s)+ check_spec(svc.spec)+ HTTPServer(("0.0.0.0", port), make_handler(svc)).serve_forever()+++# ---------------------------------------------------------------- the collect hook's first half+def _alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ try: # a zombie (exited, not yet reaped) counts as gone+ with open(f"/proc/{pid}/stat") as f:+ return f.read().rsplit(")", 1)[-1].split()[0] != "Z"+ except OSError:+ return True+++def end_episode(data: str, timeout: float = 21600.0, wait_key: str | None = None, resend_s: float = 30.0) -> int:+ """Tell the service that the agent phase is over and wait until it has ended the episode. The service may be+ resuming after a crash (no PID file until it is ready again), so there is no fixed start-up wait, and a signal goes+ only to the process that wrote the newest line of startups.jsonl (its SIGUSR1 handler is installed by then).+ Returns 2: final.json already holds the verdict (the service gave up after crashes, or graded in-process; with+ `wait_key`, also waits for that final.json key, e.g. video_done): keep it, run no replays.+ Returns 0: the service dumped the episode (episode.json) and exited: the hook replays it next.+ Returns 1: timed out."""+ t0, sent = time.time(), 0.0+ f_pid, f_dump, f_starts = (os.path.join(data, n) for n in ("server.pid", "episode.json", "startups.jsonl"))+ while time.time() - t0 < timeout:+ fin = final_verdict(data)+ if fin is not None:+ if not wait_key or fin.get(wait_key) or fin.get("gave_up"):+ return 2+ time.sleep(2); continue+ try:+ with open(f_pid) as f:+ pid = int(f.read().strip())+ except (OSError, ValueError):+ pid = None+ try:+ with open(f_starts) as f:+ cur = json.loads([x for x in f if x.strip()][-1]).get("pid")+ except (OSError, ValueError, IndexError):+ cur = None # a service without Episode.startup(): signal what the PID file names+ if pid is not None and (cur is None or pid == cur):+ if not _alive(pid):+ if os.path.exists(f_dump):+ return 0+ elif time.time() - sent >= resend_s:+ try:+ os.kill(pid, signal.SIGUSR1); sent = time.time()+ except OSError:+ pass+ time.sleep(2)+ return 1+++if __name__ == "__main__":+ a = sys.argv[1:]+ if len(a) >= 2 and a[0] == "end":+ wk = a[a.index("--wait-key") + 1] if "--wait-key" in a else None+ to = float(a[a.index("--timeout") + 1]) if "--timeout" in a else 21600.0+ rc = end_episode(a[1], timeout=to, wait_key=wk)+ print({0: "[collect] episode dumped by the service", 1: "[collect] timed out waiting for the service",+ 2: "[collect] final.json already holds the verdict"}[rc], flush=True)+ sys.exit(rc)+ if len(a) == 2 and a[0] == "final-verdict":+ fin = final_verdict(a[1])+ print(json.dumps(fin) if fin else "no final verdict")+ sys.exit(0 if fin else 1)+ print("usage: rcb_limited.py end <data dir> [--wait-key KEY] [--timeout S] | final-verdict <data dir>")+ sys.exit(2)diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/rcb_quadruped.py b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/run.sh b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/run.shnew file mode 100755index 0000000000..49d4d045d4--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/run.sh@@ -0,0 +1,22 @@+#!/bin/sh+# eai-standard/2.2 sidecar entrypoint: PID 1 of the `sim` container, shared by every 2.2 service+# (scripts/eai_standard/run.sh, copied unchanged into each standard task's environment/sim/).+# - The service crashed (a non-zero exit: an exception, a signal, the startup watchdog): exit with its code, so compose+# restarts the container (`restart: on-failure:6`) and the service resumes the same episode from its journal+# (rcb_limited.Episode). The container keeps its /data (or /out) across the restart.+# - The service exited cleanly (0: it dumped its episode on the collect hook's SIGUSR1 and released the simulator): keep+# the container up for the collect hook's fresh-process replays. If the service were PID 1 itself, that exit would+# stop the container and kill the hook with it (Harbor reports exit 137).+# - Everything the service prints also goes to $RCB_DATA/server.log (an artifact: Harbor keeps no sidecar output, and a+# simulator that dies while it loads leaves no other trace).+DATA="${RCB_DATA:-/data}"+mkdir -p "$DATA"+rm -f "$DATA/.service_rc"+{ python -u "${RCB_SERVER:-/srv/server.py}" 2>&1; echo "$?" > "$DATA/.service_rc"; } | tee -a "$DATA/server.log"+rc="$(cat "$DATA/.service_rc" 2>/dev/null)"; rc="${rc:-1}"+if [ "$rc" != 0 ]; then+ echo "[sim] service exited ($rc): leaving, so compose restarts the container (the service resumes the episode if one began)" | tee -a "$DATA/server.log"+ exit "$rc"+fi+echo "[sim] service exited (0); holding the container open for the collect hook" | tee -a "$DATA/server.log"+while true; do sleep 3600; donediff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/server.py b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/server.pynew file mode 100644index 0000000000..b0c774b183--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/environment/sim/server.py@@ -0,0 +1,478 @@+"""eai-standard/2.2 sim service for MuJoCo Playground's quadruped tasks (docs/STANDARD_MODE_2_2.md): the adapter of the+shared layer rcb_limited.py; the simulator is rcb_quadruped.Session (plain MuJoCo on the CPU).+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to+/data/episode.jsonl.++The episode is the frozen instance's: one control step = 1/50 s. A joystick episode ends after the whole command schedule+(the horizon), when the robot meets Playground's termination rule (it falls over: a failure), when the agent submits+`done`, or when its time is over; success = the task's check on the steps executed. A getup episode ends the moment the+check holds (success), after the horizon, on `done` or on timeout.++Crash recovery (rcb_limited.Episode, resume class `exact`: MuJoCo on the CPU repeats bit for bit in a fresh process):+every executed row is journaled; after a crash the service rebuilds the episode and replays the journal. When the+episode ends the service writes /data/trajectory.npz + /data/episode.json; the collect hook (finalize.sh) makes it exit+and replays the trajectory in two fresh processes."""++import math+import os+import sys+import threading+import time+import traceback++import numpy as np++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import rcb_limited as L # noqa: E402++DATA = os.environ.get("RCB_DATA", "/data")+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.json"))+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "3600"))+MAX_CHUNK_S = float(os.environ.get("RCB_MAX_CHUNK_S", "10"))+MAX_WATCH_S = float(os.environ.get("RCB_MAX_WATCH_S", "30"))+CAM_W, CAM_H = 320, 240+LOCK = threading.Lock()+PID_FILE = os.path.join(DATA, "server.pid")+E = {"ready": False, "step": 0, "calls": 0, "done": False, "reason": None, "success": False, "t0": time.time(), "error": None}++os.environ["RCB_SESSION_LOG"] = ""+os.environ["RCB_AGENT_TRACE_DIR"] = ""+import rcb_quadruped as Q # noqa: E402 (first: it picks the rendering backend before mujoco loads)+import mujoco # noqa: E402++EP = L.Episode(DATA, dim=Q.N, resume="exact")+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()+S = Q.Session(INSTANCE)+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz+DT = S.control_dt # one control step of simulated time (Barkour: 10 ms, as Playground steps it)+CTRL_HZ = 1.0 / DT+SUBSTEPS = S.substeps+M = S.model+CAMS = list(S.cameras)+FEET = S.robot["feet"]+LIMITS = np.stack([S.lower, S.upper], axis=1)+GROUPS = [+ ("joint_pos", S.joint_names, "measured joint positions (rad), in the action's order"),+ ("joint_vel", [f"{j}_vel" for j in S.joint_names], "measured joint velocities (rad/s)"),+ ("joint_effort", [f"{j}_effort" for j in S.joint_names], "actuator torques of those joints (N m)"),+ ("gripper_opening", [], "none (no gripper)"),+ ("tcp_pose", [], "none (no gripper)"),+ ("imu_gyro", ["gyro_x", "gyro_y", "gyro_z"], "angular velocity of the trunk, IMU frame (rad/s)"),+ ("imu_accelerometer", ["acc_x", "acc_y", "acc_z"], "specific force at the IMU, IMU frame (m/s^2; +9.81 up at rest)"),+ ("imu_gravity", ["gravity_x", "gravity_y", "gravity_z"], "unit vector of gravity's direction in the IMU frame "+ "([0, 0, -1] when the trunk is level)"),+ ("imu_linvel", ["linvel_x", "linvel_y", "linvel_z"], "linear velocity of the trunk at the IMU, IMU frame (m/s; the "+ "IMU's velocimeter, what a state estimator gives)"),+ ("foot_contact", [f"{f}_contact" for f in FEET], "1 when the foot touches the ground, else 0"),+]+PROPRIO_LAYOUT = [n for _, names, _ in GROUPS for n in names]+PROPRIO_GROUPS, _i = {}, 0+for _g, _names, _meaning in GROUPS:+ PROPRIO_GROUPS[_g] = [_i, len(_names), _meaning]+ _i += len(_names)+++# ------------------------------------------------------------------------------------------------- cameras+def _intrinsic(cam: str) -> list:+ fovy = math.radians(float(M.cam_fovy[M.camera(cam).id]))+ f = 0.5 * CAM_H / math.tan(fovy / 2)+ return [[f, 0.0, CAM_W / 2], [0.0, f, CAM_H / 2], [0.0, 0.0, 1.0]]+++def camera_info(cam: str) -> dict:+ """World -> camera (OpenCV axes) and camera -> world (OpenGL axes) at the current state."""+ i = M.camera(cam).id+ R_gl = S.data.cam_xmat[i].reshape(3, 3) # camera axes (OpenGL: x right, y up, z back) in the world+ p = S.data.cam_xpos[i].copy()+ R_cv = R_gl @ np.diag([1.0, -1.0, -1.0])+ ext = np.zeros((3, 4))+ ext[:, :3] = R_cv.T+ ext[:, 3] = -R_cv.T @ p+ c2w = np.eye(4)+ c2w[:3, :3] = R_gl+ c2w[:3, 3] = p+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": ext.tolist(), "cam2world_gl": c2w.tolist(),+ "image_size": [CAM_W, CAM_H]}+++# ------------------------------------------------------------------------------------------------- kinematics+KD = mujoco.MjData(M) # kinematics only: the trunk at the origin, level; never stepped+_FOOT = {f: M.site(f).id for f in FEET}+_LEG_DOF = {f: [6 + 3 * k + j for j in range(3)] for k, f in enumerate(FEET)} # actuator order = leg order = FEET+++def _fk_kd(q) -> None:+ KD.qpos[:] = 0.0+ KD.qpos[3] = 1.0+ KD.qpos[7:] = q+ mujoco.mj_kinematics(M, KD)+++def _foot_pose(f: str) -> list:+ quat = np.zeros(4)+ mujoco.mju_mat2Quat(quat, KD.site_xmat[_FOOT[f]])+ return [*KD.site_xpos[_FOOT[f]].tolist(), *quat.tolist()]+++def do_kinematics(req: dict) -> dict:+ """Feet in the trunk frame (the trunk body's origin and axes; x forward, y left, z up). IK solves positions only, one+ leg (3 joints) per foot target, damped least squares within the joint ranges; a foot's orientation is ignored."""+ if req["op"] == "fk":+ _fk_kd(np.asarray(req["q"]))+ return L.fk_response({f: _foot_pose(f) for f in req["links"]}, "trunk")+ q = np.array(req["seed"] if req["seed"] is not None else S.data.qpos[7:], dtype=np.float64)+ errors = {}+ jac = np.zeros((3, M.nv))+ for f, pose in req["targets"].items():+ tgt = np.asarray(pose[:3])+ idx = _LEG_DOF[f]+ for _ in range(req["max_iters"]):+ _fk_kd(q)+ err = tgt - KD.site_xpos[_FOOT[f]]+ if np.linalg.norm(err) < req["tol_pos_m"]:+ break+ mujoco.mj_jacSite(M, KD, jac, None, _FOOT[f])+ J = jac[:, idx]+ dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(3), err)+ q[[i - 6 for i in idx]] = np.clip(q[[i - 6 for i in idx]] + dq, S.lower[[i - 6 for i in idx]],+ S.upper[[i - 6 for i in idx]])+ _fk_kd(q)+ errors[f] = (float(np.linalg.norm(tgt - KD.site_xpos[_FOOT[f]])), 0.0)+ ok = all(e[0] <= req["tol_pos_m"] for e in errors.values())+ return L.ik_response(q, ok, errors, "trunk", note="feet: position only (a foot is a sphere; its orientation is ignored)")+++# ------------------------------------------------------------------------------------------------- spec+def schedule_text() -> list:+ if S.commands is None:+ return []+ return [{"from_s": round(int(c["start_step"]) * DT, 2), "vx_mps": round(c["vx"], 4), "vy_mps": round(c["vy"], 4),+ "wz_radps": round(c["wz"], 4)} for c in S.inst["commands"]]+++TASK_EPISODE = {+ "joystick": f"one episode, no reset: it ends after {S.horizon} control steps (the {S.horizon * DT:g} s command "+ f"schedule), when the robot meets its termination rule ({S.spec.get('term_text')}: a failure), when you "+ "submit `done`, or when your time is over",+ "getup": f"one episode, no reset: it ends the moment the robot has stood upright for {Q.HOLD_STEPS} control steps in a "+ f"row (success), after {S.horizon} control steps, when you submit `done`, or when your time is over",+ "stand_on_two": f"one episode, no reset: it ends the moment the pose has been held for {Q.POSE_HOLD_STEPS} control steps "+ "in a row (success), when the robot meets the termination rule (a failure: its trunk's up axis below "+ f"-0.25, or {'a leg' if S.spec.get('hind_leg_contact') else 'a front leg'}'s thigh, calf or hip on the "+ f"floor), after {S.horizon} control steps, when you "+ "submit `done`, or when your time is over",+}[S.kind]+_ctl = {"type": "joint position actuators (PD)", "kp_nm_per_rad": float(M.actuator_gainprm[0, 0]),+ "kd_nms_per_rad": float(M.dof_damping[6] - M.actuator_biasprm[0, 2])}+SPEC = {+ "protocol": L.PROTOCOL,+ "protocol_compat": list(L.COMPAT),+ "simulator": "MuJoCo 3.3.7 (MuJoCo Playground's scene, plain MuJoCo on the CPU)",+ "robot": S.robot["name"],+ "task_text": S.inst["text"],+ "control_hz": CTRL_HZ,+ "physics_substeps": SUBSTEPS,+ "max_chunk_s": MAX_CHUNK_S,+ "max_watch_s": MAX_WATCH_S,+ "cameras": {c: {"rgb": True, "depth": True, "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),+ **({"mounted": "follows the robot", "mount": {"type": "link", "link": S.robot["root"], "note":+ "follows the robot's centre of mass at a fixed offset; it does not turn with the robot"}}+ if int(M.cam_mode[M.camera(c).id]) != 0 else+ {"mounted": "on the robot's head", "mount": {"type": "link", "link": M.body(M.cam_bodyid[M.camera(c).id]).name+ or S.robot["root"], "note": "fixed to the robot: moves and turns with it"}})}+ for c in CAMS},+ "default_cameras": ["track"],+ "action_types": {+ "joint_position": {+ "dim": Q.N,+ "layout": S.joint_names,+ "limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "units": "rad",+ "semantics": "absolute targets of the 12 joint position actuators, one per control step (1/50 s); rows `dt` "+ "apart (a multiple of the control period, at most 0.5 s), `hold` or `linear` between rows; values "+ "outside the limits are clipped and reported",+ },+ "done": {"dim": 0, "layout": [], "semantics": 'ends the episode now, in the current state (no physics); r.submit("done", [])'},+ "not_yet": ["joint_velocity", "joint_torque", "joint_delta"],+ },+ "proprio_layout": PROPRIO_LAYOUT,+ "proprio_groups": PROPRIO_GROUPS,+ "static": {},+ "world": {"frame": "z up; the robot starts where the episode puts it (no world coordinates are given)", "up": "+z",+ "units": {"length": "m", "angle": "rad", "time": "s"}, "quaternion_order": "wxyz",+ "camera_axes": "intrinsic_cv / extrinsic_cv: OpenCV camera axes (x right, y down, z forward); cam2world_gl: OpenGL axes"},+ "budget": {"reset": 0, "steps": None, "wall_clock_s": WALL_CLOCK_S},+ "max_control_steps": S.horizon,+ "episode": TASK_EPISODE,+ "command_schedule": schedule_text(),+ **({"gait": {k: S.gait[k] for k in ("name", "frequency_hz", "foot_height_m", "phase0", "phase_dt")} | {+ "feet": FEET, "rule": "foot i's target height at control step t is get_rz(wrap(phase0[i] + t * phase_dt)) with "+ "Playground's gait.get_rz (a cubic Bezier from 0 up to foot_height_m over the first half of the phase, then "+ "down); phases in rad, wrapped to [-pi, pi)"}} if S.gait else {}),+ "robot_spec": {"name": S.robot["name"], "joints": S.joint_names, "joint_limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "joint_order": S.robot["joint_text"], "home_pose": dict(zip(S.joint_names, S.home.tolist())),+ "feet": FEET, "controller": _ctl},+ "kinematics": {"endpoint": "/kinematics", "joint_names": S.joint_names, "frame": "trunk", "quaternion_order": "wxyz",+ "links": FEET, "tcp_frames": [], "ee_frames": FEET, "ik_targets": FEET,+ "ik": {"tol_pos_m": 0.002, "tol_rot_rad": 3.2, "max_iters": 100},+ "note": "poses of the feet in the trunk frame (x forward, y left, z up, metres) for joint positions q; "+ "ik: one leg per foot, positions only"},+ "depth": {"modes": list(L.DEPTH_MODES), "default": "none", "kind": "z-depth", "unit": "m", "invalid": 0,+ "max_m": L.DEPTH_MAX_M, "frames_encoding": "uint16 mm, zlib", "noise": L.DEPTH_NOISE},+}+L.check_spec(SPEC) # a spec that misses a 2.2 field or names a forbidden one never starts the episode+EP.scene_built()++_RENDER = {}+++def _renderer():+ if "r" not in _RENDER:+ _RENDER["r"] = mujoco.Renderer(M, CAM_H, CAM_W)+ return _RENDER["r"]+++def ctrl_steps() -> int:+ return S.steps+++def proprio_row() -> np.ndarray:+ d = S.data+ return np.concatenate([d.qpos[7:], d.qvel[6:], d.actuator_force, S.sensor("gyro"), S.sensor("accelerometer"), S.gravity(),+ S.sensor("local_linvel"), S.foot_contacts()]).astype(np.float32)+++def grab(cams, want_depth: bool):+ r = _renderer()+ rgb, dep = {}, {}+ for c in cams:+ r.update_scene(S.data, camera=c)+ rgb[c] = r.render().copy()+ if want_depth:+ r.enable_depth_rendering()+ r.update_scene(S.data, camera=c)+ dep[c] = r.render().astype(np.float32).copy()+ r.disable_depth_rendering()+ return rgb, dep+++def extrinsics(cams) -> dict:+ return {c: np.asarray(camera_info(c)["extrinsic_cv"], dtype=np.float64) for c in cams}+++def write_final() -> None:+ if L.final_verdict(DATA): # finalize.sh's verdict, or a give-up after crashes: never overwritten+ return+ L._write_json(os.path.join(DATA, "final.json"), {**summary(), "finalized": False, "live_sha": E.get("live_sha")})+++def summary() -> dict:+ n = int(E.get("episode_control_steps") or ctrl_steps())+ chk = E.get("check") or {}+ return {"success": bool(E["success"]), "steps": E["step"], "calls": E["calls"], "control_steps": n,+ "physics_steps": n * SUBSTEPS, "elapsed_s": round((E.get("t_end") or time.time()) - E["t0"], 1),+ "reason": E["reason"], "done": E["done"], "env": S.env, "protocol": L.PROTOCOL, "n_actions": len(ROWS),+ "fell_at": chk.get("fell_at"), "worst_lin_err": chk.get("worst_lin_err"), "worst_yaw_err": chk.get("worst_yaw_err"),+ "tilt_deg": chk.get("tilt_deg"), "imu_height": chk.get("imu_height"), "pose_angle_deg": chk.get("pose_angle_deg"),+ **EP.final_fields()}+++def finish(reason: str) -> None:+ """The episode is over: the task's check on the steps executed, then the record for the collect hook."""+ if E["done"]:+ return+ E["done"] = True+ E["reason"] = reason+ E["t_end"] = time.time()+ E["episode_control_steps"] = ctrl_steps()+ try:+ chk = S.check()+ E["check"] = {k: v for k, v in chk.items() if k != "segments"}+ E["success"] = bool(chk["success"])+ except Exception: # noqa: BLE001+ traceback.print_exc()+ EP.log({"ev": "end", "reason": reason, "step": E["step"], "control_steps": ctrl_steps(), "success": bool(E["success"])})+ dump()+++def dump() -> None:+ if E.get("dumped"):+ return+ E["dumped"] = True+ E["live_sha"] = S.state_sha()+ np.savez(os.path.join(DATA, "trajectory.npz"), actions=np.asarray(ROWS, dtype=np.float64).reshape(-1, Q.N),+ env=S.env, action_layout=",".join(S.joint_names))+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})+ write_final()+++def after_step() -> None:+ if S.kind in ("joystick", "stand_on_two") and S.fell_at is not None:+ finish("fell")+ elif S.kind in ("getup", "stand_on_two") and S.check()["success"]:+ finish("success")+ elif S.done:+ finish("horizon")+++def ctrl_step(a, rec) -> bool:+ """One executed control step, journaled. True when the call must stop here."""+ S.step(a)+ ROWS.append(np.asarray(a, dtype=np.float64))+ stop = EP.journal(a)+ rec.tick()+ after_step()+ return E["done"] or stop+++def recorder(cams, fps: int, meta: dict) -> L.Recorder:+ return L.Recorder(cams, max(1, int(round(CTRL_HZ / max(1, fps)))), grab, proprio_row, extrinsics, ctrl_steps,+ depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+++def video_fps(meta: dict) -> int:+ fps = meta.get("video_fps")+ if fps is None:+ return 10+ if isinstance(fps, bool) or not isinstance(fps, (int, float)) or not (1 <= fps <= 50):+ raise ValueError("video_fps must be in [1, 50]")+ return int(fps)+++def cameras_of(meta: dict) -> list:+ cams = meta.get("cameras") or ["track"]+ bad = [c for c in cams if c not in CAMS]+ if bad:+ raise ValueError(f"unknown cameras {bad}; cameras: {CAMS}")+ return list(cams)+++def meta_common(cams) -> dict:+ n = ctrl_steps()+ out = {"step": E["step"], "calls": E["calls"], "control_steps": n, "physics_steps": n * SUBSTEPS,+ "sim_time_s": round(n * DT, 3), "time_s": round(time.time() - E["t0"], 2),+ "time_left_s": max(0.0, round(WALL_CLOCK_S - (time.time() - E["t0"]), 1)),+ "proprio": {"layout": PROPRIO_LAYOUT, "now": proprio_row().tolist()}, "done": E["done"], "reason": E["reason"],+ "cameras": {c: camera_info(c) for c in cams}}+ if S.kind == "joystick":+ out["command_now"] = dict(zip(("vx_mps", "vy_mps", "wz_radps"), S.command_now().round(4).tolist()))+ return out+++def do_submit(meta: dict, A: np.ndarray):+ typ = meta.get("type")+ if typ == "done":+ rec = recorder(cameras_of(meta), 5, meta)+ rec.tick(force=True, last=True) # every response carries the last frames+ E["calls"] += 1+ finish("done")+ return {**meta_common(cameras_of(meta)), "chunk_id": E["calls"], "type": typ, "executed_rows": 0, "ok": True}, rec.parts("none", 5)+ if typ != "joint_position":+ raise ValueError(f"type must be joint_position or done (not yet: {SPEC['action_types']['not_yet']})")+ dt = float(meta.get("dt", DT))+ interp = meta.get("interpolate", "linear")+ video = meta.get("video", "mp4")+ cams, fps = cameras_of(meta), video_fps(meta)+ k = dt / DT+ if A.ndim != 2 or A.shape[1] != Q.N:+ raise ValueError(f"joint_position actions must be (T, {Q.N}), got {list(A.shape)}")+ if not np.all(np.isfinite(A)):+ raise ValueError("actions contain NaN/inf")+ if not (math.isfinite(dt) and dt <= 0.5 + 1e-9 and round(k) >= 1 and abs(k - round(k)) < 1e-6):+ raise ValueError(f"dt must be a whole multiple of the {DT:g} s control period and at most 0.5 s; got {dt}")+ if A.shape[0] * dt > MAX_CHUNK_S + 1e-9:+ raise ValueError(f"chunk longer than max_chunk_s={MAX_CHUNK_S}: {A.shape[0]} rows x {dt} s")+ if interp not in ("hold", "linear"):+ raise ValueError("interpolate must be hold|linear")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, clipped = recorder(cams, fps, meta), []+ E["calls"] += 1+ step0, before = E["step"], ctrl_steps()+ rec.tick(force=True)+ prev = S.targets.copy()+ for ri, row in enumerate(A):+ E["step"] += 1+ target = np.clip(row, LIMITS[:, 0], LIMITS[:, 1])+ for j in np.flatnonzero(target != row)[:20]:+ clipped.append({"row": ri, "index": int(j), "reason": f"{S.joint_names[j]} limit [{LIMITS[j, 0]:g}, {LIMITS[j, 1]:g}]"})+ n = int(round(k))+ stop = False+ for s in range(1, n + 1):+ a = target if interp == "hold" else prev + (target - prev) * (s / n)+ if ctrl_step(a, rec):+ stop = True+ break+ prev = target+ if stop:+ break+ rec.tick(force=True, last=True)+ out = {**meta_common(cams), "chunk_id": E["calls"], "type": typ, "executed_rows": E["step"] - step0,+ "control_steps_chunk": ctrl_steps() - before, "physics_steps_chunk": (ctrl_steps() - before) * SUBSTEPS,+ "clipped": clipped[:200], "n_clipped": len(clipped), "plan": [], "ok": True}+ EP.log({"ev": "submit", "call": E["calls"], "rows": E["step"] - step0, "dt": dt, "interpolate": interp, "cameras": cams,+ "control_steps": ctrl_steps() - before, "n_clipped": len(clipped), "note": (meta.get("note") or "")[:500],+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video, fps)+++def do_observe(meta: dict):+ cams, fps = cameras_of(meta), video_fps(meta)+ seconds = float(meta.get("seconds", 0))+ video = meta.get("video", "frames")+ if not math.isfinite(seconds) or seconds < 0 or seconds > MAX_WATCH_S:+ raise ValueError(f"seconds must be in [0, {MAX_WATCH_S}]")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, before = recorder(cams, fps, meta), ctrl_steps()+ if seconds > 0 and not E["done"]:+ rec.tick(force=True)+ hold = S.targets.copy()+ for _ in range(int(round(seconds / DT))):+ if ctrl_step(hold, rec):+ break+ rec.tick(force=True, last=True)+ E["calls"] += 1+ out = {**meta_common(cams), "obs_id": E["calls"], "seconds": seconds, "control_steps_watch": ctrl_steps() - before,+ "physics_steps_watch": (ctrl_steps() - before) * SUBSTEPS, "ok": True}+ EP.log({"ev": "observe", "call": E["calls"], "seconds": seconds, "cameras": cams, "control_steps": ctrl_steps() - before,+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video if seconds > 0 else ("frames" if video == "mp4" else video), fps)+++def status() -> dict:+ return {"step": E["step"], "calls": E["calls"], "control_steps": ctrl_steps(), "done": E["done"], "reason": E["reason"],+ "elapsed_s": round(time.time() - E["t0"], 1)}+++def end_from_signal() -> None:+ """The collect hook's SIGUSR1: end the episode (the agent's time is over), dump it, exit so the replays can start."""+ with LOCK:+ E["exiting"] = True+ if not E["done"]:+ finish("timeout")+ EP.log({"ev": "exit", "reason": "collect hook: episode dumped"})+ if not os.path.exists(PID_FILE):+ open(PID_FILE, "w").write(str(os.getpid()))+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(0)+++def replay_row(row) -> None:+ """A journaled row during a resume."""+ S.step(row)+ ROWS.append(np.asarray(row, dtype=np.float64))+++EP.begin(state=E, step=replay_row, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, on_end=end_from_signal,+ start_event={"env": S.env, "seed": S.inst.get("seed"), "cameras": CAMS})+if E["done"]:+ dump() # resumed after the episode had ended: the record is rewritten from the replay+E["ready"] = True+write_final()+open(PID_FILE, "w").write(str(os.getpid()))+print(f"{L.PROTOCOL} MuJoCo Playground quadruped sim ready ({S.env}; startup {EP.n_startups}, resumes {EP.resumes})", flush=True)+L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics, status=status,+ on_submit_error=lambda exc: finish("error"), log=EP.log, episode=EP, state_sha=S.state_sha,+ proprio=proprio_row), port=int(os.environ.get("RCB_PORT", "8000")))diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/instruction.md b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/instruction.mdnew file mode 100644index 0000000000..8149077321--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/instruction.md@@ -0,0 +1,59 @@+# MuJoCo Playground · Go1JoystickRoughTerrain — STANDARD MODE (robot as a service, eai-standard/2.2)++**Task:** Make the Unitree Go1 follow the joystick command schedule on rough terrain (a 20 x 20 m heightfield, up to 5 cm high) for the whole 20 s episode without falling over.++You control the Unitree Go1 quadruped — **as if it were real hardware** — in one episode of MuJoCo Playground's+`Go1JoystickRoughTerrain` environment (plain MuJoCo 3.3.7 with Playground's scene, commit 4057c14). The simulator runs in a service you+cannot open. You get one client and one episode.++## The episode+The robot starts at Playground's `home` pose, its base moved to (-0.096, 0.049) m and turned to a yaw of 118.2 deg, with a random base velocity (Playground's reset). The ground is Playground's rough terrain: a 20 x 20 m heightfield (`hfield.png`, up to 5 cm high) centred on the world origin, with nothing beyond its edge.+For 20 s (1000 control steps) it is given this command schedule, drawn by Playground's command process (a new draw after Exp(1) x 5 s; a draw may keep a component). A command is a velocity in the robot's own frame: vx forward, vy to the left (the trunk's planar velocity), and the yaw rate:++| from (s) | vx (m/s) | vy (m/s) | yaw rate (rad/s) |+|---:|---:|---:|---:|+| 0.00 | +1.137 | +0.168 | -0.703 |+| 0.34 | +1.137 | +0.000 | -0.703 |+| 2.76 | -1.078 | -0.702 | +0.000 |+| 10.96 | -1.078 | +0.000 | +0.787 |+| 11.88 | +0.000 | -0.359 | +0.787 |+| 12.22 | +0.000 | -0.359 | +0.000 |+| 13.48 | -0.036 | +0.000 | -0.087 |++The same schedule is `spec["command_schedule"]`; every response's `meta["command_now"]` is the current command.++## Rules (real-robot rules)+- **No reset.** One episode. You see four cameras that follow the robot (RGB, depth if you ask) and the robot's own+ sensors: joint positions, velocities and torques, the IMU (gyro, accelerometer, gravity's direction, the trunk's+ velocity), foot contacts. No world positions, no success check.+- **The episode ends** after 1000 control steps, the whole schedule (`spec["max_control_steps"]`, counted by `meta["control_steps"]`), when the robot meets its termination rule (the trunk's up axis pointing below the horizon (the z component of the IMU frame's z axis negative): a failure), when you submit `done`, or when your time is up (before the end of the schedule, both are failures).+- **Success** is judged on the whole schedule: no termination, and in every command segment, after its first 25 control steps, a mean |v_xy - cmd_xy| of at most 0.2 m/s (`imu_linvel`) and a mean |w_z - cmd_wz| of at most 0.3 rad/s (`imu_gyro`).+- Your wall-clock budget is 3600 s from your start. Simulated time only advances with your commands (and+ `get_obs(seconds=...)`, which holds the current targets).+- Nothing to hand in: the service records the episode and grades it. Leave your script at `/app/output/gen.py`.+- **If the service crashes**, a call fails with a connection error: it restarts and resumes the SAME episode (never a+ reset) in the state after the last call it completed. `r.wait_ready()` waits for it; then check `r.status()`.+- Nothing is put into your context automatically: images come back as arrays in Python objects.++## Client (`/opt/tools/rcb_client.py`)+```python+from rcb_client import Robot+r = Robot() # connects (waits while the service starts)+spec = r.spec() # action types, limits, cameras, robot_spec (home pose, gains), kinematics, command_schedule+obs = r.get_obs() # obs.last[cam] -> uint8 (240, 320, 3); obs.meta["proprio"] {"layout", "now"}+res = r.submit("joint_position", A, dt=0.02) # A: (T, 12) rows dt apart; res.proprio (one row per frame), res.meta+obs = r.get_obs(seconds=1.0, video="mp4") # hold the current targets and watch for 1 s (max 30)+r.fk(q); r.ik({"FR": [x, y, z, 1, 0, 0, 0]}, seed=q) # feet in the trunk frame <-> joints (no physics)+r.submit("done", []) # end the episode now+r.status() # calls, control steps, done, reason, elapsed time+```+Cameras: `track`, `side`, `back`, `top` (they follow the robot); `spec["cameras"]` gives each one's mounting and intrinsics, and every response carries its pose. Proprioception (`spec["proprio_groups"]`): `joint_pos`, `joint_vel`, `joint_effort` (12 each, action+order), `imu_gyro`, `imu_accelerometer`, `imu_gravity`, `imu_linvel` (3 each, IMU frame: x forward, y left, z up),+`foot_contact` (FR, FL, RR, RL).++### `joint_position` (12)+FR, FL, RR, RL legs, each hip (abduction), thigh (hip pitch), calf (knee): absolute targets of the joint position actuators (rad; kp = 35 N m/rad, joint damping 0.5 N m s/rad).+Rows are `dt` apart (a whole multiple of the 0.02 s control period, at most 0.5 s), `interpolate="linear"` (default) or+`"hold"` between rows; a chunk covers at most 10 s; values outside the limits+(`spec["action_types"]["joint_position"]["limits"]`) are clipped and listed in `res.meta["clipped"]`. Feedback control+means short chunks: each response tells you where the robot is now.diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/solution/oracle.npy b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/solution/oracle.npynew file mode 100644index 0000000000..7ca581e9d7Binary files /dev/null and b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/solution/oracle_replay.py b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/solution/oracle_replay.pynew file mode 100644index 0000000000..b6a9824592--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/solution/oracle_replay.py@@ -0,0 +1,42 @@+"""Oracle (standard mode): streams the reference rows (one per 1/50 s control step, `hold`) as `joint_position` chunks+through the client, the same interface an agent has. Uses no privileged information at run time; the service's recorded+trajectory is then exactly the privileged reference. If the service crashes it resumes the same episode+(spec["on_service_error"]): the oracle waits until it answers again and goes on from the control step it reports."""+import os+import sys+import time++import numpy as np+import requests++sys.path.insert(0, "/opt/tools")+from rcb_client import EpisodeOver, Robot # noqa: E402++Q = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy")).astype(np.float64)+r = Robot()+spec = r.spec()+dt = 1.0 / float(spec["control_hz"])+per_chunk = max(1, int(spec.get("max_chunk_s", 10) / dt + 1e-9))+print("spec:", spec["protocol"], "rows:", len(Q), flush=True)+t0, i = time.time(), 0+while i < len(Q):+ chunk = Q[i:i + per_chunk]+ try:+ res = r.submit("joint_position", chunk, dt=dt, interpolate="hold", cameras=["track"], video="none", note=f"oracle rows {i}+")+ except EpisodeOver as e:+ print("episode over:", e)+ break+ except requests.exceptions.RequestException as e: # the service crashed: it restarts and resumes the same episode+ print("service unreachable:", repr(e)[:200], "- waiting for it to resume", flush=True)+ st = r.wait_ready()+ n = int(st["control_steps"])+ if not i <= n <= i + len(chunk):+ raise SystemExit(f"resumed at control step {n}: outside the chunk in flight (rows {i}..{i + len(chunk)})")+ i = n+ continue+ n = int(res.meta["control_steps"])+ print(f"rows {i}..{n}: clipped={res.meta['n_clipped']} done={res.meta['done']} reason={res.meta['reason']}", flush=True)+ if res.meta["done"] or n <= i:+ break+ i = n+print("status:", r.status(), "wall %.0fs" % (time.time() - t0))diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/solution/solve.sh b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/solution/solve.shnew file mode 100755index 0000000000..ecb1f6c954--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/solution/solve.sh@@ -0,0 +1,8 @@+#!/bin/bash+# Oracle (standard mode): streams the reference trajectory's joint targets (solution/oracle.npy, one row per control step)+# as `joint_position` chunks through the client. Uses no privileged information at run time (only the pre-recorded+# targets); the service's recorded trajectory is then exactly the privileged reference.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/task.toml b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/task.tomlnew file mode 100644index 0000000000..668c1bab89--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/task.toml@@ -0,0 +1,54 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = [+ { source = "/data/final.json", service = "sim" },+ { source = "/data/episode.jsonl", service = "sim" },+ { source = "/data/trajectory.npz", service = "sim" },+ { source = "/data/replay.mp4", service = "sim" },+ { source = "/data/server.log", service = "sim" }, # the service's own output (Harbor keeps none)+ { source = "/data/journal.f64", service = "sim" }, # crash recovery: every executed control step (float64 rows)+ { source = "/data/startups.jsonl", service = "sim" }, # crash recovery: one line per service start+ { source = "/data/replay1.log", service = "sim" }, # the collect hook's two fresh-process replays+ { source = "/data/replay2.log", service = "sim" },+ { source = "/data/replay3.log", service = "sim" }, # and its third, which renders replay.mp4+ "/app/output/",+]++[task]+name = "robot-coding-bench/mujoco_playground_go1_joystick_rough_terrain-standard"+description = "STANDARD MODE (robot as a service, eai-standard/2.2): MuJoCo Playground Go1JoystickRoughTerrain (Unitree Go1) on the same frozen instance as mujoco_playground_go1_joystick_rough_terrain-privileged: Make the Unitree Go1 follow the joystick command schedule on rough terrain (a 20 x 20 m heightfield, up to 5 cm high) for the whole 20 s episode without falling over. The agent only gets a client: four cameras that follow the robot (RGB, optional depth), the robot's joints and IMU, joint position chunks at 50 Hz, the feet's kinematics; one episode, no reset, no world state; the sim service records the episode, replays it in fresh processes and grades it."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "unitree-go1", "quadruped", "locomotion", "joystick", "code-as-policy", "trajectory", "standard-mode"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "unitree-go1"+family = "mujoco_playground/Go1JoystickRoughTerrain"+mode = "standard"+protocol = "eai-standard/2.2"+oracle = "full"+instance_seed = 1+expert_time_estimate_hours = 4.0++[verifier]+timeout_sec = 600.0+environment_mode = "separate"+network_mode = "no-network"++[[verifier.collect]]+service = "sim"+command = "sh /srv/finalize.sh" # end + dump + exit the service, replay twice in fresh processes, write final.json, video+timeout_sec = 1200++[agent]+timeout_sec = 3600.0+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/tests/Dockerfile b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/tests/Dockerfilenew file mode 100644index 0000000000..26bc699ebe--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/tests/Dockerfile@@ -0,0 +1,5 @@+# Separate verifier sandbox: grades the sim service's own artifacts; needs nothing but python (the shared client base).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY test.sh /tests/test.sh+COPY grade.py /tests/grade.py+RUN chmod +x /tests/test.shdiff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/tests/grade.py b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/tests/grade.pynew file mode 100644index 0000000000..5b990bf458--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/tests/grade.py@@ -0,0 +1,64 @@+"""Standard-mode verifier (MuJoCo Playground quadrupeds): reads what the sim service (which the agent could not touch) wrote:+/data/final.json (live success, two fresh-process replays of the recorded trajectory, determinism, crash-recovery+fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, the+replays having started in the instance's t = 0 state. Numeric-only reward.json."""++import json, os, shutil++LOG = "/logs/verifier"+os.makedirs(LOG, exist_ok=True)+++def write(ok, out):+ open(f"{LOG}/reward.txt", "w").write("1\n" if ok else "0\n")+ json.dump(out, open(f"{LOG}/reward.json", "w"))+ print(out)+++p = "/data/final.json"+if not os.path.exists(p):+ write(False, {"success": 0, "missing_log": 1, "grader_error": 0, "infra_error": 0})+ raise SystemExit+d = json.load(open(p))+for f in ("replay.mp4", "trajectory.npz", "episode.jsonl"):+ if os.path.exists(f"/data/{f}"):+ shutil.copy(f"/data/{f}", f"{LOG}/{f}")+ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic"))+ok = ok and not d.get("instance_mismatch")+num = lambda k: float(d.get(k) or 0) # noqa: E731+write(+ ok,+ {+ "success": int(ok),+ "live_success": int(bool(d.get("success"))),+ "replay_success": int(bool(d.get("replay_success"))),+ "deterministic": int(bool(d.get("deterministic"))),+ "live_matches_replay": int(bool(d.get("live_matches_replay"))),+ "finalized": int(bool(d.get("finalized"))),+ "n_actions": int(d.get("n_actions") or 0),+ "sim_steps": int(d.get("control_steps") or 0),+ "physics_steps": int(d.get("physics_steps") or 0),+ "steps": int(d.get("steps") or 0),+ "elapsed_s": float(d.get("elapsed_s") or 0),+ "video_rendered": int(bool(d.get("video"))),+ "fell": int(d.get("fell_at") is not None),+ "worst_lin_err": float(d["worst_lin_err"]) if d.get("worst_lin_err") is not None else -1.0,+ "worst_yaw_err": float(d["worst_yaw_err"]) if d.get("worst_yaw_err") is not None else -1.0,+ "end_tilt_deg": float(d["tilt_deg"]) if d.get("tilt_deg") is not None else -1.0,+ "end_imu_height": float(d["imu_height"]) if d.get("imu_height") is not None else -1.0,+ "end_pose_angle_deg": float(d["pose_angle_deg"]) if d.get("pose_angle_deg") is not None else -1.0,+ # a replay process gave no result, or the image no longer builds the frozen start: not the agent's 0+ "grader_error": int(bool(d.get("replay_failed") or d.get("instance_mismatch"))),+ "instance_mismatch": int(bool(d.get("instance_mismatch"))),+ # an infrastructure failure, not the agent's (PROTOCOL §2.6): a give-up after crashes between calls or a failed+ # resume (docs/STANDARD_MODE_2_2.md §13), the service not ending its episode for the collect hook, a replay+ # process that gave no result, replays that did not start in the instance's t = 0 state+ "infra_error": int(bool(d.get("infra_error"))),+ "gave_up": int(bool(d.get("gave_up"))),+ "sim_error": int(d.get("reason") == "error"),+ "sim_startups": int(d.get("sim_startups") or 0),+ "resumes": int(d.get("resumes") or 0),+ "resume_state_mismatch": int(d.get("resume_state_mismatch") or 0),+ "resume_max_joint_dev": num("resume_max_joint_dev"),+ },+)diff --git a/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/tests/test.sh b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/tests/test.shnew file mode 100755index 0000000000..bc608aa8b9--- /dev/null+++ b/tasks/mujoco_playground_go1_joystick_rough_terrain-standard/tests/test.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Verifier (separate sandbox): the sim sidecar's artifacts were uploaded to /data by Harbor.+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)+mkdir -p /logs/verifier+python /tests/grade.py 2> /logs/verifier/grade.logdiff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/README.md b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/README.mdnew file mode 100644index 0000000000..6a977da9c7--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/README.md@@ -0,0 +1,42 @@+# mujoco_playground_spot_flat_terrain_joystick-privileged++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | privileged |+| Twin | `mujoco_playground_spot_flat_terrain_joystick-standard` |+| Simulator / robot | `mujoco` / `boston-dynamics-spot` |+| Family / instance | `mujoco_playground/SpotFlatTerrainJoystick` / seed 0 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `SpotFlatTerrainJoystick` (Boston Dynamics Spot), rebuilt in plain MuJoCo from Playground's scene files: Make Boston Dynamics Spot follow the joystick command schedule on flat ground for the whole 20 s episode without falling over.+For 20 s the robot gets a joystick command schedule (5 segments: planar velocity and yaw rate in its own frame) and must track it without falling over. The deliverable is one replayable trajectory of joint position targets+(`/app/output/trajectory.npz`, `(T, 12)`, T = 1000 (the whole schedule)).++## Difficulty+Velocity tracking for 20 s: the agent has to make a 12-joint quadruped walk (a gait, not one motion) and steer it through the schedule's changes of speed, direction and turning rate, and an open-loop trajectory of 1000 steps only works if it is computed against the simulator. Spot is large and heavy, and Playground stops the episode once its trunk tilts by about 32 deg, so the gait has to stay level.++## Reference solution+A policy trained here on Playground's SpotFlatTerrainJoystick reward (PPO on the CPU, `scripts/mujoco-playground/train/`, not in the image), its targets recorded (`scripts/mujoco-playground/oracle.py`): worst segment errors 0.155 m/s and 0.072 rad/s. Replayed by `solution/solve.sh` (`solution/oracle.npy`, 1000 rows); the rows are float32-exact, so the+standard twin's client executes the same targets. Re-verified by `scripts/mujoco-playground/select_instances.py`: two+fresh-process replays succeed and end in the same state.++## Verification+`tests/grade.py` in a separate sandbox without network: two replays, each in a fresh process, from the verifier's own+copy of the instance (`tests/instance.json`; the start state is checked against its hash on every load); pass iff both+succeed and end in the same state (`deterministic`). Oracle: success, worst segment errors 0.155 m/s and 0.072 rad/s. `nop`: no trajectory, reward 0.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml`; MuJoCo Menagerie @ 1b86ece (`boston_dynamics_spot`); simulated in MuJoCo 3.3.7 on the CPU |+| Instance | Playground's `reset` with `jax.random.PRNGKey(0)` and Playground's command process over the 1000 steps; chosen by `scripts/mujoco-playground/select_instances.py` (seed 0; the first candidate) |+| Actions | 12 joint position targets per control step (0.02 s of simulated time); kp = 300 N m/rad, joint damping 1 N m s/rad, plus the actuators' own damping of 20 N m s/rad |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py` from `scripts/mujoco-playground/instances/SpotFlatTerrainJoystick.json`+(`make_instances.py`, `select_instances.py`) and `scripts/mujoco-playground/oracles/SpotFlatTerrainJoystick.npy` (`oracle.py`).diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/environment/Dockerfile b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/environment/Dockerfilenew file mode 100644index 0000000000..7bdd7d2938--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/environment/Dockerfile@@ -0,0 +1,8 @@+# MuJoCo Playground quadruped task (privileged): plain MuJoCo with Playground's and Menagerie's assets+# (images/mujoco/prepare_assets.sh), the task's tooling and its frozen instance.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY instance.json /app/instance.json+COPY rcb_quadruped.py /opt/tools/rcb_quadruped.py+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/environment/instance.json b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/environment/instance.jsonnew file mode 100644index 0000000000..3ea273b2b3--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/environment/instance.json@@ -0,0 +1,100 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "SpotFlatTerrainJoystick",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 0.46000000834465027,+ 1.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842+ ],+ "qvel0": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 0.7129874229431152,+ "vy": 0.045435335487127304,+ "wz": 0.6093337535858154+ },+ {+ "start_step": 201,+ "vx": -0.18540263175964355,+ "vy": -0.40133342146873474,+ "wz": -0.4772922992706299+ },+ {+ "start_step": 402,+ "vx": 0.6049041748046875,+ "vy": 0.11546879261732101,+ "wz": 0.04899191856384277+ },+ {+ "start_step": 603,+ "vx": 0.0,+ "vy": 0.0,+ "wz": 0.0+ },+ {+ "start_step": 804,+ "vx": -0.28104639053344727,+ "vy": -0.7415485382080078,+ "wz": -0.6673171520233154+ }+ ],+ "text": "Make Boston Dynamics Spot follow the joystick command schedule on flat ground for the whole 20 s episode without falling over.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": 0.0,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.46,+ "reference_rows": 1000,+ "torso_mass_kg": 50.34,+ "reference_worst_lin_err": 0.1555,+ "reference_worst_yaw_err": 0.072+ },+ "state_sha": "53128662ae17",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/environment/rcb_quadruped.py b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/environment/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/environment/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/instruction.md b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/instruction.mdnew file mode 100644index 0000000000..b1ebe2a05b--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/instruction.md@@ -0,0 +1,63 @@+# MuJoCo Playground · SpotFlatTerrainJoystick — frozen episode++**Task:** Make Boston Dynamics Spot follow the joystick command schedule on flat ground for the whole 20 s episode without falling over.++You control the Boston Dynamics Spot quadruped in one episode of MuJoCo Playground's `SpotFlatTerrainJoystick` environment, rebuilt in plain+MuJoCo 3.3.7 from Playground's own scene files (Apache-2.0, commit 4057c14) and the robot from MuJoCo Menagerie. The+episode is frozen: it starts the same way after every reset (Playground's `reset` with seed 0), and you may reset+as often as you like. Your deliverable is **one open-loop trajectory**, not a general policy.++## The episode+The robot starts standing still at Playground's `home` pose (this environment's reset does not move it). The ground is flat.+For 20 s (1000 control steps) it is given this command schedule, drawn by Playground's command process (a new draw every 201 control steps, zero with probability 0.1). A command is a velocity in the robot's own frame: vx forward, vy to the left (the trunk's planar velocity), and the yaw rate:++| from (s) | vx (m/s) | vy (m/s) | yaw rate (rad/s) |+|---:|---:|---:|---:|+| 0.00 | +0.713 | +0.045 | +0.609 |+| 4.02 | -0.185 | -0.401 | -0.477 |+| 8.04 | +0.605 | +0.115 | +0.049 |+| 12.06 | +0.000 | +0.000 | +0.000 |+| 16.08 | -0.281 | -0.742 | -0.667 |++`s.commands` holds the schedule per control step; `s.state()["command"]` is the current one.++## Success+The episode lasts exactly 1000 control steps: the trajectory must have T = 1000 rows. Success iff+1. the robot never meets Playground's termination rule for this environment: the trunk tilted by more than about 32 deg (the z component of the IMU frame's z axis below 0.85); and+2. in every command segment, over its control steps after the first 25 (0.5 s): the mean planar velocity error |v_xy - cmd_xy| is at most 0.2 m/s, with v the IMU's velocimeter (`local_linvel`, trunk frame), and the mean yaw-rate error |w_z - cmd_wz| at most 0.3 rad/s, with w the IMU's gyro.++`s.check()` reports `fell_at`, each segment's errors and `success`.++## Deliverable+`/app/output/trajectory.npz` with `actions`: float64 (T, 12), one row per control step (0.02 s): absolute targets of+the 12 joint position actuators, in `s.joint_names` order (FL, FR, HL, HR legs, each hx (abduction), hy (hip pitch), kn (knee)), in radians; T = 1000 (the whole schedule). Values+outside the actuator ranges (`s.lower`, `s.upper`) are clipped. `s.save_trajectory(rows)` writes it. Also leave the+script that produced it at `/app/output/gen.py`. Save a working trajectory as soon as you have one and overwrite it as+you improve it: whatever is in `/app/output/` when your 3600 s are up is graded. The tooling logs your sessions and+resets (cost accounting, not graded).++## Tooling (installed; `python` from any directory)+```python+from rcb_quadruped import Session+s = Session("/app/instance.json") # the frozen episode at t = 0 (checked against the instance's state hash)+s.joint_names; s.lower; s.upper # the actuator order and ranges (rad)+s.home # Playground's standing pose (its `home` keyframe), in that order+s.step(row) # one control step: 12 joint targets, 5 physics steps of 0.004 s; returns s.check()+s.check() # the task's check on the steps so far (see Success)+s.state() # qpos, qvel, IMU (local_linvel, gyro, gravity, accelerometer, pose), feet, contacts, command+s.sensor(name); s.gravity() # one MuJoCo sensor; gravity's direction in the IMU frame+s.model, s.data # the live MuJoCo model and data (read them; changing them is not part of the replay)+s.render(cam); s.cameras # uint8 (240, 320, 3) from cameras that follow the robot: `track`, `side`, `back`, `top` (they follow the robot)+s.reset() # back to t = 0+s.replay(rows) # reset, run the rows, return the check and the final state's hash+s.render_video(rows, "/app/output/try.mp4")+s.save_trajectory(rows, "/app/output/trajectory.npz")+```+The grader runs exactly this CLI in two fresh processes, so run it to check yourself:+`python /opt/tools/rcb_quadruped.py replay --instance /app/instance.json --traj /app/output/trajectory.npz`++## Conventions+- Joint position actuators (PD): kp = 300 N m/rad, joint damping 1 N m s/rad, plus the actuators' own damping of 20 N m s/rad, as Playground's environment sets them; the physics step is 0.004 s,+ the control step 0.02 s (5 physics steps); a row holds until the next one.+- World frame z up, metres; quaternions **wxyz**. The IMU frame is the trunk's: x forward, y left, z up.+- Physics is MuJoCo on the CPU: the same rows from the same start give the same result in every fresh process.diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/solution/oracle.npy b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/solution/oracle.npynew file mode 100644index 0000000000..ce4a22921dBinary files /dev/null and b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/solution/oracle_replay.py b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/solution/oracle_replay.pynew file mode 100644index 0000000000..46987df1d0--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/solution/oracle_replay.py@@ -0,0 +1,15 @@+"""Oracle (privileged): replay the reference rows in the tooling, check them, and save them as the deliverable."""+import json+import os+import sys++import numpy as np++sys.path.insert(0, "/opt/tools")+from rcb_quadruped import Session # noqa: E402++rows = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy"))+s = Session("/app/instance.json")+r = s.replay(rows)+s.save_trajectory(rows, "/app/output/trajectory.npz", meta={"source": "reference trajectory (solution/oracle.npy)"})+print(json.dumps({k: v for k, v in r.items() if k != "segments"}))diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/solution/solve.sh b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/solution/solve.shnew file mode 100755index 0000000000..430ffb6017--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/solution/solve.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Oracle (privileged): write the reference trajectory frozen at generation time (solution/oracle.npy; how it was made:+# scripts/mujoco-playground/oracle.py) as the deliverable.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/task.toml b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/task.tomlnew file mode 100644index 0000000000..cd08b3b634--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/task.toml@@ -0,0 +1,43 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = ["/app/output/", "/logs/agent/rcb/"]++[task]+name = "robot-coding-bench/mujoco_playground_spot_flat_terrain_joystick-privileged"+description = "MuJoCo Playground SpotFlatTerrainJoystick in plain MuJoCo (Boston Dynamics Spot, joint position control every 0.02 s): Make Boston Dynamics Spot follow the joystick command schedule on flat ground for the whole 20 s episode without falling over. Produce one replayable trajectory of joint position targets on a frozen instance (Playground's reset with seed 0); graded by velocity tracking over the whole 20 s schedule without a fall (two fresh-process replays)."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "boston-dynamics-spot", "quadruped", "locomotion", "joystick", "code-as-policy", "trajectory", "privileged"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "boston-dynamics-spot"+family = "mujoco_playground/SpotFlatTerrainJoystick"+mode = "privileged"+oracle = "full"+instance_seed = 0 # the PRNGKey of Playground's reset (and, for the joystick tasks, its command process)+expert_time_estimate_hours = 3.0++[verifier]+timeout_sec = 1200.0+environment_mode = "separate"+network_mode = "no-network"++[verifier.environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192++[agent]+timeout_sec = 3600.0+# MuJoCo Playground's trained policies are public upstream, so the agent reaches the model APIs and nothing else+# (scripts/set_agent_egress.py HOSTS).+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/tests/Dockerfile b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/tests/Dockerfilenew file mode 100644index 0000000000..f49c79154d--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/tests/Dockerfile@@ -0,0 +1,7 @@+# Separate verifier sandbox (PROTOCOL §4): the same image with the verifier's own copies of the tooling and the frozen+# instance. Nothing the agent did in its container reaches this one: Harbor uploads only the declared artifacts.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY grade.py instance.json rcb_quadruped.py test.sh /tests/+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier+ENV PYTHONPATH=/tests+WORKDIR /testsdiff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/tests/grade.py b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/tests/grade.pynew file mode 100644index 0000000000..e5668de85f--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/tests/grade.py@@ -0,0 +1,126 @@+"""Verifier (privileged): replay /app/output/trajectory.npz from the frozen instance and write Harbor's rewards.++ python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz++Two replays, each in its own fresh process (`rcb_quadruped.py replay`: the frozen start, one control step per row, the+task's success check on the whole trajectory). success = both replays succeed and end in the same state. Writes+/logs/verifier/reward.txt (1/0) and reward.json (numbers only); then a third replay renders replay.mp4, after the+verdict is on disk (it never changes it).+"""+import argparse+import json+import os+import subprocess+import sys+import tempfile+import traceback++import numpy as np++LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")+TOOL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_quadruped.py")+REPLAY_TIMEOUT_S = 300 # a 1000-step replay takes a few seconds; the video replay renders 4 views every 2nd step+++def write(ok: bool, out: dict) -> None:+ os.makedirs(LOG_DIR, exist_ok=True)+ open(os.path.join(LOG_DIR, "reward.txt"), "w").write("1\n" if ok else "0\n")+ json.dump(out, open(os.path.join(LOG_DIR, "reward.json"), "w"))+ print(json.dumps(out), flush=True)+++def agent_cost() -> dict:+ """Self-reported cost from the tooling's log in the agent's container (accounting, not evidence)."""+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_replays": 0, "agent_cost_self_reported": 1}+ for path in ("/logs/agent/rcb/rcb_session_log.jsonl", "/app/output/rcb_session_log.jsonl"):+ if not os.path.exists(path):+ continue+ try:+ with open(path) as f:+ for i, line in enumerate(f):+ if i > 200_000 or len(line) > 10_000:+ break+ try:+ e = json.loads(line)+ ev = e.get("ev") if isinstance(e, dict) else None+ if ev == "session_start":+ cost["agent_sessions"] += 1+ elif ev == "reset":+ cost["agent_resets"] += 1+ elif ev == "replay":+ cost["agent_replays"] += 1+ elif ev == "session_end":+ cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)+ except Exception: # noqa: BLE001 -- one bad line must not sink the verdict+ continue+ except OSError:+ pass+ break+ return cost+++def replay(instance: str, traj: str, video: str | None) -> dict:+ """One replay in a fresh process; its result (`--out`), or {"error": ...}."""+ with tempfile.NamedTemporaryFile(suffix=".json") as out:+ cmd = [sys.executable, TOOL, "replay", "--instance", instance, "--traj", traj, "--out", out.name]+ try:+ p = subprocess.run(cmd + (["--video", video] if video else []), stdout=subprocess.DEVNULL, stderr=sys.stderr,+ timeout=REPLAY_TIMEOUT_S, env={**os.environ, "RCB_SESSION_LOG": "", "RCB_AGENT_TRACE_DIR": ""})+ except subprocess.TimeoutExpired:+ return {"error": f"replay took over {REPLAY_TIMEOUT_S} s"}+ try:+ return json.load(open(out.name))+ except ValueError:+ return {"error": f"replay process rc={p.returncode}"}+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--instance", required=True)+ ap.add_argument("--traj", default="/app/output/trajectory.npz")+ a = ap.parse_args()+ cost = agent_cost()+ if not os.path.isfile(a.traj):+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost})+ return 0+ try:+ horizon = int(json.load(open(a.instance))["horizon"])+ d = np.load(a.traj, allow_pickle=False)+ acts = np.asarray(d["actions"], dtype=np.float64) if "actions" in d.files else np.zeros((0, 0))+ if acts.ndim != 2 or acts.shape[1] != 12 or len(acts) > horizon or not np.all(np.isfinite(acts)):+ write(False, {"success": 0, "bad_trajectory": 1, "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0,+ "grader_error": 0, **cost})+ return 0+ runs = [replay(a.instance, a.traj, None), replay(a.instance, a.traj, None)]+ if any("error" in r and not r.get("bad_trajectory") for r in runs):+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ if not all(r.get("instance_ok") for r in runs): # the image no longer builds the frozen start: not the agent's 0+ write(False, {"success": 0, "grader_error": 1, "instance_mismatch": 1, **cost})+ return 0+ all_success = all(bool(r.get("success")) for r in runs)+ deterministic = runs[0].get("state_sha") == runs[1].get("state_sha")+ ok = all_success and deterministic+ r = runs[0]+ num = lambda k: float(r.get(k) if r.get(k) is not None else -1) # noqa: E731+ out = {"success": int(ok), "replay_success": int(all_success), "deterministic": int(deterministic),+ "n_actions": int(len(acts)), "horizon": horizon, "fell": int(r.get("fell_at") is not None),+ "fell_at_step": num("fell_at"), "worst_lin_err": num("worst_lin_err"), "worst_yaw_err": num("worst_yaw_err"),+ "end_tilt_deg": num("tilt_deg"), "end_imu_height": num("imu_height"), "end_pose_angle_deg": num("pose_angle_deg"),+ "grader_error": 0,+ "video_rendered": 0, **cost}+ write(ok, out) # the verdict, before any video+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ try: # the video, for humans: it never changes the verdict+ if replay(a.instance, a.traj, os.path.join(LOG_DIR, "replay.mp4")).get("video"):+ write(ok, {**out, "video_rendered": 1})+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/tests/instance.json b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/tests/instance.jsonnew file mode 100644index 0000000000..3ea273b2b3--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/tests/instance.json@@ -0,0 +1,100 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "SpotFlatTerrainJoystick",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 0.46000000834465027,+ 1.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842+ ],+ "qvel0": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 0.7129874229431152,+ "vy": 0.045435335487127304,+ "wz": 0.6093337535858154+ },+ {+ "start_step": 201,+ "vx": -0.18540263175964355,+ "vy": -0.40133342146873474,+ "wz": -0.4772922992706299+ },+ {+ "start_step": 402,+ "vx": 0.6049041748046875,+ "vy": 0.11546879261732101,+ "wz": 0.04899191856384277+ },+ {+ "start_step": 603,+ "vx": 0.0,+ "vy": 0.0,+ "wz": 0.0+ },+ {+ "start_step": 804,+ "vx": -0.28104639053344727,+ "vy": -0.7415485382080078,+ "wz": -0.6673171520233154+ }+ ],+ "text": "Make Boston Dynamics Spot follow the joystick command schedule on flat ground for the whole 20 s episode without falling over.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": 0.0,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.46,+ "reference_rows": 1000,+ "torso_mass_kg": 50.34,+ "reference_worst_lin_err": 0.1555,+ "reference_worst_yaw_err": 0.072+ },+ "state_sha": "53128662ae17",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/tests/rcb_quadruped.py b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/tests/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/tests/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/tests/test.sh b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/tests/test.shnew file mode 100755index 0000000000..1c3d2f767b--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-privileged/tests/test.sh@@ -0,0 +1,9 @@+#!/bin/bash+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in two fresh processes (the+# verdict), then a third that renders replay.mp4.+# Writes /logs/verifier/reward.txt (1/0) and reward.json (numeric fields, docs/PROTOCOL.md §2.6).+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/*+mkdir -p /logs/verifier+python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz 2> /logs/verifier/grade.logdiff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/README.md b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/README.mdnew file mode 100644index 0000000000..cff0916aed--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/README.md@@ -0,0 +1,44 @@+# mujoco_playground_spot_flat_terrain_joystick-standard++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | standard (`eai-standard/2.2`) |+| Twin | `mujoco_playground_spot_flat_terrain_joystick-privileged` |+| Simulator / robot | `mujoco` / `boston-dynamics-spot` |+| Family / instance | `mujoco_playground/SpotFlatTerrainJoystick` / seed 0 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `SpotFlatTerrainJoystick` (Boston Dynamics Spot) on the same frozen instance as `mujoco_playground_spot_flat_terrain_joystick-privileged`: Make Boston Dynamics Spot follow the joystick command schedule on flat ground for the whole 20 s episode without falling over.+For 20 s the robot gets a joystick command schedule (5 segments: planar velocity and yaw rate in its own frame) and must track it without falling over. Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with only+the robot's own sensors and four cameras that follow it.++## Difficulty+Same instance and success check as `mujoco_playground_spot_flat_terrain_joystick-privileged`. In standard mode the agent loses resets, the simulator and+the world state: it sees camera images and proprioception (joints, IMU, foot contacts), acts in joint position chunks,+and gets one episode, so it has to close the loop on the robot's own sensors and recover from its own mistakes without+starting over.++## Reference solution+`solution/oracle_replay.py` streams the privileged reference's rows (`solution/oracle.npy`, 1000 rows, float32-exact)+through the client in `hold` chunks; it uses no privileged information at run time. The service's recorded trajectory+is then exactly the privileged reference, and the episode ends after the 1000 steps of the schedule, with success.++## Verification+The sim service judges the episode live and records every executed control step; the collect hook+(`environment/sim/finalize.sh`) ends the service, replays the recorded trajectory in two fresh processes and writes+`final.json`; `tests/grade.py` (separate sandbox, no network) passes iff the live check succeeded, both replays succeed,+and they end in the same state. Oracle: success, worst segment errors 0.155 m/s and 0.072 rad/s.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml`; MuJoCo Menagerie @ 1b86ece (`boston_dynamics_spot`); MuJoCo 3.3.7 on the CPU |+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); cameras `track`, `side`, `back`, `top` (they follow the robot) (320 x 240), the feet's kinematics in the trunk frame |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py`, as its privileged twin.diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/Dockerfile b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/Dockerfilenew file mode 100644index 0000000000..ed5eee3703--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/Dockerfile@@ -0,0 +1,9 @@+# Standard mode: the agent container has NO simulator and no Playground code, only Python and the client, on the shared+# pinned client base with the shared pins (scripts/eai_standard/client.env, client-requirements.txt).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY client-requirements.txt /tmp/client-requirements.txt+RUN pip install --no-cache-dir -r /tmp/client-requirements.txt+COPY rcb_client.py rcb1.py /opt/tools/+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/client-requirements.txt b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/client-requirements.txtnew file mode 100644index 0000000000..8aa73a968f--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/client-requirements.txt@@ -0,0 +1,11 @@+# Exact pins for what the standard agent container installs (and a verifier, if it installs anything): the closure of+# `pip install requests numpy pillow scipy`, the unpinned line of every standard task at 9eb18edf, resolved on+# 2026-10-01 in CLIENT_IMAGE (client.env: Python 3.12.14, pip 25.0.1). A change here is a shared-files PR.+certifi==2026.7.22+charset-normalizer==3.5.2+idna==3.20+numpy==2.5.3+pillow==12.3.0+requests==2.34.2+scipy==1.18.1+urllib3==2.8.0diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/docker-compose.yaml b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/docker-compose.yamlnew file mode 100644index 0000000000..8ec63c582e--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/docker-compose.yaml@@ -0,0 +1,23 @@+# Standard mode: the simulator runs in the `sim` sidecar (the agent cannot open it); the agent only reaches port 8000.+# No `expose`/`ports` on sim: under Harbor's egress control it shares main's network namespace (localhost:8000).+# CPU only: MuJoCo physics and rendering (EGL when a GPU is there, else OSMesa); no GPU reservation.+# Crash recovery (docs/STANDARD_MODE_2_2.md §13): run.sh exits non-zero when the service crashes, compose restarts the+# container (same container, same /data) and the service replays its journal into the same episode, never a reset.+services:+ main:+ depends_on: [sim]+ sim:+ image: ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+ volumes:+ - ./sim:/srv:ro+ working_dir: /tmp+ command: sh /srv/run.sh+ restart: on-failure:6 # N >= 3 (PROTOCOL §4.1); a resume continues the episode+ environment:+ RCB_INSTANCE: /srv/instance.json+ RCB_TOOL: /srv/rcb_quadruped.py+ RCB_DATA: /data+ RCB_WALL_CLOCK_S: "3600"+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in about a second+ PYTHONPATH: /srv+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction logdiff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/rcb1.py b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/rcb_client.py b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/rcb_client.pynew file mode 100644index 0000000000..aa25b0e050--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/rcb_client.py@@ -0,0 +1,211 @@+"""eai-standard/2.2 client (formerly rcb-limited/2.x) — the only thing a standard-mode agent gets (installed at+/opt/tools/rcb_client.py).++ from rcb_client import Robot+ r = Robot() # finds the service (sim:8000, then localhost:8000), waits for warm-up+ spec = r.spec() # actions, cameras (+ intrinsics, mounting), robot_spec, world, budget, kinematics+ obs = r.get_obs() # current frames: obs.last[cam] -> uint8 (H,W,3); obs.meta["proprio"]+ obs = r.get_obs(depth=True) # + obs.last_depth[cam] -> float32 (H,W) z-depth in metres, 0 = no reading+ res = r.submit("joint_position", A, dt=0.1) # A: (T, dim) rows dt apart; returns the execution video+ res = r.submit("ee_pose", P) # (T, dim) end-effector targets (see spec()["action_types"])+ res.video[cam] -> mp4 bytes res.frames[cam] -> uint8 (N,H,W,3) if video="frames"/"both" res.last[cam]+ res.proprio -> float32 (N, D), one row per frame (names: spec()["proprio_layout"]; res.group("tcp_pose"))+ res.frame_step -> int64 (N,) control step of each frame res.frame_time_s -> float64 (N,) simulated time+ res.extrinsic_cv[cam] -> float64 (N,3,4) world->camera per frame (res.meta["cameras"]: intrinsics + the last frame's pose)+ res = r.submit(..., depth="frames") # + res.depth[cam] -> float32 (N,H,W) metres, one per frame (1 mm steps)+ r.fk(q) # {"ok", "poses": {frame: [x,y,z, quaternion]}}: forward kinematics, no physics+ r.ik({frame: pose}, seed=q) # {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}: inverse kinematics+ res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, frames/<cam>/NNN.jpg, proprio.npy, depth, frame_meta.npz+ obs = r.get_obs(seconds=3, video="both") # hold the last command, let physics run 3 s, return the video+ r.status() # calls, control steps, done, reason, elapsed time++Nothing is put into your context automatically: what you look at, and where you store it, is your code's decision.++If a call fails with a connection error or a 5xx, the service may have crashed; it restarts and resumes the SAME episode+(never a reset) in the state after the last call it completed, which you may not have received. r.wait_ready() waits+until it answers again (resuming replays the episode so far: long episodes can take minutes); then check r.status()+before you continue (spec()["on_service_error"]).+"""+from __future__ import annotations+import json, os, pathlib, sys, time, zlib+import numpy as np+import requests+import rcb1++PROTOCOL = "eai-standard/2.2" # also talks to 2.0 / 2.1 services (they ignore depth and send no frame metadata)+ACCEPTED = ("eai-standard/2.", "rcb-limited/2.") # every 2.x service, under the protocol's current and former name+++class EpisodeOver(RuntimeError):+ pass+++def _decode_depth_frames(p: dict) -> np.ndarray:+ a = np.frombuffer(zlib.decompress(p["data"]), dtype="<u2").reshape(p["shape"])+ return a.astype(np.float32) / 1000.0+++class Result:+ """Decoded RCB1 response: meta (dict), video (cam -> mp4 bytes), frames (cam -> uint8 (N,H,W,3)), last (cam -> uint8+ (H,W,3)), last_depth (cam -> float32 (H,W) m), depth (cam -> float32 (N,H,W) m, one per frame), proprio (float32 (N,D)),+ frame_step (int64 (N,)), frame_time_s (float64 (N,)), extrinsic_cv (cam -> float64 (N,3,4)). save(dir) writes it out;+ show(cam, k) returns one frame; group(name) the proprio columns of one spec()["proprio_groups"] group. stopped: None,+ or why the service stopped the call early ("max_call_wall_s": it ran longer than spec()["max_call_wall_s"]); then+ meta["executed_rows"] < the rows sent, and meta["proprio"]["now"] is where the robot is."""+ def __init__(self, meta: dict, parts: dict, spec: dict | None = None):+ self.meta = meta; self.raw = parts; self._spec = spec or {}; self.stopped = meta.get("stopped")+ self.video, self.frames, self.last, self.last_depth, self.depth, self.extrinsic_cv = {}, {}, {}, {}, {}, {}+ self.proprio = None; self.frame_step = None; self.frame_time_s = None+ for name, p in parts.items():+ kind, data = p["kind"], p["data"]+ if name.startswith("video/") and kind == "mp4": self.video[name[6:]] = data+ elif name.startswith("frames/") and kind == "array": self.frames[name[7:]] = data+ elif name.startswith("last/") and kind == "array": self.last[name[5:]] = data+ elif name.startswith("last_depth/") and kind == "array": self.last_depth[name[11:]] = np.asarray(data, dtype=np.float32)+ elif name.startswith("depth_frames/") and p.get("codec") == "zlib": self.depth[name[13:]] = _decode_depth_frames(p)+ elif name.startswith("depth/") and kind == "array": self.depth[name[6:]] = np.asarray(data, dtype=np.float32) # 2.1 form+ elif name.startswith("extrinsic_cv/") and kind == "array": self.extrinsic_cv[name[13:]] = data+ elif name == "proprio": self.proprio = data+ elif name == "frame_step": self.frame_step = data+ elif name == "frame_time_s": self.frame_time_s = data++ @property+ def done(self) -> bool: return bool(self.meta.get("done"))++ def show(self, camera: str, k: int = -1) -> np.ndarray:+ if camera in self.frames: return self.frames[camera][k]+ return self.last[camera]++ def group(self, name: str, now: bool = False) -> np.ndarray:+ """Columns of proprio group `name` (spec()["proprio_groups"]): (N, n) over the frames, or (n,) of meta["proprio"]["now"]."""+ first, n = self._spec["proprio_groups"][name][:2]+ if now: return np.asarray(self.meta["proprio"]["now"], dtype=np.float64)[first:first + n]+ return self.proprio[:, first:first + n]++ def save(self, out_dir: str) -> str:+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ (out / "meta.json").write_text(json.dumps(self.meta, indent=1))+ for cam, b in self.video.items(): (out / f"{cam}.mp4").write_bytes(b)+ try:+ from PIL import Image+ for cam, img in self.last.items():+ (out / "last").mkdir(exist_ok=True); Image.fromarray(np.ascontiguousarray(img)).save(out / "last" / f"{cam}.jpg", quality=90)+ for cam, arr in self.frames.items():+ d = out / "frames" / cam; d.mkdir(parents=True, exist_ok=True)+ for i, f in enumerate(arr): Image.fromarray(np.ascontiguousarray(f)).save(d / f"{i:03d}.jpg", quality=85)+ except ImportError:+ for cam, img in self.last.items(): np.save(out / f"last_{cam}.npy", img)+ for cam, arr in self.frames.items(): np.save(out / f"frames_{cam}.npy", arr)+ for cam, arr in self.last_depth.items(): np.save(out / f"last_depth_{cam}.npy", arr)+ for cam, arr in self.depth.items(): np.savez_compressed(out / f"depth_{cam}.npz", depth_mm=np.rint(arr * 1000).astype(np.uint16))+ if self.proprio is not None: np.save(out / "proprio.npy", self.proprio)+ if self.frame_step is not None:+ np.savez(out / "frame_meta.npz", frame_step=self.frame_step, frame_time_s=self.frame_time_s,+ **{f"extrinsic_cv/{c}": e for c, e in self.extrinsic_cv.items()})+ return str(out)+++class Robot:+ def __init__(self, base: str | None = None, timeout: float = 600.0):+ cands = [base or os.environ.get("SIM_URL"), "http://sim:8000", "http://localhost:8000"]+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ for b in [c for c in cands if c]:+ try:+ r = requests.get(b + "/spec", timeout=(5, 30))+ if r.status_code == 503: last = "warming up"; break+ r.raise_for_status(); self.base = b; self._spec = r.json()+ if not str(self._spec.get("protocol", "")).startswith(ACCEPTED):+ raise RuntimeError(f"not a 2.x service: protocol {self._spec.get('protocol')!r}")+ return+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(2)+ raise RuntimeError(f"sim service unavailable: {last}")++ def spec(self) -> dict:+ return self._spec++ def _post(self, path: str, meta: dict, parts: list, timeout: float) -> Result:+ body = rcb1.encode(meta, parts)+ r = requests.post(self.base + path, data=body, headers={"Content-Type": "application/x-rcb1"}, timeout=(5, timeout))+ if r.status_code == 409:+ raise EpisodeOver(r.json().get("reason") if r.headers.get("Content-Type", "").startswith("application/json") else "episode finished")+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ m, p = rcb1.decode(r.content); return Result(m, p, self._spec)++ def _common(self, cameras, video_fps, depth, include_depth) -> dict:+ cams = list(cameras) if cameras is not None else self._spec.get("default_cameras")+ if depth is None or depth is False: depth = "frames" if include_depth else "none"+ elif depth is True: depth = "last"+ m = {"cameras": cams, "video_fps": None if video_fps is None else int(video_fps), "depth": depth}+ return {k: v for k, v in m.items() if v is not None}++ def submit(self, action_type: str, actions, dt: float | None = None, interpolate: str = "linear", cameras=None,+ video_fps: int | None = None, video: str = "mp4", depth=None, include_depth: bool = False, note: str = "") -> Result:+ """Execute a chunk of low-level actions (T, dim); see spec()['action_types'] for dims, layouts, limits and semantics.+ dt defaults to one control period, cameras to spec()['default_cameras']; depth: None | True (= "last") | "frames"."""+ a = np.asarray(actions, dtype=np.float32)+ if a.ndim == 1: a = a[None, :]+ if dt is None and self._spec.get("control_hz"): dt = 1.0 / float(self._spec["control_hz"])+ meta = {"type": action_type, "interpolate": interpolate, "video": video, "note": note,+ **({} if dt is None else {"dt": float(dt)}), **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/submit", meta, [rcb1.array_part("actions", a)], timeout=1800)+ if res.stopped:+ print(f"[rcb_client] the service stopped this call early ({res.stopped}): {res.meta.get('executed_rows')} of {len(a)} rows "+ "executed; meta['proprio']['now'] is where the robot is", file=sys.stderr)+ return res++ def get_obs(self, cameras=None, seconds: float = 0.0, video_fps: int | None = None, depth=None, include_depth: bool = False,+ video: str = "frames") -> Result:+ """Current frames (seconds=0, free) or hold the last command and watch for `seconds` (returns the video).+ depth: None | True (= "last": the last frame's depth) | "frames" (one depth map per frame)."""+ meta = {"seconds": float(seconds), "video": video, **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/observe", meta, [], timeout=600)+ if res.stopped:+ print(f"[rcb_client] the service stopped this watch early ({res.stopped}) after {res.meta.get('control_steps_watch')} control "+ "steps", file=sys.stderr)+ return res++ def status(self) -> dict:+ r = requests.get(self.base + "/status", timeout=(5, 60)); r.raise_for_status(); return r.json()++ def wait_ready(self, timeout: float = 3600.0) -> dict:+ """After a connection error: wait until the service answers GET /status again (it resumes the same episode after a+ crash), then return the status. Raises RuntimeError after `timeout` seconds."""+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ try:+ return self.status()+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(5)+ raise RuntimeError(f"sim service did not come back within {timeout:.0f} s: {last}")++ def kinematics(self, body: dict) -> dict:+ """POST /kinematics (stateless: never moves the robot, never advances time). Raises ValueError on a bad request."""+ r = requests.post(self.base + "/kinematics", json=body, timeout=(5, 120))+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ return r.json()++ def fk(self, q, links=None, base_pose=None) -> dict:+ """Forward kinematics: q in spec()['kinematics']['joint_names'] order -> {"ok", "frame", "poses": {link: [x,y,z, quat]}}+ (quaternion order spec()['world']['quaternion_order']; a mobile robot answers in its base frame unless base_pose is given)."""+ body = {"op": "fk", "q": [float(v) for v in np.asarray(q).reshape(-1)]}+ if links is not None: body["links"] = list(links)+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)++ def ik(self, targets: dict, seed=None, base_pose=None, **opts) -> dict:+ """Inverse kinematics: {frame: [x,y,z, quat]} (frames from spec()['kinematics']['ik_targets']) and an optional seed q ->+ {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}. opts: tol_pos_m, tol_rot_rad, max_iters."""+ body = {"op": "ik", "targets": {k: [float(v) for v in p] for k, p in targets.items()}, **opts}+ if seed is not None: body["seed"] = [float(v) for v in np.asarray(seed).reshape(-1)]+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/finalize.sh b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/finalize.shnew file mode 100755index 0000000000..02048ddc74--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/finalize.sh@@ -0,0 +1,80 @@+#!/bin/sh+# [[verifier.collect]] hook, run inside the `sim` sidecar once Harbor has stopped the agent's container.+# 1. `rcb_limited.py end` (docs/STANDARD_MODE_2_2.md §13.3): SIGUSR1 to the service, which ends the episode if the+# agent had not (reason "timeout"), writes trajectory.npz + episode.json (live verdict, final-state hash) and exits.+# It exits 2 when final.json already holds the verdict (the service gave up after crashes): that verdict stays.+# 2. replay the trajectory from the frozen instance in TWO fresh processes (`rcb_quadruped.py replay`, the privileged+# verifier's replay): determinism = fresh process == fresh process; live_matches_replay = live == replay.+# 3. merge everything into final.json, the only thing the verifier sandbox grades;+# 4. a third replay renders replay.mp4, after the verdict is on disk (it never changes it).+set -u+DATA="${RCB_DATA:-/data}"; TOOL="${RCB_TOOL:?}"; INSTANCE="${RCB_INSTANCE:?}"+python /srv/rcb_limited.py end "$DATA" --timeout "${RCB_COLLECT_END_TIMEOUT_S:-900}"; rc=$?+if [ "$rc" = 2 ]; then+ echo "[finalize] final.json already holds the verdict; no replay"; exit 0+fi+if [ "$rc" != 0 ]; then+ echo "[finalize] the service did not end and dump the episode in time (rc $rc): an infrastructure failure"+ python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data"); p = os.path.join(d, "final.json")+try:+ out = json.load(open(p))+except Exception:+ out = {}+out.update({"finalized": True, "success": False, "replay_success": False, "deterministic": False, "infra_error": 1,+ "error": "collect hook: the sim service did not end and dump the episode in time"})+json.dump(out, open(p, "w"))+print(json.dumps(out))+PY+ exit 0+fi+replay() { # <n> [--video FILE]: one replay in a fresh process, its result in $DATA/replay<n>.json+ n=$1; shift+ RCB_SESSION_LOG= python "$TOOL" replay --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --out "$DATA/replay$n.json" \+ "$@" > /dev/null 2> "$DATA/replay$n.log"+ echo "[finalize] replay $n exit $?"+}+echo "[finalize] episode dumped; replaying twice in fresh processes"+rm -f "$DATA/replay1.json" "$DATA/replay2.json" "$DATA/replay3.json"+replay 1+replay 2+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+def result(name):+ try:+ v = json.load(open(os.path.join(d, name)))+ except (OSError, ValueError):+ return {}+ return v if isinstance(v, dict) else {}+out = {"replay_success": False, "deterministic": False, "video": False}+try:+ out.update(json.load(open(os.path.join(d, "episode.json"))))+except Exception as exc:+ out["error"] = f"no episode.json: {exc!r}"+a, b = result("replay1.json"), result("replay2.json")+out["replay_success"] = bool(a.get("success")) and bool(b.get("success"))+out["replay_sha"], out["replay_sha2"] = a.get("state_sha"), b.get("state_sha")+out["deterministic"] = bool(a.get("state_sha")) and a.get("state_sha") == b.get("state_sha")+out["live_matches_replay"] = bool(a.get("state_sha")) and a.get("state_sha") == out.get("live_sha")+if not (a.get("state_sha") and b.get("state_sha")): # a replay process died (it crashed or timed out): not the agent's 0+ out.update({"replay_failed": 1, "infra_error": 1,+ "error": "a replay process gave no result (replay1.log / replay2.log)"})+elif not (a.get("instance_ok") and b.get("instance_ok")): # the image no longer builds the frozen start: not the agent's 0+ out.update({"instance_mismatch": 1, "infra_error": 1, "error": "a replay did not start in the instance's t = 0 state"})+out["finalized"] = True+json.dump(out, open(os.path.join(d, "final.json"), "w"))+print(json.dumps(out))+PY+replay 3 --video "$DATA/replay.mp4"+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+try:+ shown = json.load(open(os.path.join(d, "replay3.json"))).get("video")+except (OSError, ValueError):+ shown = False+if shown:+ p = os.path.join(d, "final.json"); out = json.load(open(p)); out["video"] = True; json.dump(out, open(p, "w"))+PYdiff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/instance.json b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/instance.jsonnew file mode 100644index 0000000000..3ea273b2b3--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/instance.json@@ -0,0 +1,100 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "SpotFlatTerrainJoystick",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 0.46000000834465027,+ 1.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842+ ],+ "qvel0": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 0.7129874229431152,+ "vy": 0.045435335487127304,+ "wz": 0.6093337535858154+ },+ {+ "start_step": 201,+ "vx": -0.18540263175964355,+ "vy": -0.40133342146873474,+ "wz": -0.4772922992706299+ },+ {+ "start_step": 402,+ "vx": 0.6049041748046875,+ "vy": 0.11546879261732101,+ "wz": 0.04899191856384277+ },+ {+ "start_step": 603,+ "vx": 0.0,+ "vy": 0.0,+ "wz": 0.0+ },+ {+ "start_step": 804,+ "vx": -0.28104639053344727,+ "vy": -0.7415485382080078,+ "wz": -0.6673171520233154+ }+ ],+ "text": "Make Boston Dynamics Spot follow the joystick command schedule on flat ground for the whole 20 s episode without falling over.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": 0.0,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.46,+ "reference_rows": 1000,+ "torso_mass_kg": 50.34,+ "reference_worst_lin_err": 0.1555,+ "reference_worst_yaw_err": 0.072+ },+ "state_sha": "53128662ae17",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/rcb1.py b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/rcb_limited.py b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/rcb_limited.pynew file mode 100644index 0000000000..1ce1171787--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/rcb_limited.py@@ -0,0 +1,930 @@+"""eai-standard/2.2 (formerly rcb-limited/2.2): the HTTP layer, the protocol helpers and the crash recovery that every+2.2 sim service shares (docs/STANDARD_MODE_2_2.md; the 2.1 base is docs/LIMITED_MODE_PROTOCOL.md).++The source is scripts/eai_standard/rcb_limited.py; the generators copy it unchanged into every standard task's+environment/sim/ (ci_checks/check-tooling-identity.sh). A service keeps its simulator to itself (scene, action+execution, cameras, kinematic model) and hands this module plain callables:++ import rcb_limited as L+ EP = L.Episode(DATA, dim=N, resume="exact") # before the scene is built; "approx" for a nondeterministic simulator+ EP.startup() # start count, back-off after failed starts, startup watchdog+ S = <build the scene>; EP.scene_built() # the watchdog stands down+ def ctrl_step(a, rec): # every executed control step+ S.step(a); stop = EP.journal(a); rec.tick(); return E["done"] or stop+ rec = L.Recorder(cams, every, grab, proprio_row, extrinsics, clock, depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+ rec.tick(force=True) # first frame (before the chunk / watch)+ ...; rec.tick(); ... # after every control step: a frame every `every` steps+ rec.tick(force=True, last=True) # last frame (+ its depth)+ parts = rec.parts(video, fps) # RCB1 parts: video/ frames/ last/ extrinsic_cv/ last_depth/ depth_frames/ depth/ proprio frame_*+ S.record_start()+ EP.begin(state=E, step=S.step, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, start_event={...}, on_end=end_fn)+ L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics,+ status=status, on_submit_error=lambda exc: finish("error"), log=EP.log,+ episode=EP, state_sha=S.state_sha, proprio=proprio_row))++ grab(cams, want_depth) -> ({cam: uint8 (H,W,3)}, {cam: float32 (H,W) z-depth in metres, 0 = no reading})+ extrinsics(cams) -> {cam: (3,4) world -> camera, OpenCV axes (x right, y down, z forward)}+ proprio_row() -> float32 (len(spec["proprio_layout"]),)+ clock() -> int, control steps since the episode start (the frame's step index)+ do_kinematics(req) -> dict; `req` is parse_kinematics(body, spec["kinematics"]); it must never step physics++None of the callables may step physics. check_spec(SPEC) runs in serve(): a service whose /spec misses a 2.2 field, or+carries a field the protocol forbids (segmentation, object identities or sizes, physical parameters), does not start.+Crash recovery (class Episode; PROTOCOL §4.7): every executed control step is journaled, every completed call+checkpointed (rows, state hash, the robot's proprio row); after a crash compose restarts the container and the service+replays the journal and continues the SAME episode, never a reset. `python rcb_limited.py end <data dir>` is the shared+first half of a collect hook."""+from __future__ import annotations+import faulthandler, json, math, os, re, select, signal, socket, sys, tempfile, threading, time, traceback, zlib+from http.server import BaseHTTPRequestHandler, HTTPServer+from typing import Any, Callable++import numpy as np++import rcb1++PROTOCOL = "eai-standard/2.2"+COMPAT = ["rcb-limited/2.0", "rcb-limited/2.1", "eai-standard/2.1"] # requests written for these are served unchanged+MAX_BODY = 64 * 1024 * 1024+MAX_RESP = 256 * 1024 * 1024+DEPTH_MODES = ("none", "last", "frames")+DEPTH_MAX_M = 65.535 # uint16 millimetres; a farther surface reads 0 (no reading)+DEPTH_NOISE = os.environ.get("RCB_DEPTH_NOISE", "off").strip().lower() # off | realsense (as rcb-limited/2.1)+_RNG = np.random.default_rng(int(os.environ.get("RCB_DEPTH_NOISE_SEED", "0")))+PROPRIO_GROUPS_REQUIRED = ("joint_pos", "joint_vel", "gripper_opening", "tcp_pose", "joint_effort")+PART_PREFIXES = ("video/", "frames/", "last/", "last_depth/", "depth_frames/", "depth/", "extrinsic_cv/")+PART_NAMES = ("proprio", "frame_step", "frame_time_s")+++# ---------------------------------------------------------------- depth+def depth_mode(meta: dict) -> str:+ """The request's depth mode: "none" | "last" | "frames" (2.2 field `depth`), or "legacy" for a 2.0/2.1 request that+ sets `include_depth: true` and no `depth` (answered as 2.1 did: `depth/<cam>` float16 (N,H,W) metres)."""+ d = meta.get("depth")+ if d is None or d is False:+ return "legacy" if meta.get("include_depth") is True else "none"+ if d is True:+ return "last"+ if isinstance(d, str) and d in DEPTH_MODES:+ return d+ raise ValueError(f"depth must be one of {'|'.join(DEPTH_MODES)} (got {d!r})")+++def clean_depth(z) -> np.ndarray:+ """float32 z-depth in metres: non-finite, negative and beyond-range pixels read 0 (no reading); the optional+ RCB_DEPTH_NOISE=realsense model (sigma = 2 mm + 2.5 mm * z^2, 1 % dropouts) is applied here, after rendering, so it+ never touches physics."""+ z = np.asarray(z, dtype=np.float32).copy()+ if z.ndim == 3 and z.shape[-1] == 1:+ z = z[..., 0]+ bad = ~np.isfinite(z) | (z <= 0) | (z > DEPTH_MAX_M)+ z[bad] = 0.0+ if DEPTH_NOISE == "realsense":+ valid = z > 0+ z = z + _RNG.normal(0.0, 1.0, z.shape).astype(np.float32) * (0.002 + 0.0025 * z * z)+ z[_RNG.random(z.shape) < 0.01] = 0.0+ z[~valid] = 0.0+ z[(z < 0) | (z > DEPTH_MAX_M)] = 0.0+ return z.astype(np.float32)+++def depth_frames_part(name: str, stack: np.ndarray) -> tuple[str, str, bytes, dict]:+ """(N,H,W) metres -> an RCB1 "bytes" part: zlib of C-order uint16 millimetres (0 = no reading). Clients that do not+ know it keep the raw bytes and ignore it; rcb_client decodes it back to float32 metres."""+ mm = np.rint(np.asarray(stack, dtype=np.float64) * 1000.0)+ mm[(mm < 0) | (mm > 65535)] = 0+ a = np.ascontiguousarray(mm.astype("<u2"))+ return (name, "bytes", zlib.compress(a.tobytes(), 1), {"codec": "zlib", "dtype": "uint16", "shape": list(a.shape), "unit": "mm"})+++def encode_mp4(frames: np.ndarray, fps: int) -> bytes:+ """H.264 mp4 (yuv420p, faststart) of uint8 (N,H,W,3) frames: the same encoding every 2.0 service used."""+ import imageio.v2 as imageio+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tf:+ path = tf.name+ try:+ with imageio.get_writer(path, format="FFMPEG", mode="I", fps=fps, codec="libx264", macro_block_size=1,+ output_params=["-movflags", "+faststart", "-pix_fmt", "yuv420p"]) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ return open(path, "rb").read()+ finally:+ try:+ os.unlink(path)+ except OSError:+ pass+++# ---------------------------------------------------------------- recording what the cameras see during one call+class Recorder:+ """Frames of the requested cameras every `every` clock ticks, plus forced first/last frames; for every frame the+ proprio row, the clock (step index), each camera's extrinsics and, if asked, its depth. All arrays share one frame+ axis N: frames/<cam>, the mp4's frames, proprio, frame_step, frame_time_s, extrinsic_cv/<cam>, depth_frames/<cam>."""++ def __init__(self, cameras, every: int, grab: Callable, proprio_row: Callable, extrinsics: Callable, clock: Callable,+ depth: str = "none", clock_hz: float = 1.0):+ if depth not in DEPTH_MODES + ("legacy",):+ raise ValueError(f"bad depth mode {depth!r}")+ self.cams = list(cameras); self.every = max(1, int(every)); self.mode = depth; self.hz = float(clock_hz)+ self._grab, self._prop, self._ext, self._clock = grab, proprio_row, extrinsics, clock+ self.frames: dict = {c: [] for c in self.cams}; self.depth: dict = {c: [] for c in self.cams}+ self.ext: dict = {c: [] for c in self.cams}; self.last_depth: dict = {}+ self.prop: list = []; self.steps: list = []; self.n = 0; self.missing = 0++ def tick(self, force: bool = False, last: bool = False) -> None:+ if force or last or self.n % self.every == 0:+ self._capture(last)+ self.n += 1++ def _capture(self, last: bool) -> None:+ want = self.mode in ("frames", "legacy") or (last and self.mode == "last")+ rgb, dep = self._grab(self.cams, want)+ ext = self._ext(self.cams)+ for c in self.cams:+ img = rgb.get(c)+ if img is not None:+ img = np.ascontiguousarray(np.asarray(img)[..., :3].astype(np.uint8))+ else: # a camera that failed to render: a black frame (sized in parts()) keeps one frame axis+ self.missing += 1+ self.frames[c].append(img)+ e = ext.get(c)+ self.ext[c].append(np.full((3, 4), np.nan) if e is None else np.asarray(e, dtype=np.float64).reshape(3, 4))+ if want:+ d = dep.get(c)+ if d is None:+ d = np.zeros(img.shape[:2] if img is not None else (1, 1), np.float32)+ else:+ d = clean_depth(d)+ if img is not None and d.shape != img.shape[:2]:+ raise RuntimeError(f"depth of {c} is {d.shape}, its RGB {img.shape[:2]}: they must be pixel-aligned")+ if self.mode in ("frames", "legacy"):+ self.depth[c].append(d)+ if last or self.mode == "frames":+ self.last_depth[c] = d+ self.prop.append(np.asarray(self._prop(), dtype=np.float32).reshape(-1))+ self.steps.append(int(self._clock()))++ def parts(self, video: str, fps: int) -> list:+ if self.mode == "last" and not self.last_depth and self.prop: # no last=True tick: the state has not moved since+ _, dep = self._grab(self.cams, True)+ self.last_depth = {c: clean_depth(dep[c]) for c in self.cams if c in dep}+ out = []+ for c in self.cams:+ good = [f for f in self.frames[c] if f is not None]+ hw = good[-1].shape[:2] if good else (1, 1)+ if len(good) < len(self.frames[c]):+ self.frames[c] = [f if f is not None else np.zeros(hw + (3,), np.uint8) for f in self.frames[c]]+ self.depth[c] = [d if d.shape == hw else np.zeros(hw, np.float32) for d in self.depth[c]]+ if c in self.last_depth and self.last_depth[c].shape != hw:+ self.last_depth[c] = np.zeros(hw, np.float32)+ fr = np.stack(self.frames[c]) if self.frames[c] else np.zeros((0, 1, 1, 3), np.uint8)+ if video in ("mp4", "both") and len(fr):+ out.append((f"video/{c}", "mp4", encode_mp4(fr, fps), {"fps": fps, "n": int(len(fr))}))+ if video in ("frames", "both"):+ out.append(rcb1.array_part(f"frames/{c}", fr))+ if len(fr):+ out.append(rcb1.array_part(f"last/{c}", fr[-1]))+ out.append(rcb1.array_part(f"extrinsic_cv/{c}", np.stack(self.ext[c]) if self.ext[c] else np.zeros((0, 3, 4))))+ if self.mode in ("last", "frames") and c in self.last_depth:+ out.append(rcb1.array_part(f"last_depth/{c}", self.last_depth[c]))+ if self.mode == "frames" and self.depth[c]:+ out.append(depth_frames_part(f"depth_frames/{c}", np.stack(self.depth[c])))+ if self.mode == "legacy" and self.depth[c]:+ out.append(rcb1.array_part(f"depth/{c}", np.stack(self.depth[c]).astype(np.float16)))+ out.append(rcb1.array_part("proprio", np.stack(self.prop) if self.prop else np.zeros((0, 0), np.float32)))+ st = np.asarray(self.steps, dtype=np.int64)+ out.append(rcb1.array_part("frame_step", st))+ out.append(rcb1.array_part("frame_time_s", st.astype(np.float64) / self.hz))+ return out+++def encode_response(meta: dict, parts: list, max_bytes: int = MAX_RESP) -> bytes:+ """The RCB1 body; over `max_bytes` the per-frame depth goes first, then the raw frames (mp4, last frames, last+ depth, proprio and the per-frame arrays always stay), and meta["degraded"] says what was dropped."""+ body = rcb1.encode(meta, parts)+ dropped = []+ for prefixes in (("depth_frames/", "depth/"), ("frames/",)):+ if len(body) <= max_bytes:+ break+ keep = [p for p in parts if not p[0].startswith(prefixes)]+ if len(keep) < len(parts):+ parts = keep; dropped += [x.rstrip("/") for x in prefixes]+ body = rcb1.encode({**meta, "degraded": f"response over {max_bytes} bytes: {', '.join(dropped)} dropped"}, parts)+ return body+++# ---------------------------------------------------------------- kinematics+def _vec(x, n: int, what: str) -> list:+ a = np.asarray(x, dtype=np.float64).reshape(-1) if x is not None else None+ if a is None or a.size != n or not np.all(np.isfinite(a)):+ raise ValueError(f"{what} must be {n} finite numbers")+ return a.tolist()+++def _pose(x, what: str) -> list:+ p = _vec(x, 7, what)+ nq = math.sqrt(sum(v * v for v in p[3:]))+ if nq < 1e-6:+ raise ValueError(f"{what}: quaternion has zero norm")+ return p[:3] + [v / nq for v in p[3:]]+++def parse_kinematics(body: dict, kin: dict) -> dict:+ """Validate a /kinematics request against spec["kinematics"] (ValueError -> 400). Returns+ {"op": "fk", "q", "links", "base_pose"} or {"op": "ik", "targets": {frame: pose7}, "seed", "base_pose", "tol_pos_m",+ "tol_rot_rad", "max_iters"}; poses are x y z + a unit quaternion in the spec's order; q follows kin["joint_names"]."""+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object")+ op = body.get("op"); n = len(kin["joint_names"])+ base = None+ if body.get("base_pose") is not None:+ if kin.get("frame") != "base":+ raise ValueError("base_pose is only accepted by a mobile robot (spec kinematics.frame == 'base')")+ base = _pose(body["base_pose"], "base_pose")+ if op == "fk":+ links = body.get("links") or list(kin["links"])+ if not isinstance(links, list) or any(l not in kin["links"] for l in links):+ raise ValueError(f"links must be a list of names from spec kinematics.links: {kin['links']}")+ return {"op": "fk", "q": _vec(body.get("q"), n, "q"), "links": links, "base_pose": base}+ if op == "ik":+ tg = body.get("targets")+ if not isinstance(tg, dict) or not tg or any(k not in kin["ik_targets"] for k in tg):+ raise ValueError(f"targets must map frames from spec kinematics.ik_targets {kin['ik_targets']} to poses")+ ik = kin.get("ik", {})+ seed = None if body.get("seed") is None else _vec(body["seed"], n, "seed")+ tol_p = float(body.get("tol_pos_m", ik.get("tol_pos_m", 0.005)))+ tol_r = float(body.get("tol_rot_rad", ik.get("tol_rot_rad", 0.05)))+ it = int(body.get("max_iters", ik.get("max_iters", 200)))+ if not (1e-5 <= tol_p <= 0.5 and 1e-4 <= tol_r <= 3.2 and 1 <= it <= 5000):+ raise ValueError("tol_pos_m in [1e-5, 0.5], tol_rot_rad in [1e-4, 3.2], max_iters in [1, 5000]")+ return {"op": "ik", "targets": {k: _pose(v, f"targets[{k}]") for k, v in tg.items()}, "seed": seed, "base_pose": base,+ "tol_pos_m": tol_p, "tol_rot_rad": tol_r, "max_iters": it}+ raise ValueError("op must be 'fk' or 'ik'")+++def fk_response(poses: dict, frame: str) -> dict:+ return {"ok": True, "op": "fk", "frame": frame, "poses": {k: [float(v) for v in np.asarray(p, dtype=np.float64).reshape(7)] for k, p in poses.items()}}+++def ik_response(q, ok: bool, errors: dict, frame: str, note: str | None = None) -> dict:+ """errors: {frame: (position error m, rotation error rad)} of the returned q (None / non-finite -> null: no solution)."""+ fin = lambda v: float(v) if v is not None and math.isfinite(float(v)) else None # noqa: E731+ out = {"ok": bool(ok), "op": "ik", "frame": frame, "q": None if q is None else [float(v) for v in np.asarray(q).reshape(-1)],+ "error": {k: {"pos_m": fin(e[0]), "rot_rad": fin(e[1])} for k, e in errors.items()}}+ if note:+ out["note"] = note+ return out+++def quat_angle(q1, q2) -> float:+ """Rotation angle (rad) between two unit quaternions of the same order."""+ d = abs(float(np.dot(np.asarray(q1, dtype=np.float64), np.asarray(q2, dtype=np.float64))))+ return 2.0 * math.acos(min(1.0, d))+++# ---------------------------------------------------------------- /spec self-check+FORBIDDEN_KEY = re.compile(r"mask|segment|semantic(?!s$)|instance_?id|bbox|bounding|categor|object|\bobj_|label|mass|friction|"+ r"restitution|inertia|density|damping|stiffness", re.I)+GAIN_PATHS = ("robot_spec.controller",) # joint drive gains (stiffness, damping) are the robot's own, and allowed there+POSITION_KEY = re.compile(r"(?:^|_)(?:pos|position|positions|pose|poses|origin|location|coords?|coordinates|world|translation)(?:_|$)|"+ r"(?:^|_)cent(?:er|re)s?(?:_|$)|(?:^|_)xyz?$|(?:^|_)(?:top|surface|floor|table|plane|height|elevation)?_?z$", re.I)+WORLD_TEXT = re.compile(r"\bworld\s+[xyz]\s*=", re.I)+COORDS = re.compile(r"\(\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*(?:,\s*-?\d+(?:\.\d+)?\s*)?\)")+++def world_text(s: str) -> bool:+ """A text that gives a world coordinate: a pixel-to-world formula, or a coordinate tuple with a decimal point that is+ not the robot's own pose ("robot base at (0, 0, 1.08)" stays)."""+ return bool(WORLD_TEXT.search(s)) or any("." in m.group(0) and not re.search(r"base|robot|origin", s[max(0, m.start() - 40):m.start()], re.I)+ for m in COORDS.finditer(s))+CONVENTIONS = {"static.floor_z": 0.0} # BEHAVIOR: the floor is the plane z = 0 (the world frame's definition)+++def static_positions(obj: Any, path: str = "static") -> list[str]:+ """Paths in /spec static that say WHERE something is (keys naming positions, heights, centres; texts with world+ coordinates). Names, inventories, sizes and colours may stay in static; positions never (docs § Never provided)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}"+ if POSITION_KEY.search(str(k)) and CONVENTIONS.get(p, object()) != v:+ out.append(p)+ else:+ out += static_positions(v, p)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += static_positions(v, f"{path}[{i}]")+ elif isinstance(obj, str) and world_text(obj):+ out.append(path)+ return out+++SPEC_REQUIRED = ("protocol", "protocol_compat", "simulator", "robot", "task_text", "control_hz", "cameras", "default_cameras",+ "action_types", "proprio_layout", "proprio_groups", "static", "world", "budget", "robot_spec", "kinematics", "depth")+++def forbidden_keys(obj: Any, path: str = "", skip: tuple = ()) -> list[str]:+ """Key paths that name something the protocol never provides (key paths in `skip` are not searched)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}" if path else str(k)+ if p in skip:+ continue+ if FORBIDDEN_KEY.search(str(k)) and not (re.search(r"damping|stiffness", str(k), re.I) and p.startswith(GAIN_PATHS)):+ out.append(p)+ out += forbidden_keys(v, p, skip)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += forbidden_keys(v, f"{path}[{i}]", skip)+ return out+++def check_spec(spec: dict) -> None:+ """Raise if /spec is not a complete 2.2 spec or names anything forbidden (run at startup, before binding :8000)."""+ miss = [k for k in SPEC_REQUIRED if k not in spec]+ if miss:+ raise RuntimeError(f"/spec misses {miss}")+ if spec["protocol"] != PROTOCOL:+ raise RuntimeError(f"/spec protocol {spec['protocol']!r} != {PROTOCOL}")+ bad = forbidden_keys(spec, skip=())+ if bad:+ raise RuntimeError(f"/spec names forbidden fields: {bad}")+ pos = static_positions(spec["static"])+ if pos:+ raise RuntimeError(f"/spec static says where things are (never provided): {pos}")+ lay = spec["proprio_layout"]+ if len(set(lay)) != len(lay):+ raise RuntimeError("proprio_layout names are not unique")+ for g in PROPRIO_GROUPS_REQUIRED:+ if g not in spec["proprio_groups"]:+ raise RuntimeError(f"proprio_groups misses {g}")+ for g, (first, n, _meaning) in spec["proprio_groups"].items():+ if not (0 <= first and first + n <= len(lay)):+ raise RuntimeError(f"proprio group {g} [{first}, +{n}) outside the {len(lay)} columns")+ kin = spec["kinematics"]+ for k in ("endpoint", "joint_names", "frame", "quaternion_order", "links", "tcp_frames", "ee_frames", "ik_targets"):+ if k not in kin:+ raise RuntimeError(f"kinematics misses {k}")+ if any(j not in lay for j in kin["joint_names"]):+ raise RuntimeError("kinematics.joint_names must be proprio_layout columns (the measured joint positions)")+ if any(f not in kin["links"] for f in list(kin["tcp_frames"]) + list(kin["ee_frames"]) + list(kin["ik_targets"])):+ raise RuntimeError("kinematics tcp_frames / ee_frames / ik_targets must be listed in kinematics.links")+ if spec["proprio_groups"]["tcp_pose"][1] != 7 * len(kin["tcp_frames"]):+ raise RuntimeError("proprio group tcp_pose must hold 7 columns per kinematics.tcp_frames entry")+ for c, cam in spec["cameras"].items():+ for k in ("rgb", "depth", "mounted", "resolution", "intrinsic_cv", "mount"):+ if k not in cam:+ raise RuntimeError(f"cameras.{c} misses {k}")+ if cam["mount"].get("type") not in ("static", "link"):+ raise RuntimeError(f"cameras.{c}.mount.type must be static|link")+ if any(c not in spec["cameras"] for c in spec["default_cameras"]):+ raise RuntimeError("default_cameras must be cameras")+++# ---------------------------------------------------------------- crash recovery (PROTOCOL §4.7; docs/STANDARD_MODE_2_2.md)+MAX_RESUMES = int(os.environ.get("RCB_MAX_RESUMES", "2"))+STARTUP_TIMEOUT_S = float(os.environ.get("RCB_STARTUP_TIMEOUT_S", "900")) # a task with a slower scene build sets more+MAX_CALL_WALL_S = float(os.environ.get("RCB_MAX_CALL_WALL_S", "900")) # < the client's 1800 s /submit read timeout+RESUME_MAX_DEV_M = float(os.environ.get("RCB_RESUME_MAX_DEV_M", "0.05")) # approx resumes: the gross-divergence guard+ON_SERVICE_ERROR = ("a connection error means the service crashed: it restarts and resumes the SAME episode (never a reset) "+ "in the state after the last call it completed, which you may not have received. Wait until GET /status "+ "answers again (rcb_client: Robot.wait_ready(); resuming replays the episode so far, which can take "+ "minutes in a long episode, and the wall clock keeps running), then check calls and control_steps "+ "before you continue. A 500 means the simulator failed: the episode is over (reason \"error\"). A call "+ "that runs longer than max_call_wall_s seconds stops at the next control step and returns what it "+ "executed (meta.stopped, executed_rows).")+++def _jsonable(v: Any) -> Any:+ if isinstance(v, np.ndarray):+ return v.tolist()+ if isinstance(v, (np.floating, np.integer, np.bool_)):+ return v.item()+ if isinstance(v, (list, tuple)):+ return [_jsonable(x) for x in v]+ if isinstance(v, dict):+ return {str(k): _jsonable(x) for k, x in v.items()}+ return v+++def _peer_closed(sock) -> bool:+ """True when the client of an HTTP request has closed its connection (it gave up on the call): the socket reads as+ end-of-file. A client never sends anything while it waits for the response, so readable means closed."""+ try:+ r, _, _ = select.select([sock], [], [], 0)+ return bool(r) and sock.recv(1, socket.MSG_PEEK) == b""+ except (OSError, ValueError):+ return True+++def _read_json(path: str) -> dict:+ try:+ with open(path) as f:+ d = json.load(f)+ return d if isinstance(d, dict) else {}+ except (OSError, ValueError):+ return {}+++def _write_json(path: str, obj: dict) -> None:+ tmp = f"{path}.{os.getpid()}.tmp"+ with open(tmp, "w") as f:+ json.dump(obj, f)+ os.replace(tmp, path)+++def final_verdict(data: str) -> dict | None:+ """final.json if it already holds a verdict that nothing may overwrite: the grading result (finalized, with+ `deterministic`) or the end of an episode the service gave up after crashes (`gave_up`)."""+ fin = _read_json(os.path.join(data, "final.json"))+ if fin.get("finalized") and (fin.get("gave_up") or fin.get("deterministic") is not None):+ return fin+ return None+++class Episode:+ """Crash-safe episode bookkeeping, the same rules as the RoboTwin and MuJoCo services (PROTOCOL §4.7):++ - startup(): before the scene is built. One line in startups.jsonl; a back-off of min(120, 20 (n - 1)) s when the+ earlier starts never began an episode (they crashed while building, e.g. GPU memory taken by other trials); the+ startup watchdog (faulthandler, a C thread: it fires even when a native scene build holds the GIL) dumps every+ thread's traceback and exits 1 after RCB_STARTUP_TIMEOUT_S, so compose restarts the build. Until begin() a SIGUSR1+ (the collect hook's "the agent phase is over") is only remembered.+ - journal(row): every executed control step (the exact row given to the simulator's step) goes to journal.f64.+ - checkpoint(): after every completed call (the HTTP layer calls it): the journal is flushed, then the call's+ checkpoint is logged in episode.jsonl (rows, control steps, state hash, the robot's proprio row, `persist` keys).+ - begin(): a fresh episode, or after a crash (run.sh exits non-zero, compose restarts the container, `restart:+ on-failure:N`) the SAME episode resumed: the journal is replayed up to the last checkpoint, the journal truncated+ there (the call that was in flight is lost as a whole: its caller got an error, not a result), the state hash+ compared, the service's counters restored; the wall clock keeps running from the first start.+ - Resume check, by the simulator's determinism class: `exact` (bit-exact in a fresh process): the hash must match,+ else the episode ends `resume_failed` (infra_error). `approx` (a simulator declared nondeterministic): a+ mismatch is recorded (resume_state_mismatch, and the robot's deviation from its checkpointed proprio: joint_pos and+ tcp_pose) and the episode continues, unless a TCP is more than RCB_RESUME_MAX_DEV_M from where it was+ (resume_failed, infra_error). The verdict never comes from the live state but from fresh replays of the complete+ recorded trajectory, so continuing cannot raise a score.+ - More than RCB_MAX_RESUMES crashes end the episode: `sim_crashed_on_call` if every crash happened while a call was+ being served (the agent's failure), else `sim_crashed` (infra_error = 1). A verdict already on disk is never+ overwritten; the service then idles with its PID file for the collect hook.+ - Per call, two bounds keep one call from holding the single-threaded service: a call that runs longer than+ max_call_wall_s, or whose client has hung up, stops at the next control step and returns what it executed+ (journal() returns True; meta.stopped says why). Neither bounds the episode: the wall clock is its only budget."""++ def __init__(self, data: str, dim: int, resume: str = "exact", persist: tuple = ()):+ if resume not in ("exact", "approx"):+ raise ValueError("resume must be 'exact' or 'approx'")+ self.data, self.dim, self.resume_class, self.persist = data, int(dim), resume, tuple(persist)+ os.makedirs(data, exist_ok=True)+ p = lambda n: os.path.join(data, n) # noqa: E731+ self.f_events, self.f_journal, self.f_final, self.f_pid, self.f_startups = (+ p("episode.jsonl"), p("journal.f64"), p("final.json"), p("server.pid"), p("startups.jsonl"))+ self.rows = 0 # control steps executed in this episode (journaled)+ self.max_call_wall_s = MAX_CALL_WALL_S+ self.n_startups = 0; self.resumes = 0; self.mismatches = 0; self.max_tcp_dev = 0.0; self.max_joint_dev = 0.0+ self._jf = None; self._call: dict | None = None; self._ids = 0; self._ck: tuple | None = None+ self._on_end: Callable | None = None; self._end_pending = False++ # ---- startup+ def startup(self) -> None:+ signal.signal(signal.SIGUSR1, self._usr1)+ try:+ os.remove(self.f_pid) # a PID file from before a crash would send the collect hook to a dead process+ except OSError:+ pass+ with open(self.f_startups, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid()}) + "\n")+ with open(self.f_startups) as f:+ self.n_startups = sum(1 for line in f if line.strip())+ if self.n_startups > 1 and not any(e.get("ev") == "start" for e in self.events()):+ time.sleep(min(120.0, 20.0 * (self.n_startups - 1)))+ faulthandler.dump_traceback_later(STARTUP_TIMEOUT_S, exit=True)++ def scene_built(self) -> None:+ faulthandler.cancel_dump_traceback_later() # the scene exists: a resume replay may take long, it is not a hang++ def _usr1(self, *_):+ if self._on_end is None:+ self._end_pending = True+ else:+ threading.Thread(target=self._on_end, daemon=True).start()++ # ---- the record+ def log(self, ev: dict) -> None:+ with open(self.f_events, "a") as f:+ f.write(json.dumps(_jsonable({"ts": time.time(), **ev})) + "\n")++ def events(self) -> list:+ out = []+ try:+ with open(self.f_events) as f:+ for line in f:+ try:+ out.append(json.loads(line))+ except ValueError: # a line cut by a crash+ pass+ except OSError:+ pass+ return [e for e in out if isinstance(e, dict)]++ def journal(self, row) -> bool:+ """One executed control step. True: the call in progress must stop at this step boundary (meta.stopped)."""+ a = np.asarray(row, dtype=np.float64).reshape(-1)+ if a.size != self.dim:+ raise ValueError(f"journal rows have {self.dim} entries, got {a.size}")+ if self._jf is None:+ self._jf = open(self.f_journal, "ab")+ self._jf.write(a.tobytes()); self.rows += 1+ c = self._call+ if c is None:+ return False+ if c["stopped"] is None:+ now = time.monotonic()+ if now - c["t0"] > self.max_call_wall_s:+ c["stopped"] = "max_call_wall_s"+ elif c["sock"] is not None and now - c["polled"] >= 0.2:+ c["polled"] = now+ if _peer_closed(c["sock"]):+ c["stopped"] = "client_disconnected"+ return c["stopped"] is not None++ @property+ def stopping(self) -> bool:+ """The call in progress must stop (adapters whose loops test E["done"] test this too)."""+ return bool(self._call and self._call["stopped"])++ @property+ def stop_reason(self) -> str | None:+ return self._call["stopped"] if self._call else None++ def call_begin(self, path: str, sock=None) -> int:+ self._ids += 1+ if path != "/kinematics":+ self._call = {"id": self._ids, "t0": time.monotonic(), "sock": sock, "polled": 0.0, "stopped": None}+ self.log({"ev": "call_begin", "id": self._ids, "path": path})+ return self._ids++ def call_end(self, cid: int, path: str, **extra) -> None:+ self.log({"ev": "call_end", "id": cid, "path": path, **extra})+ if path != "/kinematics":+ self._call = None++ def checkpoint(self, state: dict, state_sha: Callable | None, proprio: Callable | None) -> None:+ if self._jf is not None:+ self._jf.flush() # the rows reach the file before the checkpoint that counts them+ if self._ck is not None and self._ck[0] == self.rows:+ sha, pr = self._ck[1], self._ck[2] # no physics since the last checkpoint+ else:+ try:+ sha = state_sha() if state_sha else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); sha = None+ pr = self._proprio_row(proprio)+ self._ck = (self.rows, sha, pr)+ self.log({"ev": "checkpoint", "call": int(state.get("calls") or 0), "step": int(state.get("step") or 0),+ "control_steps": self.rows, "success": bool(state.get("success")), "done": bool(state.get("done")),+ "reason": state.get("reason"), "state_sha": sha, "proprio": pr,+ **({"persist": {k: state.get(k) for k in self.persist}} if self.persist else {})})++ @staticmethod+ def _proprio_row(proprio: Callable | None) -> list | None:+ try:+ return [round(float(v), 6) for v in np.asarray(proprio(), dtype=np.float64).reshape(-1)] if proprio else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); return None++ def final_fields(self) -> dict:+ """Crash-recovery fields for final.json / episode.json (all numeric, for reward.json)."""+ return {"sim_startups": self.n_startups, "resumes": self.resumes, "resume_state_mismatch": int(self.mismatches > 0),+ "resume_max_tcp_dev_m": round(self.max_tcp_dev, 6), "resume_max_joint_dev": round(self.max_joint_dev, 6)}++ # ---- start or resume+ def begin(self, *, state: dict, step: Callable, state_sha: Callable, proprio: Callable, spec: dict,+ start_event: dict | None = None, on_end: Callable | None = None) -> bool:+ """Start the episode, or resume it after a crash. `step(row)` executes one journaled row on the simulator (the+ recorder on, no rendering needed); `on_end` is what the collect hook's SIGUSR1 runs (in a thread). Returns True+ if the episode was resumed."""+ try: # a line cut by the crash must not swallow the next record+ with open(self.f_events, "rb+") as f:+ f.seek(0, os.SEEK_END)+ if f.tell():+ f.seek(-1, os.SEEK_END)+ if f.read(1) != b"\n":+ f.write(b"\n")+ except OSError:+ pass+ ev = self.events()+ starts = [e for e in ev if e.get("ev") == "start"]+ if not starts:+ try:+ os.remove(self.f_journal)+ except OSError:+ pass+ sha = state_sha()+ self._ck = (0, sha, self._proprio_row(proprio))+ self.log({**(start_event or {}), "ev": "start", "state_sha": sha, "protocol": PROTOCOL, "resume": self.resume_class,+ "journal_dim": self.dim})+ state["t0"] = time.time()+ self._arm(on_end)+ return False+ tries = [e for e in ev if e.get("ev") == "resuming"] # earlier resumes (a crash during one counts too)+ resumed = [e for e in ev if e.get("ev") == "resumed"]+ self.resumes = len(tries) # the record so far, also for a give-up below (final_fields)+ self.mismatches = sum(1 for e in resumed if e.get("exact") is False)+ self.max_tcp_dev = max([float(e.get("tcp_dev_m") or 0) for e in resumed] + [0.0])+ self.max_joint_dev = max([float(e.get("joint_dev") or 0) for e in resumed] + [0.0])+ if final_verdict(self.data):+ self.give_up("restarted after finalize", infra=False)+ k = max(i for i, e in enumerate(ev) if e.get("ev") in ("start", "resuming", "resumed"))+ tail = ev[k + 1:]+ in_call = bool({e.get("id") for e in tail if e.get("ev") == "call_begin"} - {e.get("id") for e in tail if e.get("ev") == "call_end"})+ if len(tries) >= MAX_RESUMES:+ agent = sum(1 for e in tries if e.get("crashed_in_call")) + int(in_call) == len(tries) + 1+ self.give_up("sim_crashed_on_call" if agent else "sim_crashed", infra=not agent)+ self.log({"ev": "resuming", "attempt": len(tries) + 1, "crashed_in_call": in_call,+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self.resumes = len(tries) + 1 # this attempt counts, whether or not it succeeds+ cps = [e for e in ev if e.get("ev") == "checkpoint"]+ last = cps[-1] if cps else {"call": 0, "step": 0, "control_steps": 0, "success": False, "state_sha": starts[0].get("state_sha")}+ n = int(last.get("control_steps") or 0)+ try:+ R = np.fromfile(self.f_journal, dtype=np.float64)+ except (OSError, ValueError):+ R = np.zeros(0)+ if R.size < n * self.dim:+ self.give_up("resume_failed: journal shorter than the log", infra=True)+ R = R[: n * self.dim].reshape(n, self.dim)+ t = time.time()+ for row in R:+ step(row)+ replay_s = time.time() - t+ R.tofile(self.f_journal) # drop the rows of the call that was in flight+ self.rows = n+ sha = state_sha(); want = last.get("state_sha")+ exact = None if want is None else sha == want+ dev = self._deviation(last.get("proprio"), proprio, spec)+ if exact is False: # recorded first: a give-up below reports it too+ self.mismatches += 1+ self.max_tcp_dev = max(self.max_tcp_dev, dev.get("tcp_m") or 0.0)+ self.max_joint_dev = max(self.max_joint_dev, dev.get("joint") or 0.0)+ if self.resume_class == "exact":+ self.give_up("resume_failed: replayed state differs from the logged one", infra=True)+ if dev.get("tcp_m") is not None and dev["tcp_m"] > RESUME_MAX_DEV_M:+ self.give_up(f"resume_failed: a replayed TCP is {dev['tcp_m']:.3f} m from its checkpoint (> {RESUME_MAX_DEV_M} m)", infra=True)+ state["calls"] = int(last.get("call") or 0); state["step"] = int(last.get("step") or 0)+ if "success" in state:+ state["success"] = bool(last.get("success"))+ for key, v in (last.get("persist") or {}).items():+ state[key] = v+ state["t0"] = float(starts[0]["ts"])+ ended = [e for e in ev if e.get("ev") == "end" and int(e.get("control_steps") or 0) <= n] # not the lost call's+ if ended:+ state["done"] = True; state["reason"] = ended[-1].get("reason"); state["t_end"] = float(ended[-1]["ts"])+ state["episode_control_steps"] = int(ended[-1].get("control_steps") or n)+ self._ck = (n, sha, self._proprio_row(proprio)) # the replayed state's row (it may differ under approx)+ self.log({"ev": "resumed", "attempt": self.resumes, "control_steps": n, "calls": state["calls"], "state_sha": sha,+ "logged_sha": want, "exact": exact, "class": self.resume_class, "tcp_dev_m": dev.get("tcp_m"),+ "joint_dev": dev.get("joint"), "crashed_in_call": in_call, "replay_s": round(replay_s, 1),+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self._arm(on_end)+ return True++ @staticmethod+ def _deviation(ref, proprio: Callable, spec: dict) -> dict:+ """The replayed robot against its checkpointed proprio row: max |joint_pos| difference (rad or m) and the largest+ TCP position error (m) over the tcp_pose frames (7 columns each: x y z + quaternion)."""+ if ref is None:+ return {}+ try:+ now = np.asarray(proprio(), dtype=np.float64).reshape(-1); ref = np.asarray(ref, dtype=np.float64).reshape(-1)+ except Exception: # noqa: BLE001+ return {}+ if now.shape != ref.shape:+ return {}+ g, out = spec.get("proprio_groups") or {}, {}+ if "joint_pos" in g:+ f, n = int(g["joint_pos"][0]), int(g["joint_pos"][1])+ out["joint"] = float(np.max(np.abs(now[f:f + n] - ref[f:f + n]))) if n else 0.0+ if "tcp_pose" in g:+ f, n = int(g["tcp_pose"][0]), int(g["tcp_pose"][1]); m = n // 7+ d = (now[f:f + 7 * m] - ref[f:f + 7 * m]).reshape(m, 7)[:, :3]+ out["tcp_m"] = float(np.max(np.linalg.norm(d, axis=1))) if m else 0.0+ return out++ def _arm(self, on_end: Callable | None) -> None:+ self._on_end = on_end+ signal.signal(signal.SIGUSR1, self._usr1)+ if on_end is not None and self._end_pending:+ self._end_pending = False+ threading.Thread(target=on_end, daemon=True).start()++ def give_up(self, reason: str, infra: bool) -> None:+ """End the trial's episode without a new one (never a reset): log it, write the verdict unless one is on disk,+ leave the PID file for the collect hook, and idle until the container is removed."""+ faulthandler.cancel_dump_traceback_later()+ self.log({"ev": "restart_refused", "reason": reason})+ if not final_verdict(self.data):+ fin = _read_json(self.f_final)+ fin.update({"success": False, "done": True, "reason": reason, "finalized": True, "gave_up": True, "protocol": PROTOCOL,+ **self.final_fields(), **({"infra_error": 1} if infra else {})})+ _write_json(self.f_final, fin)+ with open(self.f_pid, "w") as f:+ f.write(str(os.getpid()))+ signal.signal(signal.SIGUSR1, lambda *_: None)+ print(f"[{PROTOCOL}] restart refused: {reason}", flush=True)+ while True:+ time.sleep(3600)+++# ---------------------------------------------------------------- the HTTP layer+class Service:+ """What a sim service hands to serve(): spec (dict), lock, state (the service's E dict: done, reason, exiting, error),+ submit(meta, actions) and observe(meta) -> (meta_out, rcb1 parts), kinematics(req) -> dict, status() -> dict,+ on_submit_error(exc) (a simulator error in /submit or /observe: it ends the episode, reason "error"), log(event dict),+ and for crash recovery the Episode with the simulator's state_sha() and proprio row()."""++ def __init__(self, *, spec: dict, lock, state: dict, submit: Callable, observe: Callable, kinematics: Callable,+ status: Callable, on_submit_error: Callable, log: Callable, max_resp: int = MAX_RESP,+ episode: Episode | None = None, state_sha: Callable | None = None, proprio: Callable | None = None):+ self.spec, self.lock, self.state, self.submit, self.observe = spec, lock, state, submit, observe+ self.kinematics, self.status, self.on_submit_error, self.log, self.max_resp = kinematics, status, on_submit_error, log, max_resp+ self.episode, self.state_sha, self.proprio = episode, state_sha, proprio+ self.kin_calls = 0+++def make_handler(svc: Service):+ class H(BaseHTTPRequestHandler):+ def _send(self, code: int, ctype: str, body: bytes) -> None:+ try:+ self.send_response(code); self.send_header("Content-Type", ctype); self.send_header("Content-Length", str(len(body)))+ self.end_headers(); self.wfile.write(body)+ except (BrokenPipeError, ConnectionResetError): # the client hung up (its call was abandoned)+ pass++ def _json(self, code: int, obj: dict) -> None:+ self._send(code, "application/json", json.dumps(obj).encode())++ def _rcb1(self, meta: dict, parts: list) -> None:+ self._send(200, "application/x-rcb1", encode_response(meta, parts, svc.max_resp))++ def log_message(self, *a):+ pass++ def _body(self):+ try:+ n = int(self.headers.get("Content-Length", 0))+ except ValueError:+ raise ValueError("bad Content-Length")+ if n > MAX_BODY:+ raise ValueError("request too large")+ raw = self.rfile.read(n) if n else b""+ if raw[:4] == rcb1.MAGIC:+ return rcb1.decode(raw)+ body = json.loads(raw or b"{}")+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object or an RCB1 frame")+ return body, {}++ def do_GET(self):+ if self.path == "/spec":+ return self._json(200, svc.spec)+ if self.path == "/status":+ st = svc.status()+ return self._json(200, {**st, "resumes": svc.episode.resumes} if svc.episode else st)+ return self._json(404, {"error": "no such endpoint"})++ def do_POST(self):+ if self.path not in ("/submit", "/observe", "/kinematics"):+ return self._json(404, {"error": "no such endpoint"})+ try:+ meta, parts = self._body()+ except Exception as exc: # noqa: BLE001+ return self._json(413 if "too large" in str(exc) else 400, {"error": str(exc)[:200]})+ E, ep = svc.state, svc.episode+ if self.path == "/kinematics": # stateless: never steps physics, never waits for the episode lock+ cid = ep.call_begin(self.path) if ep else 0+ try:+ req = parse_kinematics(meta, svc.spec["kinematics"])+ out = svc.kinematics(req); svc.kin_calls += 1+ except ValueError as exc:+ return self._json(400, {"error": str(exc)[:300]})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); return self._json(500, {"error": "kinematics error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ ep.call_end(cid, self.path)+ return self._json(200, out)+ with svc.lock:+ if E.get("exiting") or (self.path == "/submit" and E.get("done")):+ return self._json(409, {"error": "episode finished", "reason": E.get("reason")})+ cid = ep.call_begin(self.path, self.connection) if ep else 0+ rows0 = ep.rows if ep else 0+ out = blobs = err = None; stopped = None+ try:+ if self.path == "/submit":+ A = np.asarray(parts["actions"]["data"] if "actions" in parts else meta.get("actions", []), dtype=np.float64)+ out, blobs = svc.submit(meta, A)+ else:+ out, blobs = svc.observe(meta)+ except ValueError as exc:+ err = (400, {"error": str(exc)})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); E["error"] = repr(exc); svc.log({"ev": "error", "path": self.path, "error": repr(exc)})+ try:+ svc.on_submit_error(exc) # PROTOCOL §4.6: a simulator error ends the episode (reason "error")+ except Exception: # noqa: BLE001+ traceback.print_exc()+ err = (500, {"error": "simulator error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ stopped = ep.stop_reason+ if err is None or ep.rows != rows0:+ try:+ ep.checkpoint(E, svc.state_sha, svc.proprio)+ except Exception: # noqa: BLE001+ traceback.print_exc()+ ep.call_end(cid, self.path, **({"stopped": stopped} if stopped else {}))+ if err is not None:+ return self._json(*err)+ return self._rcb1({**out, "stopped": stopped}, blobs)+ return H+++def serve(svc: Service, port: int = 8000) -> None:+ """Check the spec, then serve forever (one request at a time, as every 2.x service)."""+ svc.spec.setdefault("on_service_error", ON_SERVICE_ERROR)+ if svc.episode is not None:+ svc.spec.setdefault("max_call_wall_s", svc.episode.max_call_wall_s)+ check_spec(svc.spec)+ HTTPServer(("0.0.0.0", port), make_handler(svc)).serve_forever()+++# ---------------------------------------------------------------- the collect hook's first half+def _alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ try: # a zombie (exited, not yet reaped) counts as gone+ with open(f"/proc/{pid}/stat") as f:+ return f.read().rsplit(")", 1)[-1].split()[0] != "Z"+ except OSError:+ return True+++def end_episode(data: str, timeout: float = 21600.0, wait_key: str | None = None, resend_s: float = 30.0) -> int:+ """Tell the service that the agent phase is over and wait until it has ended the episode. The service may be+ resuming after a crash (no PID file until it is ready again), so there is no fixed start-up wait, and a signal goes+ only to the process that wrote the newest line of startups.jsonl (its SIGUSR1 handler is installed by then).+ Returns 2: final.json already holds the verdict (the service gave up after crashes, or graded in-process; with+ `wait_key`, also waits for that final.json key, e.g. video_done): keep it, run no replays.+ Returns 0: the service dumped the episode (episode.json) and exited: the hook replays it next.+ Returns 1: timed out."""+ t0, sent = time.time(), 0.0+ f_pid, f_dump, f_starts = (os.path.join(data, n) for n in ("server.pid", "episode.json", "startups.jsonl"))+ while time.time() - t0 < timeout:+ fin = final_verdict(data)+ if fin is not None:+ if not wait_key or fin.get(wait_key) or fin.get("gave_up"):+ return 2+ time.sleep(2); continue+ try:+ with open(f_pid) as f:+ pid = int(f.read().strip())+ except (OSError, ValueError):+ pid = None+ try:+ with open(f_starts) as f:+ cur = json.loads([x for x in f if x.strip()][-1]).get("pid")+ except (OSError, ValueError, IndexError):+ cur = None # a service without Episode.startup(): signal what the PID file names+ if pid is not None and (cur is None or pid == cur):+ if not _alive(pid):+ if os.path.exists(f_dump):+ return 0+ elif time.time() - sent >= resend_s:+ try:+ os.kill(pid, signal.SIGUSR1); sent = time.time()+ except OSError:+ pass+ time.sleep(2)+ return 1+++if __name__ == "__main__":+ a = sys.argv[1:]+ if len(a) >= 2 and a[0] == "end":+ wk = a[a.index("--wait-key") + 1] if "--wait-key" in a else None+ to = float(a[a.index("--timeout") + 1]) if "--timeout" in a else 21600.0+ rc = end_episode(a[1], timeout=to, wait_key=wk)+ print({0: "[collect] episode dumped by the service", 1: "[collect] timed out waiting for the service",+ 2: "[collect] final.json already holds the verdict"}[rc], flush=True)+ sys.exit(rc)+ if len(a) == 2 and a[0] == "final-verdict":+ fin = final_verdict(a[1])+ print(json.dumps(fin) if fin else "no final verdict")+ sys.exit(0 if fin else 1)+ print("usage: rcb_limited.py end <data dir> [--wait-key KEY] [--timeout S] | final-verdict <data dir>")+ sys.exit(2)diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/rcb_quadruped.py b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/run.sh b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/run.shnew file mode 100755index 0000000000..49d4d045d4--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/run.sh@@ -0,0 +1,22 @@+#!/bin/sh+# eai-standard/2.2 sidecar entrypoint: PID 1 of the `sim` container, shared by every 2.2 service+# (scripts/eai_standard/run.sh, copied unchanged into each standard task's environment/sim/).+# - The service crashed (a non-zero exit: an exception, a signal, the startup watchdog): exit with its code, so compose+# restarts the container (`restart: on-failure:6`) and the service resumes the same episode from its journal+# (rcb_limited.Episode). The container keeps its /data (or /out) across the restart.+# - The service exited cleanly (0: it dumped its episode on the collect hook's SIGUSR1 and released the simulator): keep+# the container up for the collect hook's fresh-process replays. If the service were PID 1 itself, that exit would+# stop the container and kill the hook with it (Harbor reports exit 137).+# - Everything the service prints also goes to $RCB_DATA/server.log (an artifact: Harbor keeps no sidecar output, and a+# simulator that dies while it loads leaves no other trace).+DATA="${RCB_DATA:-/data}"+mkdir -p "$DATA"+rm -f "$DATA/.service_rc"+{ python -u "${RCB_SERVER:-/srv/server.py}" 2>&1; echo "$?" > "$DATA/.service_rc"; } | tee -a "$DATA/server.log"+rc="$(cat "$DATA/.service_rc" 2>/dev/null)"; rc="${rc:-1}"+if [ "$rc" != 0 ]; then+ echo "[sim] service exited ($rc): leaving, so compose restarts the container (the service resumes the episode if one began)" | tee -a "$DATA/server.log"+ exit "$rc"+fi+echo "[sim] service exited (0); holding the container open for the collect hook" | tee -a "$DATA/server.log"+while true; do sleep 3600; donediff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/server.py b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/server.pynew file mode 100644index 0000000000..b0c774b183--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/environment/sim/server.py@@ -0,0 +1,478 @@+"""eai-standard/2.2 sim service for MuJoCo Playground's quadruped tasks (docs/STANDARD_MODE_2_2.md): the adapter of the+shared layer rcb_limited.py; the simulator is rcb_quadruped.Session (plain MuJoCo on the CPU).+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to+/data/episode.jsonl.++The episode is the frozen instance's: one control step = 1/50 s. A joystick episode ends after the whole command schedule+(the horizon), when the robot meets Playground's termination rule (it falls over: a failure), when the agent submits+`done`, or when its time is over; success = the task's check on the steps executed. A getup episode ends the moment the+check holds (success), after the horizon, on `done` or on timeout.++Crash recovery (rcb_limited.Episode, resume class `exact`: MuJoCo on the CPU repeats bit for bit in a fresh process):+every executed row is journaled; after a crash the service rebuilds the episode and replays the journal. When the+episode ends the service writes /data/trajectory.npz + /data/episode.json; the collect hook (finalize.sh) makes it exit+and replays the trajectory in two fresh processes."""++import math+import os+import sys+import threading+import time+import traceback++import numpy as np++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import rcb_limited as L # noqa: E402++DATA = os.environ.get("RCB_DATA", "/data")+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.json"))+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "3600"))+MAX_CHUNK_S = float(os.environ.get("RCB_MAX_CHUNK_S", "10"))+MAX_WATCH_S = float(os.environ.get("RCB_MAX_WATCH_S", "30"))+CAM_W, CAM_H = 320, 240+LOCK = threading.Lock()+PID_FILE = os.path.join(DATA, "server.pid")+E = {"ready": False, "step": 0, "calls": 0, "done": False, "reason": None, "success": False, "t0": time.time(), "error": None}++os.environ["RCB_SESSION_LOG"] = ""+os.environ["RCB_AGENT_TRACE_DIR"] = ""+import rcb_quadruped as Q # noqa: E402 (first: it picks the rendering backend before mujoco loads)+import mujoco # noqa: E402++EP = L.Episode(DATA, dim=Q.N, resume="exact")+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()+S = Q.Session(INSTANCE)+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz+DT = S.control_dt # one control step of simulated time (Barkour: 10 ms, as Playground steps it)+CTRL_HZ = 1.0 / DT+SUBSTEPS = S.substeps+M = S.model+CAMS = list(S.cameras)+FEET = S.robot["feet"]+LIMITS = np.stack([S.lower, S.upper], axis=1)+GROUPS = [+ ("joint_pos", S.joint_names, "measured joint positions (rad), in the action's order"),+ ("joint_vel", [f"{j}_vel" for j in S.joint_names], "measured joint velocities (rad/s)"),+ ("joint_effort", [f"{j}_effort" for j in S.joint_names], "actuator torques of those joints (N m)"),+ ("gripper_opening", [], "none (no gripper)"),+ ("tcp_pose", [], "none (no gripper)"),+ ("imu_gyro", ["gyro_x", "gyro_y", "gyro_z"], "angular velocity of the trunk, IMU frame (rad/s)"),+ ("imu_accelerometer", ["acc_x", "acc_y", "acc_z"], "specific force at the IMU, IMU frame (m/s^2; +9.81 up at rest)"),+ ("imu_gravity", ["gravity_x", "gravity_y", "gravity_z"], "unit vector of gravity's direction in the IMU frame "+ "([0, 0, -1] when the trunk is level)"),+ ("imu_linvel", ["linvel_x", "linvel_y", "linvel_z"], "linear velocity of the trunk at the IMU, IMU frame (m/s; the "+ "IMU's velocimeter, what a state estimator gives)"),+ ("foot_contact", [f"{f}_contact" for f in FEET], "1 when the foot touches the ground, else 0"),+]+PROPRIO_LAYOUT = [n for _, names, _ in GROUPS for n in names]+PROPRIO_GROUPS, _i = {}, 0+for _g, _names, _meaning in GROUPS:+ PROPRIO_GROUPS[_g] = [_i, len(_names), _meaning]+ _i += len(_names)+++# ------------------------------------------------------------------------------------------------- cameras+def _intrinsic(cam: str) -> list:+ fovy = math.radians(float(M.cam_fovy[M.camera(cam).id]))+ f = 0.5 * CAM_H / math.tan(fovy / 2)+ return [[f, 0.0, CAM_W / 2], [0.0, f, CAM_H / 2], [0.0, 0.0, 1.0]]+++def camera_info(cam: str) -> dict:+ """World -> camera (OpenCV axes) and camera -> world (OpenGL axes) at the current state."""+ i = M.camera(cam).id+ R_gl = S.data.cam_xmat[i].reshape(3, 3) # camera axes (OpenGL: x right, y up, z back) in the world+ p = S.data.cam_xpos[i].copy()+ R_cv = R_gl @ np.diag([1.0, -1.0, -1.0])+ ext = np.zeros((3, 4))+ ext[:, :3] = R_cv.T+ ext[:, 3] = -R_cv.T @ p+ c2w = np.eye(4)+ c2w[:3, :3] = R_gl+ c2w[:3, 3] = p+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": ext.tolist(), "cam2world_gl": c2w.tolist(),+ "image_size": [CAM_W, CAM_H]}+++# ------------------------------------------------------------------------------------------------- kinematics+KD = mujoco.MjData(M) # kinematics only: the trunk at the origin, level; never stepped+_FOOT = {f: M.site(f).id for f in FEET}+_LEG_DOF = {f: [6 + 3 * k + j for j in range(3)] for k, f in enumerate(FEET)} # actuator order = leg order = FEET+++def _fk_kd(q) -> None:+ KD.qpos[:] = 0.0+ KD.qpos[3] = 1.0+ KD.qpos[7:] = q+ mujoco.mj_kinematics(M, KD)+++def _foot_pose(f: str) -> list:+ quat = np.zeros(4)+ mujoco.mju_mat2Quat(quat, KD.site_xmat[_FOOT[f]])+ return [*KD.site_xpos[_FOOT[f]].tolist(), *quat.tolist()]+++def do_kinematics(req: dict) -> dict:+ """Feet in the trunk frame (the trunk body's origin and axes; x forward, y left, z up). IK solves positions only, one+ leg (3 joints) per foot target, damped least squares within the joint ranges; a foot's orientation is ignored."""+ if req["op"] == "fk":+ _fk_kd(np.asarray(req["q"]))+ return L.fk_response({f: _foot_pose(f) for f in req["links"]}, "trunk")+ q = np.array(req["seed"] if req["seed"] is not None else S.data.qpos[7:], dtype=np.float64)+ errors = {}+ jac = np.zeros((3, M.nv))+ for f, pose in req["targets"].items():+ tgt = np.asarray(pose[:3])+ idx = _LEG_DOF[f]+ for _ in range(req["max_iters"]):+ _fk_kd(q)+ err = tgt - KD.site_xpos[_FOOT[f]]+ if np.linalg.norm(err) < req["tol_pos_m"]:+ break+ mujoco.mj_jacSite(M, KD, jac, None, _FOOT[f])+ J = jac[:, idx]+ dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(3), err)+ q[[i - 6 for i in idx]] = np.clip(q[[i - 6 for i in idx]] + dq, S.lower[[i - 6 for i in idx]],+ S.upper[[i - 6 for i in idx]])+ _fk_kd(q)+ errors[f] = (float(np.linalg.norm(tgt - KD.site_xpos[_FOOT[f]])), 0.0)+ ok = all(e[0] <= req["tol_pos_m"] for e in errors.values())+ return L.ik_response(q, ok, errors, "trunk", note="feet: position only (a foot is a sphere; its orientation is ignored)")+++# ------------------------------------------------------------------------------------------------- spec+def schedule_text() -> list:+ if S.commands is None:+ return []+ return [{"from_s": round(int(c["start_step"]) * DT, 2), "vx_mps": round(c["vx"], 4), "vy_mps": round(c["vy"], 4),+ "wz_radps": round(c["wz"], 4)} for c in S.inst["commands"]]+++TASK_EPISODE = {+ "joystick": f"one episode, no reset: it ends after {S.horizon} control steps (the {S.horizon * DT:g} s command "+ f"schedule), when the robot meets its termination rule ({S.spec.get('term_text')}: a failure), when you "+ "submit `done`, or when your time is over",+ "getup": f"one episode, no reset: it ends the moment the robot has stood upright for {Q.HOLD_STEPS} control steps in a "+ f"row (success), after {S.horizon} control steps, when you submit `done`, or when your time is over",+ "stand_on_two": f"one episode, no reset: it ends the moment the pose has been held for {Q.POSE_HOLD_STEPS} control steps "+ "in a row (success), when the robot meets the termination rule (a failure: its trunk's up axis below "+ f"-0.25, or {'a leg' if S.spec.get('hind_leg_contact') else 'a front leg'}'s thigh, calf or hip on the "+ f"floor), after {S.horizon} control steps, when you "+ "submit `done`, or when your time is over",+}[S.kind]+_ctl = {"type": "joint position actuators (PD)", "kp_nm_per_rad": float(M.actuator_gainprm[0, 0]),+ "kd_nms_per_rad": float(M.dof_damping[6] - M.actuator_biasprm[0, 2])}+SPEC = {+ "protocol": L.PROTOCOL,+ "protocol_compat": list(L.COMPAT),+ "simulator": "MuJoCo 3.3.7 (MuJoCo Playground's scene, plain MuJoCo on the CPU)",+ "robot": S.robot["name"],+ "task_text": S.inst["text"],+ "control_hz": CTRL_HZ,+ "physics_substeps": SUBSTEPS,+ "max_chunk_s": MAX_CHUNK_S,+ "max_watch_s": MAX_WATCH_S,+ "cameras": {c: {"rgb": True, "depth": True, "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),+ **({"mounted": "follows the robot", "mount": {"type": "link", "link": S.robot["root"], "note":+ "follows the robot's centre of mass at a fixed offset; it does not turn with the robot"}}+ if int(M.cam_mode[M.camera(c).id]) != 0 else+ {"mounted": "on the robot's head", "mount": {"type": "link", "link": M.body(M.cam_bodyid[M.camera(c).id]).name+ or S.robot["root"], "note": "fixed to the robot: moves and turns with it"}})}+ for c in CAMS},+ "default_cameras": ["track"],+ "action_types": {+ "joint_position": {+ "dim": Q.N,+ "layout": S.joint_names,+ "limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "units": "rad",+ "semantics": "absolute targets of the 12 joint position actuators, one per control step (1/50 s); rows `dt` "+ "apart (a multiple of the control period, at most 0.5 s), `hold` or `linear` between rows; values "+ "outside the limits are clipped and reported",+ },+ "done": {"dim": 0, "layout": [], "semantics": 'ends the episode now, in the current state (no physics); r.submit("done", [])'},+ "not_yet": ["joint_velocity", "joint_torque", "joint_delta"],+ },+ "proprio_layout": PROPRIO_LAYOUT,+ "proprio_groups": PROPRIO_GROUPS,+ "static": {},+ "world": {"frame": "z up; the robot starts where the episode puts it (no world coordinates are given)", "up": "+z",+ "units": {"length": "m", "angle": "rad", "time": "s"}, "quaternion_order": "wxyz",+ "camera_axes": "intrinsic_cv / extrinsic_cv: OpenCV camera axes (x right, y down, z forward); cam2world_gl: OpenGL axes"},+ "budget": {"reset": 0, "steps": None, "wall_clock_s": WALL_CLOCK_S},+ "max_control_steps": S.horizon,+ "episode": TASK_EPISODE,+ "command_schedule": schedule_text(),+ **({"gait": {k: S.gait[k] for k in ("name", "frequency_hz", "foot_height_m", "phase0", "phase_dt")} | {+ "feet": FEET, "rule": "foot i's target height at control step t is get_rz(wrap(phase0[i] + t * phase_dt)) with "+ "Playground's gait.get_rz (a cubic Bezier from 0 up to foot_height_m over the first half of the phase, then "+ "down); phases in rad, wrapped to [-pi, pi)"}} if S.gait else {}),+ "robot_spec": {"name": S.robot["name"], "joints": S.joint_names, "joint_limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "joint_order": S.robot["joint_text"], "home_pose": dict(zip(S.joint_names, S.home.tolist())),+ "feet": FEET, "controller": _ctl},+ "kinematics": {"endpoint": "/kinematics", "joint_names": S.joint_names, "frame": "trunk", "quaternion_order": "wxyz",+ "links": FEET, "tcp_frames": [], "ee_frames": FEET, "ik_targets": FEET,+ "ik": {"tol_pos_m": 0.002, "tol_rot_rad": 3.2, "max_iters": 100},+ "note": "poses of the feet in the trunk frame (x forward, y left, z up, metres) for joint positions q; "+ "ik: one leg per foot, positions only"},+ "depth": {"modes": list(L.DEPTH_MODES), "default": "none", "kind": "z-depth", "unit": "m", "invalid": 0,+ "max_m": L.DEPTH_MAX_M, "frames_encoding": "uint16 mm, zlib", "noise": L.DEPTH_NOISE},+}+L.check_spec(SPEC) # a spec that misses a 2.2 field or names a forbidden one never starts the episode+EP.scene_built()++_RENDER = {}+++def _renderer():+ if "r" not in _RENDER:+ _RENDER["r"] = mujoco.Renderer(M, CAM_H, CAM_W)+ return _RENDER["r"]+++def ctrl_steps() -> int:+ return S.steps+++def proprio_row() -> np.ndarray:+ d = S.data+ return np.concatenate([d.qpos[7:], d.qvel[6:], d.actuator_force, S.sensor("gyro"), S.sensor("accelerometer"), S.gravity(),+ S.sensor("local_linvel"), S.foot_contacts()]).astype(np.float32)+++def grab(cams, want_depth: bool):+ r = _renderer()+ rgb, dep = {}, {}+ for c in cams:+ r.update_scene(S.data, camera=c)+ rgb[c] = r.render().copy()+ if want_depth:+ r.enable_depth_rendering()+ r.update_scene(S.data, camera=c)+ dep[c] = r.render().astype(np.float32).copy()+ r.disable_depth_rendering()+ return rgb, dep+++def extrinsics(cams) -> dict:+ return {c: np.asarray(camera_info(c)["extrinsic_cv"], dtype=np.float64) for c in cams}+++def write_final() -> None:+ if L.final_verdict(DATA): # finalize.sh's verdict, or a give-up after crashes: never overwritten+ return+ L._write_json(os.path.join(DATA, "final.json"), {**summary(), "finalized": False, "live_sha": E.get("live_sha")})+++def summary() -> dict:+ n = int(E.get("episode_control_steps") or ctrl_steps())+ chk = E.get("check") or {}+ return {"success": bool(E["success"]), "steps": E["step"], "calls": E["calls"], "control_steps": n,+ "physics_steps": n * SUBSTEPS, "elapsed_s": round((E.get("t_end") or time.time()) - E["t0"], 1),+ "reason": E["reason"], "done": E["done"], "env": S.env, "protocol": L.PROTOCOL, "n_actions": len(ROWS),+ "fell_at": chk.get("fell_at"), "worst_lin_err": chk.get("worst_lin_err"), "worst_yaw_err": chk.get("worst_yaw_err"),+ "tilt_deg": chk.get("tilt_deg"), "imu_height": chk.get("imu_height"), "pose_angle_deg": chk.get("pose_angle_deg"),+ **EP.final_fields()}+++def finish(reason: str) -> None:+ """The episode is over: the task's check on the steps executed, then the record for the collect hook."""+ if E["done"]:+ return+ E["done"] = True+ E["reason"] = reason+ E["t_end"] = time.time()+ E["episode_control_steps"] = ctrl_steps()+ try:+ chk = S.check()+ E["check"] = {k: v for k, v in chk.items() if k != "segments"}+ E["success"] = bool(chk["success"])+ except Exception: # noqa: BLE001+ traceback.print_exc()+ EP.log({"ev": "end", "reason": reason, "step": E["step"], "control_steps": ctrl_steps(), "success": bool(E["success"])})+ dump()+++def dump() -> None:+ if E.get("dumped"):+ return+ E["dumped"] = True+ E["live_sha"] = S.state_sha()+ np.savez(os.path.join(DATA, "trajectory.npz"), actions=np.asarray(ROWS, dtype=np.float64).reshape(-1, Q.N),+ env=S.env, action_layout=",".join(S.joint_names))+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})+ write_final()+++def after_step() -> None:+ if S.kind in ("joystick", "stand_on_two") and S.fell_at is not None:+ finish("fell")+ elif S.kind in ("getup", "stand_on_two") and S.check()["success"]:+ finish("success")+ elif S.done:+ finish("horizon")+++def ctrl_step(a, rec) -> bool:+ """One executed control step, journaled. True when the call must stop here."""+ S.step(a)+ ROWS.append(np.asarray(a, dtype=np.float64))+ stop = EP.journal(a)+ rec.tick()+ after_step()+ return E["done"] or stop+++def recorder(cams, fps: int, meta: dict) -> L.Recorder:+ return L.Recorder(cams, max(1, int(round(CTRL_HZ / max(1, fps)))), grab, proprio_row, extrinsics, ctrl_steps,+ depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+++def video_fps(meta: dict) -> int:+ fps = meta.get("video_fps")+ if fps is None:+ return 10+ if isinstance(fps, bool) or not isinstance(fps, (int, float)) or not (1 <= fps <= 50):+ raise ValueError("video_fps must be in [1, 50]")+ return int(fps)+++def cameras_of(meta: dict) -> list:+ cams = meta.get("cameras") or ["track"]+ bad = [c for c in cams if c not in CAMS]+ if bad:+ raise ValueError(f"unknown cameras {bad}; cameras: {CAMS}")+ return list(cams)+++def meta_common(cams) -> dict:+ n = ctrl_steps()+ out = {"step": E["step"], "calls": E["calls"], "control_steps": n, "physics_steps": n * SUBSTEPS,+ "sim_time_s": round(n * DT, 3), "time_s": round(time.time() - E["t0"], 2),+ "time_left_s": max(0.0, round(WALL_CLOCK_S - (time.time() - E["t0"]), 1)),+ "proprio": {"layout": PROPRIO_LAYOUT, "now": proprio_row().tolist()}, "done": E["done"], "reason": E["reason"],+ "cameras": {c: camera_info(c) for c in cams}}+ if S.kind == "joystick":+ out["command_now"] = dict(zip(("vx_mps", "vy_mps", "wz_radps"), S.command_now().round(4).tolist()))+ return out+++def do_submit(meta: dict, A: np.ndarray):+ typ = meta.get("type")+ if typ == "done":+ rec = recorder(cameras_of(meta), 5, meta)+ rec.tick(force=True, last=True) # every response carries the last frames+ E["calls"] += 1+ finish("done")+ return {**meta_common(cameras_of(meta)), "chunk_id": E["calls"], "type": typ, "executed_rows": 0, "ok": True}, rec.parts("none", 5)+ if typ != "joint_position":+ raise ValueError(f"type must be joint_position or done (not yet: {SPEC['action_types']['not_yet']})")+ dt = float(meta.get("dt", DT))+ interp = meta.get("interpolate", "linear")+ video = meta.get("video", "mp4")+ cams, fps = cameras_of(meta), video_fps(meta)+ k = dt / DT+ if A.ndim != 2 or A.shape[1] != Q.N:+ raise ValueError(f"joint_position actions must be (T, {Q.N}), got {list(A.shape)}")+ if not np.all(np.isfinite(A)):+ raise ValueError("actions contain NaN/inf")+ if not (math.isfinite(dt) and dt <= 0.5 + 1e-9 and round(k) >= 1 and abs(k - round(k)) < 1e-6):+ raise ValueError(f"dt must be a whole multiple of the {DT:g} s control period and at most 0.5 s; got {dt}")+ if A.shape[0] * dt > MAX_CHUNK_S + 1e-9:+ raise ValueError(f"chunk longer than max_chunk_s={MAX_CHUNK_S}: {A.shape[0]} rows x {dt} s")+ if interp not in ("hold", "linear"):+ raise ValueError("interpolate must be hold|linear")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, clipped = recorder(cams, fps, meta), []+ E["calls"] += 1+ step0, before = E["step"], ctrl_steps()+ rec.tick(force=True)+ prev = S.targets.copy()+ for ri, row in enumerate(A):+ E["step"] += 1+ target = np.clip(row, LIMITS[:, 0], LIMITS[:, 1])+ for j in np.flatnonzero(target != row)[:20]:+ clipped.append({"row": ri, "index": int(j), "reason": f"{S.joint_names[j]} limit [{LIMITS[j, 0]:g}, {LIMITS[j, 1]:g}]"})+ n = int(round(k))+ stop = False+ for s in range(1, n + 1):+ a = target if interp == "hold" else prev + (target - prev) * (s / n)+ if ctrl_step(a, rec):+ stop = True+ break+ prev = target+ if stop:+ break+ rec.tick(force=True, last=True)+ out = {**meta_common(cams), "chunk_id": E["calls"], "type": typ, "executed_rows": E["step"] - step0,+ "control_steps_chunk": ctrl_steps() - before, "physics_steps_chunk": (ctrl_steps() - before) * SUBSTEPS,+ "clipped": clipped[:200], "n_clipped": len(clipped), "plan": [], "ok": True}+ EP.log({"ev": "submit", "call": E["calls"], "rows": E["step"] - step0, "dt": dt, "interpolate": interp, "cameras": cams,+ "control_steps": ctrl_steps() - before, "n_clipped": len(clipped), "note": (meta.get("note") or "")[:500],+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video, fps)+++def do_observe(meta: dict):+ cams, fps = cameras_of(meta), video_fps(meta)+ seconds = float(meta.get("seconds", 0))+ video = meta.get("video", "frames")+ if not math.isfinite(seconds) or seconds < 0 or seconds > MAX_WATCH_S:+ raise ValueError(f"seconds must be in [0, {MAX_WATCH_S}]")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, before = recorder(cams, fps, meta), ctrl_steps()+ if seconds > 0 and not E["done"]:+ rec.tick(force=True)+ hold = S.targets.copy()+ for _ in range(int(round(seconds / DT))):+ if ctrl_step(hold, rec):+ break+ rec.tick(force=True, last=True)+ E["calls"] += 1+ out = {**meta_common(cams), "obs_id": E["calls"], "seconds": seconds, "control_steps_watch": ctrl_steps() - before,+ "physics_steps_watch": (ctrl_steps() - before) * SUBSTEPS, "ok": True}+ EP.log({"ev": "observe", "call": E["calls"], "seconds": seconds, "cameras": cams, "control_steps": ctrl_steps() - before,+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video if seconds > 0 else ("frames" if video == "mp4" else video), fps)+++def status() -> dict:+ return {"step": E["step"], "calls": E["calls"], "control_steps": ctrl_steps(), "done": E["done"], "reason": E["reason"],+ "elapsed_s": round(time.time() - E["t0"], 1)}+++def end_from_signal() -> None:+ """The collect hook's SIGUSR1: end the episode (the agent's time is over), dump it, exit so the replays can start."""+ with LOCK:+ E["exiting"] = True+ if not E["done"]:+ finish("timeout")+ EP.log({"ev": "exit", "reason": "collect hook: episode dumped"})+ if not os.path.exists(PID_FILE):+ open(PID_FILE, "w").write(str(os.getpid()))+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(0)+++def replay_row(row) -> None:+ """A journaled row during a resume."""+ S.step(row)+ ROWS.append(np.asarray(row, dtype=np.float64))+++EP.begin(state=E, step=replay_row, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, on_end=end_from_signal,+ start_event={"env": S.env, "seed": S.inst.get("seed"), "cameras": CAMS})+if E["done"]:+ dump() # resumed after the episode had ended: the record is rewritten from the replay+E["ready"] = True+write_final()+open(PID_FILE, "w").write(str(os.getpid()))+print(f"{L.PROTOCOL} MuJoCo Playground quadruped sim ready ({S.env}; startup {EP.n_startups}, resumes {EP.resumes})", flush=True)+L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics, status=status,+ on_submit_error=lambda exc: finish("error"), log=EP.log, episode=EP, state_sha=S.state_sha,+ proprio=proprio_row), port=int(os.environ.get("RCB_PORT", "8000")))diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/instruction.md b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/instruction.mdnew file mode 100644index 0000000000..049e37cbe4--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/instruction.md@@ -0,0 +1,57 @@+# MuJoCo Playground · SpotFlatTerrainJoystick — STANDARD MODE (robot as a service, eai-standard/2.2)++**Task:** Make Boston Dynamics Spot follow the joystick command schedule on flat ground for the whole 20 s episode without falling over.++You control the Boston Dynamics Spot quadruped — **as if it were real hardware** — in one episode of MuJoCo Playground's+`SpotFlatTerrainJoystick` environment (plain MuJoCo 3.3.7 with Playground's scene, commit 4057c14). The simulator runs in a service you+cannot open. You get one client and one episode.++## The episode+The robot starts standing still at Playground's `home` pose (this environment's reset does not move it). The ground is flat.+For 20 s (1000 control steps) it is given this command schedule, drawn by Playground's command process (a new draw every 201 control steps, zero with probability 0.1). A command is a velocity in the robot's own frame: vx forward, vy to the left (the trunk's planar velocity), and the yaw rate:++| from (s) | vx (m/s) | vy (m/s) | yaw rate (rad/s) |+|---:|---:|---:|---:|+| 0.00 | +0.713 | +0.045 | +0.609 |+| 4.02 | -0.185 | -0.401 | -0.477 |+| 8.04 | +0.605 | +0.115 | +0.049 |+| 12.06 | +0.000 | +0.000 | +0.000 |+| 16.08 | -0.281 | -0.742 | -0.667 |++The same schedule is `spec["command_schedule"]`; every response's `meta["command_now"]` is the current command.++## Rules (real-robot rules)+- **No reset.** One episode. You see four cameras that follow the robot (RGB, depth if you ask) and the robot's own+ sensors: joint positions, velocities and torques, the IMU (gyro, accelerometer, gravity's direction, the trunk's+ velocity), foot contacts. No world positions, no success check.+- **The episode ends** after 1000 control steps, the whole schedule (`spec["max_control_steps"]`, counted by `meta["control_steps"]`), when the robot meets its termination rule (the trunk tilted by more than about 32 deg (the z component of the IMU frame's z axis below 0.85): a failure), when you submit `done`, or when your time is up (before the end of the schedule, both are failures).+- **Success** is judged on the whole schedule: no termination, and in every command segment, after its first 25 control steps, a mean |v_xy - cmd_xy| of at most 0.2 m/s (`imu_linvel`) and a mean |w_z - cmd_wz| of at most 0.3 rad/s (`imu_gyro`).+- Your wall-clock budget is 3600 s from your start. Simulated time only advances with your commands (and+ `get_obs(seconds=...)`, which holds the current targets).+- Nothing to hand in: the service records the episode and grades it. Leave your script at `/app/output/gen.py`.+- **If the service crashes**, a call fails with a connection error: it restarts and resumes the SAME episode (never a+ reset) in the state after the last call it completed. `r.wait_ready()` waits for it; then check `r.status()`.+- Nothing is put into your context automatically: images come back as arrays in Python objects.++## Client (`/opt/tools/rcb_client.py`)+```python+from rcb_client import Robot+r = Robot() # connects (waits while the service starts)+spec = r.spec() # action types, limits, cameras, robot_spec (home pose, gains), kinematics, command_schedule+obs = r.get_obs() # obs.last[cam] -> uint8 (240, 320, 3); obs.meta["proprio"] {"layout", "now"}+res = r.submit("joint_position", A, dt=0.02) # A: (T, 12) rows dt apart; res.proprio (one row per frame), res.meta+obs = r.get_obs(seconds=1.0, video="mp4") # hold the current targets and watch for 1 s (max 30)+r.fk(q); r.ik({"FL": [x, y, z, 1, 0, 0, 0]}, seed=q) # feet in the trunk frame <-> joints (no physics)+r.submit("done", []) # end the episode now+r.status() # calls, control steps, done, reason, elapsed time+```+Cameras: `track`, `side`, `back`, `top` (they follow the robot); `spec["cameras"]` gives each one's mounting and intrinsics, and every response carries its pose. Proprioception (`spec["proprio_groups"]`): `joint_pos`, `joint_vel`, `joint_effort` (12 each, action+order), `imu_gyro`, `imu_accelerometer`, `imu_gravity`, `imu_linvel` (3 each, IMU frame: x forward, y left, z up),+`foot_contact` (FL, FR, HL, HR).++### `joint_position` (12)+FL, FR, HL, HR legs, each hx (abduction), hy (hip pitch), kn (knee): absolute targets of the joint position actuators (rad; kp = 300 N m/rad, joint damping 1 N m s/rad, plus the actuators' own damping of 20 N m s/rad).+Rows are `dt` apart (a whole multiple of the 0.02 s control period, at most 0.5 s), `interpolate="linear"` (default) or+`"hold"` between rows; a chunk covers at most 10 s; values outside the limits+(`spec["action_types"]["joint_position"]["limits"]`) are clipped and listed in `res.meta["clipped"]`. Feedback control+means short chunks: each response tells you where the robot is now.diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/solution/oracle.npy b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/solution/oracle.npynew file mode 100644index 0000000000..ce4a22921dBinary files /dev/null and b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/solution/oracle_replay.py b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/solution/oracle_replay.pynew file mode 100644index 0000000000..b6a9824592--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/solution/oracle_replay.py@@ -0,0 +1,42 @@+"""Oracle (standard mode): streams the reference rows (one per 1/50 s control step, `hold`) as `joint_position` chunks+through the client, the same interface an agent has. Uses no privileged information at run time; the service's recorded+trajectory is then exactly the privileged reference. If the service crashes it resumes the same episode+(spec["on_service_error"]): the oracle waits until it answers again and goes on from the control step it reports."""+import os+import sys+import time++import numpy as np+import requests++sys.path.insert(0, "/opt/tools")+from rcb_client import EpisodeOver, Robot # noqa: E402++Q = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy")).astype(np.float64)+r = Robot()+spec = r.spec()+dt = 1.0 / float(spec["control_hz"])+per_chunk = max(1, int(spec.get("max_chunk_s", 10) / dt + 1e-9))+print("spec:", spec["protocol"], "rows:", len(Q), flush=True)+t0, i = time.time(), 0+while i < len(Q):+ chunk = Q[i:i + per_chunk]+ try:+ res = r.submit("joint_position", chunk, dt=dt, interpolate="hold", cameras=["track"], video="none", note=f"oracle rows {i}+")+ except EpisodeOver as e:+ print("episode over:", e)+ break+ except requests.exceptions.RequestException as e: # the service crashed: it restarts and resumes the same episode+ print("service unreachable:", repr(e)[:200], "- waiting for it to resume", flush=True)+ st = r.wait_ready()+ n = int(st["control_steps"])+ if not i <= n <= i + len(chunk):+ raise SystemExit(f"resumed at control step {n}: outside the chunk in flight (rows {i}..{i + len(chunk)})")+ i = n+ continue+ n = int(res.meta["control_steps"])+ print(f"rows {i}..{n}: clipped={res.meta['n_clipped']} done={res.meta['done']} reason={res.meta['reason']}", flush=True)+ if res.meta["done"] or n <= i:+ break+ i = n+print("status:", r.status(), "wall %.0fs" % (time.time() - t0))diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/solution/solve.sh b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/solution/solve.shnew file mode 100755index 0000000000..ecb1f6c954--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/solution/solve.sh@@ -0,0 +1,8 @@+#!/bin/bash+# Oracle (standard mode): streams the reference trajectory's joint targets (solution/oracle.npy, one row per control step)+# as `joint_position` chunks through the client. Uses no privileged information at run time (only the pre-recorded+# targets); the service's recorded trajectory is then exactly the privileged reference.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/task.toml b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/task.tomlnew file mode 100644index 0000000000..dea7de75ff--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/task.toml@@ -0,0 +1,54 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = [+ { source = "/data/final.json", service = "sim" },+ { source = "/data/episode.jsonl", service = "sim" },+ { source = "/data/trajectory.npz", service = "sim" },+ { source = "/data/replay.mp4", service = "sim" },+ { source = "/data/server.log", service = "sim" }, # the service's own output (Harbor keeps none)+ { source = "/data/journal.f64", service = "sim" }, # crash recovery: every executed control step (float64 rows)+ { source = "/data/startups.jsonl", service = "sim" }, # crash recovery: one line per service start+ { source = "/data/replay1.log", service = "sim" }, # the collect hook's two fresh-process replays+ { source = "/data/replay2.log", service = "sim" },+ { source = "/data/replay3.log", service = "sim" }, # and its third, which renders replay.mp4+ "/app/output/",+]++[task]+name = "robot-coding-bench/mujoco_playground_spot_flat_terrain_joystick-standard"+description = "STANDARD MODE (robot as a service, eai-standard/2.2): MuJoCo Playground SpotFlatTerrainJoystick (Boston Dynamics Spot) on the same frozen instance as mujoco_playground_spot_flat_terrain_joystick-privileged: Make Boston Dynamics Spot follow the joystick command schedule on flat ground for the whole 20 s episode without falling over. The agent only gets a client: four cameras that follow the robot (RGB, optional depth), the robot's joints and IMU, joint position chunks at 50 Hz, the feet's kinematics; one episode, no reset, no world state; the sim service records the episode, replays it in fresh processes and grades it."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "boston-dynamics-spot", "quadruped", "locomotion", "joystick", "code-as-policy", "trajectory", "standard-mode"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "boston-dynamics-spot"+family = "mujoco_playground/SpotFlatTerrainJoystick"+mode = "standard"+protocol = "eai-standard/2.2"+oracle = "full"+instance_seed = 0+expert_time_estimate_hours = 4.0++[verifier]+timeout_sec = 600.0+environment_mode = "separate"+network_mode = "no-network"++[[verifier.collect]]+service = "sim"+command = "sh /srv/finalize.sh" # end + dump + exit the service, replay twice in fresh processes, write final.json, video+timeout_sec = 1200++[agent]+timeout_sec = 3600.0+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/tests/Dockerfile b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/tests/Dockerfilenew file mode 100644index 0000000000..26bc699ebe--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/tests/Dockerfile@@ -0,0 +1,5 @@+# Separate verifier sandbox: grades the sim service's own artifacts; needs nothing but python (the shared client base).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY test.sh /tests/test.sh+COPY grade.py /tests/grade.py+RUN chmod +x /tests/test.shdiff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/tests/grade.py b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/tests/grade.pynew file mode 100644index 0000000000..5b990bf458--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/tests/grade.py@@ -0,0 +1,64 @@+"""Standard-mode verifier (MuJoCo Playground quadrupeds): reads what the sim service (which the agent could not touch) wrote:+/data/final.json (live success, two fresh-process replays of the recorded trajectory, determinism, crash-recovery+fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, the+replays having started in the instance's t = 0 state. Numeric-only reward.json."""++import json, os, shutil++LOG = "/logs/verifier"+os.makedirs(LOG, exist_ok=True)+++def write(ok, out):+ open(f"{LOG}/reward.txt", "w").write("1\n" if ok else "0\n")+ json.dump(out, open(f"{LOG}/reward.json", "w"))+ print(out)+++p = "/data/final.json"+if not os.path.exists(p):+ write(False, {"success": 0, "missing_log": 1, "grader_error": 0, "infra_error": 0})+ raise SystemExit+d = json.load(open(p))+for f in ("replay.mp4", "trajectory.npz", "episode.jsonl"):+ if os.path.exists(f"/data/{f}"):+ shutil.copy(f"/data/{f}", f"{LOG}/{f}")+ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic"))+ok = ok and not d.get("instance_mismatch")+num = lambda k: float(d.get(k) or 0) # noqa: E731+write(+ ok,+ {+ "success": int(ok),+ "live_success": int(bool(d.get("success"))),+ "replay_success": int(bool(d.get("replay_success"))),+ "deterministic": int(bool(d.get("deterministic"))),+ "live_matches_replay": int(bool(d.get("live_matches_replay"))),+ "finalized": int(bool(d.get("finalized"))),+ "n_actions": int(d.get("n_actions") or 0),+ "sim_steps": int(d.get("control_steps") or 0),+ "physics_steps": int(d.get("physics_steps") or 0),+ "steps": int(d.get("steps") or 0),+ "elapsed_s": float(d.get("elapsed_s") or 0),+ "video_rendered": int(bool(d.get("video"))),+ "fell": int(d.get("fell_at") is not None),+ "worst_lin_err": float(d["worst_lin_err"]) if d.get("worst_lin_err") is not None else -1.0,+ "worst_yaw_err": float(d["worst_yaw_err"]) if d.get("worst_yaw_err") is not None else -1.0,+ "end_tilt_deg": float(d["tilt_deg"]) if d.get("tilt_deg") is not None else -1.0,+ "end_imu_height": float(d["imu_height"]) if d.get("imu_height") is not None else -1.0,+ "end_pose_angle_deg": float(d["pose_angle_deg"]) if d.get("pose_angle_deg") is not None else -1.0,+ # a replay process gave no result, or the image no longer builds the frozen start: not the agent's 0+ "grader_error": int(bool(d.get("replay_failed") or d.get("instance_mismatch"))),+ "instance_mismatch": int(bool(d.get("instance_mismatch"))),+ # an infrastructure failure, not the agent's (PROTOCOL §2.6): a give-up after crashes between calls or a failed+ # resume (docs/STANDARD_MODE_2_2.md §13), the service not ending its episode for the collect hook, a replay+ # process that gave no result, replays that did not start in the instance's t = 0 state+ "infra_error": int(bool(d.get("infra_error"))),+ "gave_up": int(bool(d.get("gave_up"))),+ "sim_error": int(d.get("reason") == "error"),+ "sim_startups": int(d.get("sim_startups") or 0),+ "resumes": int(d.get("resumes") or 0),+ "resume_state_mismatch": int(d.get("resume_state_mismatch") or 0),+ "resume_max_joint_dev": num("resume_max_joint_dev"),+ },+)diff --git a/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/tests/test.sh b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/tests/test.shnew file mode 100755index 0000000000..bc608aa8b9--- /dev/null+++ b/tasks/mujoco_playground_spot_flat_terrain_joystick-standard/tests/test.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Verifier (separate sandbox): the sim sidecar's artifacts were uploaded to /data by Harbor.+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)+mkdir -p /logs/verifier+python /tests/grade.py 2> /logs/verifier/grade.logdiff --git a/tasks/mujoco_playground_spot_getup-privileged/README.md b/tasks/mujoco_playground_spot_getup-privileged/README.mdnew file mode 100644index 0000000000..4f288efbe1--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-privileged/README.md@@ -0,0 +1,42 @@+# mujoco_playground_spot_getup-privileged++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | privileged |+| Twin | `mujoco_playground_spot_getup-standard` |+| Simulator / robot | `mujoco` / `boston-dynamics-spot` |+| Family / instance | `mujoco_playground/SpotGetup` / seed 1 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `SpotGetup` (Boston Dynamics Spot), rebuilt in plain MuJoCo from Playground's scene files: Boston Dynamics Spot has fallen over. Make it get up and stand upright at its standing height.+It starts lying with its trunk tilted 128.4 deg (Playground's random drop, then a 0.5 s settle) and has 6 s to stand upright at its standing height. The deliverable is one replayable trajectory of joint position targets+(`/app/output/trajectory.npz`, `(T, 12)`, 1 <= T <= 300).++## Difficulty+Recovery from a fall: the robot lies on its side or back and has to turn itself over with its legs and then stand up within 6 s, with the trunk, thighs and calves all in contact with the floor (full collisions). The motion is whole-body and contact-rich, and a turn that fails leaves it on its back. Spot's trunk alone weighs 33 kg and its legs are long: a turn has to be timed against gravity.++## Reference solution+A policy trained here on Playground's SpotGetup reward (PPO on the CPU, `scripts/mujoco-playground/train/`, not in the image), run closed loop until the check completes (`scripts/mujoco-playground/oracle.py`): upright after 63 control steps, IMU at 0.478 m. Replayed by `solution/solve.sh` (`solution/oracle.npy`, 63 rows); the rows are float32-exact, so the+standard twin's client executes the same targets. Re-verified by `scripts/mujoco-playground/select_instances.py`: two+fresh-process replays succeed and end in the same state.++## Verification+`tests/grade.py` in a separate sandbox without network: two replays, each in a fresh process, from the verifier's own+copy of the instance (`tests/instance.json`; the start state is checked against its hash on every load); pass iff both+succeed and end in the same state (`deterministic`). Oracle: success after 63 control steps. `nop`: no trajectory, reward 0.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `locomotion/spot/xmls/scene_mjx_flat_terrain.xml`; MuJoCo Menagerie @ 1b86ece (`boston_dynamics_spot`); simulated in MuJoCo 3.3.7 on the CPU |+| Instance | Playground's `reset` with `jax.random.PRNGKey(1)` (a drop; the 0.5 s settle runs in the task's own MuJoCo); chosen by `scripts/mujoco-playground/select_instances.py` (seed 1; skipped 0: not dropped (starts standing)) |+| Actions | 12 joint position targets per control step (0.02 s of simulated time); kp = 400 N m/rad, joint damping 20 N m s/rad |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py` from `scripts/mujoco-playground/instances/SpotGetup.json`+(`make_instances.py`, `select_instances.py`) and `scripts/mujoco-playground/oracles/SpotGetup.npy` (`oracle.py`).diff --git a/tasks/mujoco_playground_spot_getup-privileged/environment/Dockerfile b/tasks/mujoco_playground_spot_getup-privileged/environment/Dockerfilenew file mode 100644index 0000000000..7bdd7d2938--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-privileged/environment/Dockerfile@@ -0,0 +1,8 @@+# MuJoCo Playground quadruped task (privileged): plain MuJoCo with Playground's and Menagerie's assets+# (images/mujoco/prepare_assets.sh), the task's tooling and its frozen instance.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY instance.json /app/instance.json+COPY rcb_quadruped.py /opt/tools/rcb_quadruped.py+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_spot_getup-privileged/environment/instance.json b/tasks/mujoco_playground_spot_getup-privileged/environment/instance.jsonnew file mode 100644index 0000000000..56466186bb--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-privileged/environment/instance.json@@ -0,0 +1,68 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "SpotGetup",+ "seed": 1,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 1.0,+ -0.6340193152427673,+ -0.3534443974494934,+ 0.6828494071960449,+ -0.08253868669271469,+ 0.5247290134429932,+ 0.13331857323646545,+ -1.1727977991104126,+ 0.7449409365653992,+ -0.023556871339678764,+ -2.530365228652954,+ 0.40282249450683594,+ 0.9718838334083557,+ -2.2890756130218506,+ -0.15391281247138977,+ 1.0196685791015625,+ -2.621039390563965+ ],+ "qvel0": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "dropped": true,+ "text": "Boston Dynamics Spot has fallen over. Make it get up and stand upright at its standing height.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": -345.2,+ "start_tilt_deg": 128.4,+ "start_imu_height_m": 0.381,+ "reference_rows": 63,+ "reference_tilt_deg": 0.47,+ "reference_imu_height": 0.4782+ },+ "state_sha": "b569d03708a2",+ "horizon": 300,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 2+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_spot_getup-privileged/environment/rcb_quadruped.py b/tasks/mujoco_playground_spot_getup-privileged/environment/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-privileged/environment/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_spot_getup-privileged/instruction.md b/tasks/mujoco_playground_spot_getup-privileged/instruction.mdnew file mode 100644index 0000000000..6dbfa07e6e--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-privileged/instruction.md@@ -0,0 +1,48 @@+# MuJoCo Playground · SpotGetup — frozen episode++**Task:** Boston Dynamics Spot has fallen over. Make it get up and stand upright at its standing height.++You control the Boston Dynamics Spot quadruped in one episode of MuJoCo Playground's `SpotGetup` environment, rebuilt in plain+MuJoCo 3.3.7 from Playground's own scene files (Apache-2.0, commit 4057c14) and the robot from MuJoCo Menagerie. The+episode is frozen: it starts the same way after every reset (Playground's `reset` with seed 1), and you may reset+as often as you like. Your deliverable is **one open-loop trajectory**, not a general policy.++## The episode+Playground's reset dropped the robot from 1 m in a random orientation with random joint angles (no base velocity), then let it settle for 0.5 s with its joints held: at t = 0 it lies with its trunk tilted 128.4 deg from upright. You have 300 control steps (6 s).++## Success+Success iff the trajectory (at most 300 rows) ends with 25 control steps in a row (0.5 s) after each of which the trunk is upright, tilted at most 10 deg (the angle between the IMU frame's z axis and world z), and the IMU is at least 0.4 m above the floor (the Spot stands at 0.44 m; lying down is below 0.38 m). End the trajectory once that holds. `s.check()` reports the last tilt, height and `success`.++## Deliverable+`/app/output/trajectory.npz` with `actions`: float64 (T, 12), one row per control step (0.02 s): absolute targets of+the 12 joint position actuators, in `s.joint_names` order (FL, FR, HL, HR legs, each hx (abduction), hy (hip pitch), kn (knee)), in radians; 1 <= T <= 300. Values+outside the actuator ranges (`s.lower`, `s.upper`) are clipped. `s.save_trajectory(rows)` writes it. Also leave the+script that produced it at `/app/output/gen.py`. Save a working trajectory as soon as you have one and overwrite it as+you improve it: whatever is in `/app/output/` when your 3600 s are up is graded. The tooling logs your sessions and+resets (cost accounting, not graded).++## Tooling (installed; `python` from any directory)+```python+from rcb_quadruped import Session+s = Session("/app/instance.json") # the frozen episode at t = 0 (checked against the instance's state hash)+s.joint_names; s.lower; s.upper # the actuator order and ranges (rad)+s.home # Playground's standing pose (its `home` keyframe), in that order+s.step(row) # one control step: 12 joint targets, 5 physics steps of 0.004 s; returns s.check()+s.check() # the task's check on the steps so far (see Success)+s.state() # qpos, qvel, IMU (local_linvel, gyro, gravity, accelerometer, pose), feet, contacts+s.sensor(name); s.gravity() # one MuJoCo sensor; gravity's direction in the IMU frame+s.model, s.data # the live MuJoCo model and data (read them; changing them is not part of the replay)+s.render(cam); s.cameras # uint8 (240, 320, 3) from cameras that follow the robot: `track`, `side`, `back`, `top` (they follow the robot)+s.reset() # back to t = 0+s.replay(rows) # reset, run the rows, return the check and the final state's hash+s.render_video(rows, "/app/output/try.mp4")+s.save_trajectory(rows, "/app/output/trajectory.npz")+```+The grader runs exactly this CLI in two fresh processes, so run it to check yourself:+`python /opt/tools/rcb_quadruped.py replay --instance /app/instance.json --traj /app/output/trajectory.npz`++## Conventions+- Joint position actuators (PD): kp = 400 N m/rad, joint damping 20 N m s/rad, as Playground's environment sets them; the physics step is 0.004 s,+ the control step 0.02 s (5 physics steps); a row holds until the next one.+- World frame z up, metres; quaternions **wxyz**. The IMU frame is the trunk's: x forward, y left, z up.+- Physics is MuJoCo on the CPU: the same rows from the same start give the same result in every fresh process.diff --git a/tasks/mujoco_playground_spot_getup-privileged/solution/oracle.npy b/tasks/mujoco_playground_spot_getup-privileged/solution/oracle.npynew file mode 100644index 0000000000..1198383fb3Binary files /dev/null and b/tasks/mujoco_playground_spot_getup-privileged/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_spot_getup-privileged/solution/oracle_replay.py b/tasks/mujoco_playground_spot_getup-privileged/solution/oracle_replay.pynew file mode 100644index 0000000000..46987df1d0--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-privileged/solution/oracle_replay.py@@ -0,0 +1,15 @@+"""Oracle (privileged): replay the reference rows in the tooling, check them, and save them as the deliverable."""+import json+import os+import sys++import numpy as np++sys.path.insert(0, "/opt/tools")+from rcb_quadruped import Session # noqa: E402++rows = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy"))+s = Session("/app/instance.json")+r = s.replay(rows)+s.save_trajectory(rows, "/app/output/trajectory.npz", meta={"source": "reference trajectory (solution/oracle.npy)"})+print(json.dumps({k: v for k, v in r.items() if k != "segments"}))diff --git a/tasks/mujoco_playground_spot_getup-privileged/solution/solve.sh b/tasks/mujoco_playground_spot_getup-privileged/solution/solve.shnew file mode 100755index 0000000000..430ffb6017--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-privileged/solution/solve.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Oracle (privileged): write the reference trajectory frozen at generation time (solution/oracle.npy; how it was made:+# scripts/mujoco-playground/oracle.py) as the deliverable.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_spot_getup-privileged/task.toml b/tasks/mujoco_playground_spot_getup-privileged/task.tomlnew file mode 100644index 0000000000..a51ec89f81--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-privileged/task.toml@@ -0,0 +1,43 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = ["/app/output/", "/logs/agent/rcb/"]++[task]+name = "robot-coding-bench/mujoco_playground_spot_getup-privileged"+description = "MuJoCo Playground SpotGetup in plain MuJoCo (Boston Dynamics Spot, joint position control every 0.02 s): Boston Dynamics Spot has fallen over. Make it get up and stand upright at its standing height. Produce one replayable trajectory of joint position targets on a frozen instance (Playground's reset with seed 1); graded by an upright stance held for the trajectory's last 0.5 s (two fresh-process replays)."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "boston-dynamics-spot", "quadruped", "locomotion", "getup", "code-as-policy", "trajectory", "privileged"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "boston-dynamics-spot"+family = "mujoco_playground/SpotGetup"+mode = "privileged"+oracle = "full"+instance_seed = 1 # the PRNGKey of Playground's reset (and, for the joystick tasks, its command process)+expert_time_estimate_hours = 2.0++[verifier]+timeout_sec = 1200.0+environment_mode = "separate"+network_mode = "no-network"++[verifier.environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192++[agent]+timeout_sec = 3600.0+# MuJoCo Playground's trained policies are public upstream, so the agent reaches the model APIs and nothing else+# (scripts/set_agent_egress.py HOSTS).+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_spot_getup-privileged/tests/Dockerfile b/tasks/mujoco_playground_spot_getup-privileged/tests/Dockerfilenew file mode 100644index 0000000000..f49c79154d--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-privileged/tests/Dockerfile@@ -0,0 +1,7 @@+# Separate verifier sandbox (PROTOCOL §4): the same image with the verifier's own copies of the tooling and the frozen+# instance. Nothing the agent did in its container reaches this one: Harbor uploads only the declared artifacts.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY grade.py instance.json rcb_quadruped.py test.sh /tests/+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier+ENV PYTHONPATH=/tests+WORKDIR /testsdiff --git a/tasks/mujoco_playground_spot_getup-privileged/tests/grade.py b/tasks/mujoco_playground_spot_getup-privileged/tests/grade.pynew file mode 100644index 0000000000..e5668de85f--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-privileged/tests/grade.py@@ -0,0 +1,126 @@+"""Verifier (privileged): replay /app/output/trajectory.npz from the frozen instance and write Harbor's rewards.++ python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz++Two replays, each in its own fresh process (`rcb_quadruped.py replay`: the frozen start, one control step per row, the+task's success check on the whole trajectory). success = both replays succeed and end in the same state. Writes+/logs/verifier/reward.txt (1/0) and reward.json (numbers only); then a third replay renders replay.mp4, after the+verdict is on disk (it never changes it).+"""+import argparse+import json+import os+import subprocess+import sys+import tempfile+import traceback++import numpy as np++LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")+TOOL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_quadruped.py")+REPLAY_TIMEOUT_S = 300 # a 1000-step replay takes a few seconds; the video replay renders 4 views every 2nd step+++def write(ok: bool, out: dict) -> None:+ os.makedirs(LOG_DIR, exist_ok=True)+ open(os.path.join(LOG_DIR, "reward.txt"), "w").write("1\n" if ok else "0\n")+ json.dump(out, open(os.path.join(LOG_DIR, "reward.json"), "w"))+ print(json.dumps(out), flush=True)+++def agent_cost() -> dict:+ """Self-reported cost from the tooling's log in the agent's container (accounting, not evidence)."""+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_replays": 0, "agent_cost_self_reported": 1}+ for path in ("/logs/agent/rcb/rcb_session_log.jsonl", "/app/output/rcb_session_log.jsonl"):+ if not os.path.exists(path):+ continue+ try:+ with open(path) as f:+ for i, line in enumerate(f):+ if i > 200_000 or len(line) > 10_000:+ break+ try:+ e = json.loads(line)+ ev = e.get("ev") if isinstance(e, dict) else None+ if ev == "session_start":+ cost["agent_sessions"] += 1+ elif ev == "reset":+ cost["agent_resets"] += 1+ elif ev == "replay":+ cost["agent_replays"] += 1+ elif ev == "session_end":+ cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)+ except Exception: # noqa: BLE001 -- one bad line must not sink the verdict+ continue+ except OSError:+ pass+ break+ return cost+++def replay(instance: str, traj: str, video: str | None) -> dict:+ """One replay in a fresh process; its result (`--out`), or {"error": ...}."""+ with tempfile.NamedTemporaryFile(suffix=".json") as out:+ cmd = [sys.executable, TOOL, "replay", "--instance", instance, "--traj", traj, "--out", out.name]+ try:+ p = subprocess.run(cmd + (["--video", video] if video else []), stdout=subprocess.DEVNULL, stderr=sys.stderr,+ timeout=REPLAY_TIMEOUT_S, env={**os.environ, "RCB_SESSION_LOG": "", "RCB_AGENT_TRACE_DIR": ""})+ except subprocess.TimeoutExpired:+ return {"error": f"replay took over {REPLAY_TIMEOUT_S} s"}+ try:+ return json.load(open(out.name))+ except ValueError:+ return {"error": f"replay process rc={p.returncode}"}+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--instance", required=True)+ ap.add_argument("--traj", default="/app/output/trajectory.npz")+ a = ap.parse_args()+ cost = agent_cost()+ if not os.path.isfile(a.traj):+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost})+ return 0+ try:+ horizon = int(json.load(open(a.instance))["horizon"])+ d = np.load(a.traj, allow_pickle=False)+ acts = np.asarray(d["actions"], dtype=np.float64) if "actions" in d.files else np.zeros((0, 0))+ if acts.ndim != 2 or acts.shape[1] != 12 or len(acts) > horizon or not np.all(np.isfinite(acts)):+ write(False, {"success": 0, "bad_trajectory": 1, "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0,+ "grader_error": 0, **cost})+ return 0+ runs = [replay(a.instance, a.traj, None), replay(a.instance, a.traj, None)]+ if any("error" in r and not r.get("bad_trajectory") for r in runs):+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ if not all(r.get("instance_ok") for r in runs): # the image no longer builds the frozen start: not the agent's 0+ write(False, {"success": 0, "grader_error": 1, "instance_mismatch": 1, **cost})+ return 0+ all_success = all(bool(r.get("success")) for r in runs)+ deterministic = runs[0].get("state_sha") == runs[1].get("state_sha")+ ok = all_success and deterministic+ r = runs[0]+ num = lambda k: float(r.get(k) if r.get(k) is not None else -1) # noqa: E731+ out = {"success": int(ok), "replay_success": int(all_success), "deterministic": int(deterministic),+ "n_actions": int(len(acts)), "horizon": horizon, "fell": int(r.get("fell_at") is not None),+ "fell_at_step": num("fell_at"), "worst_lin_err": num("worst_lin_err"), "worst_yaw_err": num("worst_yaw_err"),+ "end_tilt_deg": num("tilt_deg"), "end_imu_height": num("imu_height"), "end_pose_angle_deg": num("pose_angle_deg"),+ "grader_error": 0,+ "video_rendered": 0, **cost}+ write(ok, out) # the verdict, before any video+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ try: # the video, for humans: it never changes the verdict+ if replay(a.instance, a.traj, os.path.join(LOG_DIR, "replay.mp4")).get("video"):+ write(ok, {**out, "video_rendered": 1})+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/mujoco_playground_spot_getup-privileged/tests/instance.json b/tasks/mujoco_playground_spot_getup-privileged/tests/instance.jsonnew file mode 100644index 0000000000..56466186bb--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-privileged/tests/instance.json@@ -0,0 +1,68 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "SpotGetup",+ "seed": 1,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 1.0,+ -0.6340193152427673,+ -0.3534443974494934,+ 0.6828494071960449,+ -0.08253868669271469,+ 0.5247290134429932,+ 0.13331857323646545,+ -1.1727977991104126,+ 0.7449409365653992,+ -0.023556871339678764,+ -2.530365228652954,+ 0.40282249450683594,+ 0.9718838334083557,+ -2.2890756130218506,+ -0.15391281247138977,+ 1.0196685791015625,+ -2.621039390563965+ ],+ "qvel0": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "dropped": true,+ "text": "Boston Dynamics Spot has fallen over. Make it get up and stand upright at its standing height.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": -345.2,+ "start_tilt_deg": 128.4,+ "start_imu_height_m": 0.381,+ "reference_rows": 63,+ "reference_tilt_deg": 0.47,+ "reference_imu_height": 0.4782+ },+ "state_sha": "b569d03708a2",+ "horizon": 300,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 2+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_spot_getup-privileged/tests/rcb_quadruped.py b/tasks/mujoco_playground_spot_getup-privileged/tests/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-privileged/tests/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_spot_getup-privileged/tests/test.sh b/tasks/mujoco_playground_spot_getup-privileged/tests/test.shnew file mode 100755index 0000000000..1c3d2f767b--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-privileged/tests/test.sh@@ -0,0 +1,9 @@+#!/bin/bash+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in two fresh processes (the+# verdict), then a third that renders replay.mp4.+# Writes /logs/verifier/reward.txt (1/0) and reward.json (numeric fields, docs/PROTOCOL.md §2.6).+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/*+mkdir -p /logs/verifier+python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz 2> /logs/verifier/grade.logdiff --git a/tasks/mujoco_playground_spot_getup-standard/README.md b/tasks/mujoco_playground_spot_getup-standard/README.mdnew file mode 100644index 0000000000..48cf3b449d--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/README.md@@ -0,0 +1,44 @@+# mujoco_playground_spot_getup-standard++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | standard (`eai-standard/2.2`) |+| Twin | `mujoco_playground_spot_getup-privileged` |+| Simulator / robot | `mujoco` / `boston-dynamics-spot` |+| Family / instance | `mujoco_playground/SpotGetup` / seed 1 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `SpotGetup` (Boston Dynamics Spot) on the same frozen instance as `mujoco_playground_spot_getup-privileged`: Boston Dynamics Spot has fallen over. Make it get up and stand upright at its standing height.+It starts lying with its trunk tilted 128.4 deg (Playground's random drop, then a 0.5 s settle) and has 6 s to stand upright at its standing height. Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with only+the robot's own sensors and four cameras that follow it.++## Difficulty+Same instance and success check as `mujoco_playground_spot_getup-privileged`. In standard mode the agent loses resets, the simulator and+the world state: it sees camera images and proprioception (joints, IMU, foot contacts), acts in joint position chunks,+and gets one episode, so it has to close the loop on the robot's own sensors and recover from its own mistakes without+starting over.++## Reference solution+`solution/oracle_replay.py` streams the privileged reference's rows (`solution/oracle.npy`, 63 rows, float32-exact)+through the client in `hold` chunks; it uses no privileged information at run time. The service's recorded trajectory+is then exactly the privileged reference, and the episode ends with success after 63 control steps.++## Verification+The sim service judges the episode live and records every executed control step; the collect hook+(`environment/sim/finalize.sh`) ends the service, replays the recorded trajectory in two fresh processes and writes+`final.json`; `tests/grade.py` (separate sandbox, no network) passes iff the live check succeeded, both replays succeed,+and they end in the same state. Oracle: success after 63 control steps.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `locomotion/spot/xmls/scene_mjx_flat_terrain.xml`; MuJoCo Menagerie @ 1b86ece (`boston_dynamics_spot`); MuJoCo 3.3.7 on the CPU |+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); cameras `track`, `side`, `back`, `top` (they follow the robot) (320 x 240), the feet's kinematics in the trunk frame |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py`, as its privileged twin.diff --git a/tasks/mujoco_playground_spot_getup-standard/environment/Dockerfile b/tasks/mujoco_playground_spot_getup-standard/environment/Dockerfilenew file mode 100644index 0000000000..ed5eee3703--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/environment/Dockerfile@@ -0,0 +1,9 @@+# Standard mode: the agent container has NO simulator and no Playground code, only Python and the client, on the shared+# pinned client base with the shared pins (scripts/eai_standard/client.env, client-requirements.txt).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY client-requirements.txt /tmp/client-requirements.txt+RUN pip install --no-cache-dir -r /tmp/client-requirements.txt+COPY rcb_client.py rcb1.py /opt/tools/+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_spot_getup-standard/environment/client-requirements.txt b/tasks/mujoco_playground_spot_getup-standard/environment/client-requirements.txtnew file mode 100644index 0000000000..8aa73a968f--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/environment/client-requirements.txt@@ -0,0 +1,11 @@+# Exact pins for what the standard agent container installs (and a verifier, if it installs anything): the closure of+# `pip install requests numpy pillow scipy`, the unpinned line of every standard task at 9eb18edf, resolved on+# 2026-10-01 in CLIENT_IMAGE (client.env: Python 3.12.14, pip 25.0.1). A change here is a shared-files PR.+certifi==2026.7.22+charset-normalizer==3.5.2+idna==3.20+numpy==2.5.3+pillow==12.3.0+requests==2.34.2+scipy==1.18.1+urllib3==2.8.0diff --git a/tasks/mujoco_playground_spot_getup-standard/environment/docker-compose.yaml b/tasks/mujoco_playground_spot_getup-standard/environment/docker-compose.yamlnew file mode 100644index 0000000000..8ec63c582e--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/environment/docker-compose.yaml@@ -0,0 +1,23 @@+# Standard mode: the simulator runs in the `sim` sidecar (the agent cannot open it); the agent only reaches port 8000.+# No `expose`/`ports` on sim: under Harbor's egress control it shares main's network namespace (localhost:8000).+# CPU only: MuJoCo physics and rendering (EGL when a GPU is there, else OSMesa); no GPU reservation.+# Crash recovery (docs/STANDARD_MODE_2_2.md §13): run.sh exits non-zero when the service crashes, compose restarts the+# container (same container, same /data) and the service replays its journal into the same episode, never a reset.+services:+ main:+ depends_on: [sim]+ sim:+ image: ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+ volumes:+ - ./sim:/srv:ro+ working_dir: /tmp+ command: sh /srv/run.sh+ restart: on-failure:6 # N >= 3 (PROTOCOL §4.1); a resume continues the episode+ environment:+ RCB_INSTANCE: /srv/instance.json+ RCB_TOOL: /srv/rcb_quadruped.py+ RCB_DATA: /data+ RCB_WALL_CLOCK_S: "3600"+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in about a second+ PYTHONPATH: /srv+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction logdiff --git a/tasks/mujoco_playground_spot_getup-standard/environment/rcb1.py b/tasks/mujoco_playground_spot_getup-standard/environment/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/environment/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_spot_getup-standard/environment/rcb_client.py b/tasks/mujoco_playground_spot_getup-standard/environment/rcb_client.pynew file mode 100644index 0000000000..aa25b0e050--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/environment/rcb_client.py@@ -0,0 +1,211 @@+"""eai-standard/2.2 client (formerly rcb-limited/2.x) — the only thing a standard-mode agent gets (installed at+/opt/tools/rcb_client.py).++ from rcb_client import Robot+ r = Robot() # finds the service (sim:8000, then localhost:8000), waits for warm-up+ spec = r.spec() # actions, cameras (+ intrinsics, mounting), robot_spec, world, budget, kinematics+ obs = r.get_obs() # current frames: obs.last[cam] -> uint8 (H,W,3); obs.meta["proprio"]+ obs = r.get_obs(depth=True) # + obs.last_depth[cam] -> float32 (H,W) z-depth in metres, 0 = no reading+ res = r.submit("joint_position", A, dt=0.1) # A: (T, dim) rows dt apart; returns the execution video+ res = r.submit("ee_pose", P) # (T, dim) end-effector targets (see spec()["action_types"])+ res.video[cam] -> mp4 bytes res.frames[cam] -> uint8 (N,H,W,3) if video="frames"/"both" res.last[cam]+ res.proprio -> float32 (N, D), one row per frame (names: spec()["proprio_layout"]; res.group("tcp_pose"))+ res.frame_step -> int64 (N,) control step of each frame res.frame_time_s -> float64 (N,) simulated time+ res.extrinsic_cv[cam] -> float64 (N,3,4) world->camera per frame (res.meta["cameras"]: intrinsics + the last frame's pose)+ res = r.submit(..., depth="frames") # + res.depth[cam] -> float32 (N,H,W) metres, one per frame (1 mm steps)+ r.fk(q) # {"ok", "poses": {frame: [x,y,z, quaternion]}}: forward kinematics, no physics+ r.ik({frame: pose}, seed=q) # {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}: inverse kinematics+ res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, frames/<cam>/NNN.jpg, proprio.npy, depth, frame_meta.npz+ obs = r.get_obs(seconds=3, video="both") # hold the last command, let physics run 3 s, return the video+ r.status() # calls, control steps, done, reason, elapsed time++Nothing is put into your context automatically: what you look at, and where you store it, is your code's decision.++If a call fails with a connection error or a 5xx, the service may have crashed; it restarts and resumes the SAME episode+(never a reset) in the state after the last call it completed, which you may not have received. r.wait_ready() waits+until it answers again (resuming replays the episode so far: long episodes can take minutes); then check r.status()+before you continue (spec()["on_service_error"]).+"""+from __future__ import annotations+import json, os, pathlib, sys, time, zlib+import numpy as np+import requests+import rcb1++PROTOCOL = "eai-standard/2.2" # also talks to 2.0 / 2.1 services (they ignore depth and send no frame metadata)+ACCEPTED = ("eai-standard/2.", "rcb-limited/2.") # every 2.x service, under the protocol's current and former name+++class EpisodeOver(RuntimeError):+ pass+++def _decode_depth_frames(p: dict) -> np.ndarray:+ a = np.frombuffer(zlib.decompress(p["data"]), dtype="<u2").reshape(p["shape"])+ return a.astype(np.float32) / 1000.0+++class Result:+ """Decoded RCB1 response: meta (dict), video (cam -> mp4 bytes), frames (cam -> uint8 (N,H,W,3)), last (cam -> uint8+ (H,W,3)), last_depth (cam -> float32 (H,W) m), depth (cam -> float32 (N,H,W) m, one per frame), proprio (float32 (N,D)),+ frame_step (int64 (N,)), frame_time_s (float64 (N,)), extrinsic_cv (cam -> float64 (N,3,4)). save(dir) writes it out;+ show(cam, k) returns one frame; group(name) the proprio columns of one spec()["proprio_groups"] group. stopped: None,+ or why the service stopped the call early ("max_call_wall_s": it ran longer than spec()["max_call_wall_s"]); then+ meta["executed_rows"] < the rows sent, and meta["proprio"]["now"] is where the robot is."""+ def __init__(self, meta: dict, parts: dict, spec: dict | None = None):+ self.meta = meta; self.raw = parts; self._spec = spec or {}; self.stopped = meta.get("stopped")+ self.video, self.frames, self.last, self.last_depth, self.depth, self.extrinsic_cv = {}, {}, {}, {}, {}, {}+ self.proprio = None; self.frame_step = None; self.frame_time_s = None+ for name, p in parts.items():+ kind, data = p["kind"], p["data"]+ if name.startswith("video/") and kind == "mp4": self.video[name[6:]] = data+ elif name.startswith("frames/") and kind == "array": self.frames[name[7:]] = data+ elif name.startswith("last/") and kind == "array": self.last[name[5:]] = data+ elif name.startswith("last_depth/") and kind == "array": self.last_depth[name[11:]] = np.asarray(data, dtype=np.float32)+ elif name.startswith("depth_frames/") and p.get("codec") == "zlib": self.depth[name[13:]] = _decode_depth_frames(p)+ elif name.startswith("depth/") and kind == "array": self.depth[name[6:]] = np.asarray(data, dtype=np.float32) # 2.1 form+ elif name.startswith("extrinsic_cv/") and kind == "array": self.extrinsic_cv[name[13:]] = data+ elif name == "proprio": self.proprio = data+ elif name == "frame_step": self.frame_step = data+ elif name == "frame_time_s": self.frame_time_s = data++ @property+ def done(self) -> bool: return bool(self.meta.get("done"))++ def show(self, camera: str, k: int = -1) -> np.ndarray:+ if camera in self.frames: return self.frames[camera][k]+ return self.last[camera]++ def group(self, name: str, now: bool = False) -> np.ndarray:+ """Columns of proprio group `name` (spec()["proprio_groups"]): (N, n) over the frames, or (n,) of meta["proprio"]["now"]."""+ first, n = self._spec["proprio_groups"][name][:2]+ if now: return np.asarray(self.meta["proprio"]["now"], dtype=np.float64)[first:first + n]+ return self.proprio[:, first:first + n]++ def save(self, out_dir: str) -> str:+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ (out / "meta.json").write_text(json.dumps(self.meta, indent=1))+ for cam, b in self.video.items(): (out / f"{cam}.mp4").write_bytes(b)+ try:+ from PIL import Image+ for cam, img in self.last.items():+ (out / "last").mkdir(exist_ok=True); Image.fromarray(np.ascontiguousarray(img)).save(out / "last" / f"{cam}.jpg", quality=90)+ for cam, arr in self.frames.items():+ d = out / "frames" / cam; d.mkdir(parents=True, exist_ok=True)+ for i, f in enumerate(arr): Image.fromarray(np.ascontiguousarray(f)).save(d / f"{i:03d}.jpg", quality=85)+ except ImportError:+ for cam, img in self.last.items(): np.save(out / f"last_{cam}.npy", img)+ for cam, arr in self.frames.items(): np.save(out / f"frames_{cam}.npy", arr)+ for cam, arr in self.last_depth.items(): np.save(out / f"last_depth_{cam}.npy", arr)+ for cam, arr in self.depth.items(): np.savez_compressed(out / f"depth_{cam}.npz", depth_mm=np.rint(arr * 1000).astype(np.uint16))+ if self.proprio is not None: np.save(out / "proprio.npy", self.proprio)+ if self.frame_step is not None:+ np.savez(out / "frame_meta.npz", frame_step=self.frame_step, frame_time_s=self.frame_time_s,+ **{f"extrinsic_cv/{c}": e for c, e in self.extrinsic_cv.items()})+ return str(out)+++class Robot:+ def __init__(self, base: str | None = None, timeout: float = 600.0):+ cands = [base or os.environ.get("SIM_URL"), "http://sim:8000", "http://localhost:8000"]+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ for b in [c for c in cands if c]:+ try:+ r = requests.get(b + "/spec", timeout=(5, 30))+ if r.status_code == 503: last = "warming up"; break+ r.raise_for_status(); self.base = b; self._spec = r.json()+ if not str(self._spec.get("protocol", "")).startswith(ACCEPTED):+ raise RuntimeError(f"not a 2.x service: protocol {self._spec.get('protocol')!r}")+ return+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(2)+ raise RuntimeError(f"sim service unavailable: {last}")++ def spec(self) -> dict:+ return self._spec++ def _post(self, path: str, meta: dict, parts: list, timeout: float) -> Result:+ body = rcb1.encode(meta, parts)+ r = requests.post(self.base + path, data=body, headers={"Content-Type": "application/x-rcb1"}, timeout=(5, timeout))+ if r.status_code == 409:+ raise EpisodeOver(r.json().get("reason") if r.headers.get("Content-Type", "").startswith("application/json") else "episode finished")+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ m, p = rcb1.decode(r.content); return Result(m, p, self._spec)++ def _common(self, cameras, video_fps, depth, include_depth) -> dict:+ cams = list(cameras) if cameras is not None else self._spec.get("default_cameras")+ if depth is None or depth is False: depth = "frames" if include_depth else "none"+ elif depth is True: depth = "last"+ m = {"cameras": cams, "video_fps": None if video_fps is None else int(video_fps), "depth": depth}+ return {k: v for k, v in m.items() if v is not None}++ def submit(self, action_type: str, actions, dt: float | None = None, interpolate: str = "linear", cameras=None,+ video_fps: int | None = None, video: str = "mp4", depth=None, include_depth: bool = False, note: str = "") -> Result:+ """Execute a chunk of low-level actions (T, dim); see spec()['action_types'] for dims, layouts, limits and semantics.+ dt defaults to one control period, cameras to spec()['default_cameras']; depth: None | True (= "last") | "frames"."""+ a = np.asarray(actions, dtype=np.float32)+ if a.ndim == 1: a = a[None, :]+ if dt is None and self._spec.get("control_hz"): dt = 1.0 / float(self._spec["control_hz"])+ meta = {"type": action_type, "interpolate": interpolate, "video": video, "note": note,+ **({} if dt is None else {"dt": float(dt)}), **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/submit", meta, [rcb1.array_part("actions", a)], timeout=1800)+ if res.stopped:+ print(f"[rcb_client] the service stopped this call early ({res.stopped}): {res.meta.get('executed_rows')} of {len(a)} rows "+ "executed; meta['proprio']['now'] is where the robot is", file=sys.stderr)+ return res++ def get_obs(self, cameras=None, seconds: float = 0.0, video_fps: int | None = None, depth=None, include_depth: bool = False,+ video: str = "frames") -> Result:+ """Current frames (seconds=0, free) or hold the last command and watch for `seconds` (returns the video).+ depth: None | True (= "last": the last frame's depth) | "frames" (one depth map per frame)."""+ meta = {"seconds": float(seconds), "video": video, **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/observe", meta, [], timeout=600)+ if res.stopped:+ print(f"[rcb_client] the service stopped this watch early ({res.stopped}) after {res.meta.get('control_steps_watch')} control "+ "steps", file=sys.stderr)+ return res++ def status(self) -> dict:+ r = requests.get(self.base + "/status", timeout=(5, 60)); r.raise_for_status(); return r.json()++ def wait_ready(self, timeout: float = 3600.0) -> dict:+ """After a connection error: wait until the service answers GET /status again (it resumes the same episode after a+ crash), then return the status. Raises RuntimeError after `timeout` seconds."""+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ try:+ return self.status()+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(5)+ raise RuntimeError(f"sim service did not come back within {timeout:.0f} s: {last}")++ def kinematics(self, body: dict) -> dict:+ """POST /kinematics (stateless: never moves the robot, never advances time). Raises ValueError on a bad request."""+ r = requests.post(self.base + "/kinematics", json=body, timeout=(5, 120))+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ return r.json()++ def fk(self, q, links=None, base_pose=None) -> dict:+ """Forward kinematics: q in spec()['kinematics']['joint_names'] order -> {"ok", "frame", "poses": {link: [x,y,z, quat]}}+ (quaternion order spec()['world']['quaternion_order']; a mobile robot answers in its base frame unless base_pose is given)."""+ body = {"op": "fk", "q": [float(v) for v in np.asarray(q).reshape(-1)]}+ if links is not None: body["links"] = list(links)+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)++ def ik(self, targets: dict, seed=None, base_pose=None, **opts) -> dict:+ """Inverse kinematics: {frame: [x,y,z, quat]} (frames from spec()['kinematics']['ik_targets']) and an optional seed q ->+ {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}. opts: tol_pos_m, tol_rot_rad, max_iters."""+ body = {"op": "ik", "targets": {k: [float(v) for v in p] for k, p in targets.items()}, **opts}+ if seed is not None: body["seed"] = [float(v) for v in np.asarray(seed).reshape(-1)]+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)diff --git a/tasks/mujoco_playground_spot_getup-standard/environment/sim/finalize.sh b/tasks/mujoco_playground_spot_getup-standard/environment/sim/finalize.shnew file mode 100755index 0000000000..02048ddc74--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/environment/sim/finalize.sh@@ -0,0 +1,80 @@+#!/bin/sh+# [[verifier.collect]] hook, run inside the `sim` sidecar once Harbor has stopped the agent's container.+# 1. `rcb_limited.py end` (docs/STANDARD_MODE_2_2.md §13.3): SIGUSR1 to the service, which ends the episode if the+# agent had not (reason "timeout"), writes trajectory.npz + episode.json (live verdict, final-state hash) and exits.+# It exits 2 when final.json already holds the verdict (the service gave up after crashes): that verdict stays.+# 2. replay the trajectory from the frozen instance in TWO fresh processes (`rcb_quadruped.py replay`, the privileged+# verifier's replay): determinism = fresh process == fresh process; live_matches_replay = live == replay.+# 3. merge everything into final.json, the only thing the verifier sandbox grades;+# 4. a third replay renders replay.mp4, after the verdict is on disk (it never changes it).+set -u+DATA="${RCB_DATA:-/data}"; TOOL="${RCB_TOOL:?}"; INSTANCE="${RCB_INSTANCE:?}"+python /srv/rcb_limited.py end "$DATA" --timeout "${RCB_COLLECT_END_TIMEOUT_S:-900}"; rc=$?+if [ "$rc" = 2 ]; then+ echo "[finalize] final.json already holds the verdict; no replay"; exit 0+fi+if [ "$rc" != 0 ]; then+ echo "[finalize] the service did not end and dump the episode in time (rc $rc): an infrastructure failure"+ python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data"); p = os.path.join(d, "final.json")+try:+ out = json.load(open(p))+except Exception:+ out = {}+out.update({"finalized": True, "success": False, "replay_success": False, "deterministic": False, "infra_error": 1,+ "error": "collect hook: the sim service did not end and dump the episode in time"})+json.dump(out, open(p, "w"))+print(json.dumps(out))+PY+ exit 0+fi+replay() { # <n> [--video FILE]: one replay in a fresh process, its result in $DATA/replay<n>.json+ n=$1; shift+ RCB_SESSION_LOG= python "$TOOL" replay --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --out "$DATA/replay$n.json" \+ "$@" > /dev/null 2> "$DATA/replay$n.log"+ echo "[finalize] replay $n exit $?"+}+echo "[finalize] episode dumped; replaying twice in fresh processes"+rm -f "$DATA/replay1.json" "$DATA/replay2.json" "$DATA/replay3.json"+replay 1+replay 2+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+def result(name):+ try:+ v = json.load(open(os.path.join(d, name)))+ except (OSError, ValueError):+ return {}+ return v if isinstance(v, dict) else {}+out = {"replay_success": False, "deterministic": False, "video": False}+try:+ out.update(json.load(open(os.path.join(d, "episode.json"))))+except Exception as exc:+ out["error"] = f"no episode.json: {exc!r}"+a, b = result("replay1.json"), result("replay2.json")+out["replay_success"] = bool(a.get("success")) and bool(b.get("success"))+out["replay_sha"], out["replay_sha2"] = a.get("state_sha"), b.get("state_sha")+out["deterministic"] = bool(a.get("state_sha")) and a.get("state_sha") == b.get("state_sha")+out["live_matches_replay"] = bool(a.get("state_sha")) and a.get("state_sha") == out.get("live_sha")+if not (a.get("state_sha") and b.get("state_sha")): # a replay process died (it crashed or timed out): not the agent's 0+ out.update({"replay_failed": 1, "infra_error": 1,+ "error": "a replay process gave no result (replay1.log / replay2.log)"})+elif not (a.get("instance_ok") and b.get("instance_ok")): # the image no longer builds the frozen start: not the agent's 0+ out.update({"instance_mismatch": 1, "infra_error": 1, "error": "a replay did not start in the instance's t = 0 state"})+out["finalized"] = True+json.dump(out, open(os.path.join(d, "final.json"), "w"))+print(json.dumps(out))+PY+replay 3 --video "$DATA/replay.mp4"+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+try:+ shown = json.load(open(os.path.join(d, "replay3.json"))).get("video")+except (OSError, ValueError):+ shown = False+if shown:+ p = os.path.join(d, "final.json"); out = json.load(open(p)); out["video"] = True; json.dump(out, open(p, "w"))+PYdiff --git a/tasks/mujoco_playground_spot_getup-standard/environment/sim/instance.json b/tasks/mujoco_playground_spot_getup-standard/environment/sim/instance.jsonnew file mode 100644index 0000000000..56466186bb--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/environment/sim/instance.json@@ -0,0 +1,68 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "SpotGetup",+ "seed": 1,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 1.0,+ -0.6340193152427673,+ -0.3534443974494934,+ 0.6828494071960449,+ -0.08253868669271469,+ 0.5247290134429932,+ 0.13331857323646545,+ -1.1727977991104126,+ 0.7449409365653992,+ -0.023556871339678764,+ -2.530365228652954,+ 0.40282249450683594,+ 0.9718838334083557,+ -2.2890756130218506,+ -0.15391281247138977,+ 1.0196685791015625,+ -2.621039390563965+ ],+ "qvel0": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "dropped": true,+ "text": "Boston Dynamics Spot has fallen over. Make it get up and stand upright at its standing height.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": -345.2,+ "start_tilt_deg": 128.4,+ "start_imu_height_m": 0.381,+ "reference_rows": 63,+ "reference_tilt_deg": 0.47,+ "reference_imu_height": 0.4782+ },+ "state_sha": "b569d03708a2",+ "horizon": 300,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s) or when the reference trajectory\n (oracle.py) fails the task's success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 2+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_spot_getup-standard/environment/sim/rcb1.py b/tasks/mujoco_playground_spot_getup-standard/environment/sim/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/environment/sim/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_spot_getup-standard/environment/sim/rcb_limited.py b/tasks/mujoco_playground_spot_getup-standard/environment/sim/rcb_limited.pynew file mode 100644index 0000000000..1ce1171787--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/environment/sim/rcb_limited.py@@ -0,0 +1,930 @@+"""eai-standard/2.2 (formerly rcb-limited/2.2): the HTTP layer, the protocol helpers and the crash recovery that every+2.2 sim service shares (docs/STANDARD_MODE_2_2.md; the 2.1 base is docs/LIMITED_MODE_PROTOCOL.md).++The source is scripts/eai_standard/rcb_limited.py; the generators copy it unchanged into every standard task's+environment/sim/ (ci_checks/check-tooling-identity.sh). A service keeps its simulator to itself (scene, action+execution, cameras, kinematic model) and hands this module plain callables:++ import rcb_limited as L+ EP = L.Episode(DATA, dim=N, resume="exact") # before the scene is built; "approx" for a nondeterministic simulator+ EP.startup() # start count, back-off after failed starts, startup watchdog+ S = <build the scene>; EP.scene_built() # the watchdog stands down+ def ctrl_step(a, rec): # every executed control step+ S.step(a); stop = EP.journal(a); rec.tick(); return E["done"] or stop+ rec = L.Recorder(cams, every, grab, proprio_row, extrinsics, clock, depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+ rec.tick(force=True) # first frame (before the chunk / watch)+ ...; rec.tick(); ... # after every control step: a frame every `every` steps+ rec.tick(force=True, last=True) # last frame (+ its depth)+ parts = rec.parts(video, fps) # RCB1 parts: video/ frames/ last/ extrinsic_cv/ last_depth/ depth_frames/ depth/ proprio frame_*+ S.record_start()+ EP.begin(state=E, step=S.step, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, start_event={...}, on_end=end_fn)+ L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics,+ status=status, on_submit_error=lambda exc: finish("error"), log=EP.log,+ episode=EP, state_sha=S.state_sha, proprio=proprio_row))++ grab(cams, want_depth) -> ({cam: uint8 (H,W,3)}, {cam: float32 (H,W) z-depth in metres, 0 = no reading})+ extrinsics(cams) -> {cam: (3,4) world -> camera, OpenCV axes (x right, y down, z forward)}+ proprio_row() -> float32 (len(spec["proprio_layout"]),)+ clock() -> int, control steps since the episode start (the frame's step index)+ do_kinematics(req) -> dict; `req` is parse_kinematics(body, spec["kinematics"]); it must never step physics++None of the callables may step physics. check_spec(SPEC) runs in serve(): a service whose /spec misses a 2.2 field, or+carries a field the protocol forbids (segmentation, object identities or sizes, physical parameters), does not start.+Crash recovery (class Episode; PROTOCOL §4.7): every executed control step is journaled, every completed call+checkpointed (rows, state hash, the robot's proprio row); after a crash compose restarts the container and the service+replays the journal and continues the SAME episode, never a reset. `python rcb_limited.py end <data dir>` is the shared+first half of a collect hook."""+from __future__ import annotations+import faulthandler, json, math, os, re, select, signal, socket, sys, tempfile, threading, time, traceback, zlib+from http.server import BaseHTTPRequestHandler, HTTPServer+from typing import Any, Callable++import numpy as np++import rcb1++PROTOCOL = "eai-standard/2.2"+COMPAT = ["rcb-limited/2.0", "rcb-limited/2.1", "eai-standard/2.1"] # requests written for these are served unchanged+MAX_BODY = 64 * 1024 * 1024+MAX_RESP = 256 * 1024 * 1024+DEPTH_MODES = ("none", "last", "frames")+DEPTH_MAX_M = 65.535 # uint16 millimetres; a farther surface reads 0 (no reading)+DEPTH_NOISE = os.environ.get("RCB_DEPTH_NOISE", "off").strip().lower() # off | realsense (as rcb-limited/2.1)+_RNG = np.random.default_rng(int(os.environ.get("RCB_DEPTH_NOISE_SEED", "0")))+PROPRIO_GROUPS_REQUIRED = ("joint_pos", "joint_vel", "gripper_opening", "tcp_pose", "joint_effort")+PART_PREFIXES = ("video/", "frames/", "last/", "last_depth/", "depth_frames/", "depth/", "extrinsic_cv/")+PART_NAMES = ("proprio", "frame_step", "frame_time_s")+++# ---------------------------------------------------------------- depth+def depth_mode(meta: dict) -> str:+ """The request's depth mode: "none" | "last" | "frames" (2.2 field `depth`), or "legacy" for a 2.0/2.1 request that+ sets `include_depth: true` and no `depth` (answered as 2.1 did: `depth/<cam>` float16 (N,H,W) metres)."""+ d = meta.get("depth")+ if d is None or d is False:+ return "legacy" if meta.get("include_depth") is True else "none"+ if d is True:+ return "last"+ if isinstance(d, str) and d in DEPTH_MODES:+ return d+ raise ValueError(f"depth must be one of {'|'.join(DEPTH_MODES)} (got {d!r})")+++def clean_depth(z) -> np.ndarray:+ """float32 z-depth in metres: non-finite, negative and beyond-range pixels read 0 (no reading); the optional+ RCB_DEPTH_NOISE=realsense model (sigma = 2 mm + 2.5 mm * z^2, 1 % dropouts) is applied here, after rendering, so it+ never touches physics."""+ z = np.asarray(z, dtype=np.float32).copy()+ if z.ndim == 3 and z.shape[-1] == 1:+ z = z[..., 0]+ bad = ~np.isfinite(z) | (z <= 0) | (z > DEPTH_MAX_M)+ z[bad] = 0.0+ if DEPTH_NOISE == "realsense":+ valid = z > 0+ z = z + _RNG.normal(0.0, 1.0, z.shape).astype(np.float32) * (0.002 + 0.0025 * z * z)+ z[_RNG.random(z.shape) < 0.01] = 0.0+ z[~valid] = 0.0+ z[(z < 0) | (z > DEPTH_MAX_M)] = 0.0+ return z.astype(np.float32)+++def depth_frames_part(name: str, stack: np.ndarray) -> tuple[str, str, bytes, dict]:+ """(N,H,W) metres -> an RCB1 "bytes" part: zlib of C-order uint16 millimetres (0 = no reading). Clients that do not+ know it keep the raw bytes and ignore it; rcb_client decodes it back to float32 metres."""+ mm = np.rint(np.asarray(stack, dtype=np.float64) * 1000.0)+ mm[(mm < 0) | (mm > 65535)] = 0+ a = np.ascontiguousarray(mm.astype("<u2"))+ return (name, "bytes", zlib.compress(a.tobytes(), 1), {"codec": "zlib", "dtype": "uint16", "shape": list(a.shape), "unit": "mm"})+++def encode_mp4(frames: np.ndarray, fps: int) -> bytes:+ """H.264 mp4 (yuv420p, faststart) of uint8 (N,H,W,3) frames: the same encoding every 2.0 service used."""+ import imageio.v2 as imageio+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tf:+ path = tf.name+ try:+ with imageio.get_writer(path, format="FFMPEG", mode="I", fps=fps, codec="libx264", macro_block_size=1,+ output_params=["-movflags", "+faststart", "-pix_fmt", "yuv420p"]) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ return open(path, "rb").read()+ finally:+ try:+ os.unlink(path)+ except OSError:+ pass+++# ---------------------------------------------------------------- recording what the cameras see during one call+class Recorder:+ """Frames of the requested cameras every `every` clock ticks, plus forced first/last frames; for every frame the+ proprio row, the clock (step index), each camera's extrinsics and, if asked, its depth. All arrays share one frame+ axis N: frames/<cam>, the mp4's frames, proprio, frame_step, frame_time_s, extrinsic_cv/<cam>, depth_frames/<cam>."""++ def __init__(self, cameras, every: int, grab: Callable, proprio_row: Callable, extrinsics: Callable, clock: Callable,+ depth: str = "none", clock_hz: float = 1.0):+ if depth not in DEPTH_MODES + ("legacy",):+ raise ValueError(f"bad depth mode {depth!r}")+ self.cams = list(cameras); self.every = max(1, int(every)); self.mode = depth; self.hz = float(clock_hz)+ self._grab, self._prop, self._ext, self._clock = grab, proprio_row, extrinsics, clock+ self.frames: dict = {c: [] for c in self.cams}; self.depth: dict = {c: [] for c in self.cams}+ self.ext: dict = {c: [] for c in self.cams}; self.last_depth: dict = {}+ self.prop: list = []; self.steps: list = []; self.n = 0; self.missing = 0++ def tick(self, force: bool = False, last: bool = False) -> None:+ if force or last or self.n % self.every == 0:+ self._capture(last)+ self.n += 1++ def _capture(self, last: bool) -> None:+ want = self.mode in ("frames", "legacy") or (last and self.mode == "last")+ rgb, dep = self._grab(self.cams, want)+ ext = self._ext(self.cams)+ for c in self.cams:+ img = rgb.get(c)+ if img is not None:+ img = np.ascontiguousarray(np.asarray(img)[..., :3].astype(np.uint8))+ else: # a camera that failed to render: a black frame (sized in parts()) keeps one frame axis+ self.missing += 1+ self.frames[c].append(img)+ e = ext.get(c)+ self.ext[c].append(np.full((3, 4), np.nan) if e is None else np.asarray(e, dtype=np.float64).reshape(3, 4))+ if want:+ d = dep.get(c)+ if d is None:+ d = np.zeros(img.shape[:2] if img is not None else (1, 1), np.float32)+ else:+ d = clean_depth(d)+ if img is not None and d.shape != img.shape[:2]:+ raise RuntimeError(f"depth of {c} is {d.shape}, its RGB {img.shape[:2]}: they must be pixel-aligned")+ if self.mode in ("frames", "legacy"):+ self.depth[c].append(d)+ if last or self.mode == "frames":+ self.last_depth[c] = d+ self.prop.append(np.asarray(self._prop(), dtype=np.float32).reshape(-1))+ self.steps.append(int(self._clock()))++ def parts(self, video: str, fps: int) -> list:+ if self.mode == "last" and not self.last_depth and self.prop: # no last=True tick: the state has not moved since+ _, dep = self._grab(self.cams, True)+ self.last_depth = {c: clean_depth(dep[c]) for c in self.cams if c in dep}+ out = []+ for c in self.cams:+ good = [f for f in self.frames[c] if f is not None]+ hw = good[-1].shape[:2] if good else (1, 1)+ if len(good) < len(self.frames[c]):+ self.frames[c] = [f if f is not None else np.zeros(hw + (3,), np.uint8) for f in self.frames[c]]+ self.depth[c] = [d if d.shape == hw else np.zeros(hw, np.float32) for d in self.depth[c]]+ if c in self.last_depth and self.last_depth[c].shape != hw:+ self.last_depth[c] = np.zeros(hw, np.float32)+ fr = np.stack(self.frames[c]) if self.frames[c] else np.zeros((0, 1, 1, 3), np.uint8)+ if video in ("mp4", "both") and len(fr):+ out.append((f"video/{c}", "mp4", encode_mp4(fr, fps), {"fps": fps, "n": int(len(fr))}))+ if video in ("frames", "both"):+ out.append(rcb1.array_part(f"frames/{c}", fr))+ if len(fr):+ out.append(rcb1.array_part(f"last/{c}", fr[-1]))+ out.append(rcb1.array_part(f"extrinsic_cv/{c}", np.stack(self.ext[c]) if self.ext[c] else np.zeros((0, 3, 4))))+ if self.mode in ("last", "frames") and c in self.last_depth:+ out.append(rcb1.array_part(f"last_depth/{c}", self.last_depth[c]))+ if self.mode == "frames" and self.depth[c]:+ out.append(depth_frames_part(f"depth_frames/{c}", np.stack(self.depth[c])))+ if self.mode == "legacy" and self.depth[c]:+ out.append(rcb1.array_part(f"depth/{c}", np.stack(self.depth[c]).astype(np.float16)))+ out.append(rcb1.array_part("proprio", np.stack(self.prop) if self.prop else np.zeros((0, 0), np.float32)))+ st = np.asarray(self.steps, dtype=np.int64)+ out.append(rcb1.array_part("frame_step", st))+ out.append(rcb1.array_part("frame_time_s", st.astype(np.float64) / self.hz))+ return out+++def encode_response(meta: dict, parts: list, max_bytes: int = MAX_RESP) -> bytes:+ """The RCB1 body; over `max_bytes` the per-frame depth goes first, then the raw frames (mp4, last frames, last+ depth, proprio and the per-frame arrays always stay), and meta["degraded"] says what was dropped."""+ body = rcb1.encode(meta, parts)+ dropped = []+ for prefixes in (("depth_frames/", "depth/"), ("frames/",)):+ if len(body) <= max_bytes:+ break+ keep = [p for p in parts if not p[0].startswith(prefixes)]+ if len(keep) < len(parts):+ parts = keep; dropped += [x.rstrip("/") for x in prefixes]+ body = rcb1.encode({**meta, "degraded": f"response over {max_bytes} bytes: {', '.join(dropped)} dropped"}, parts)+ return body+++# ---------------------------------------------------------------- kinematics+def _vec(x, n: int, what: str) -> list:+ a = np.asarray(x, dtype=np.float64).reshape(-1) if x is not None else None+ if a is None or a.size != n or not np.all(np.isfinite(a)):+ raise ValueError(f"{what} must be {n} finite numbers")+ return a.tolist()+++def _pose(x, what: str) -> list:+ p = _vec(x, 7, what)+ nq = math.sqrt(sum(v * v for v in p[3:]))+ if nq < 1e-6:+ raise ValueError(f"{what}: quaternion has zero norm")+ return p[:3] + [v / nq for v in p[3:]]+++def parse_kinematics(body: dict, kin: dict) -> dict:+ """Validate a /kinematics request against spec["kinematics"] (ValueError -> 400). Returns+ {"op": "fk", "q", "links", "base_pose"} or {"op": "ik", "targets": {frame: pose7}, "seed", "base_pose", "tol_pos_m",+ "tol_rot_rad", "max_iters"}; poses are x y z + a unit quaternion in the spec's order; q follows kin["joint_names"]."""+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object")+ op = body.get("op"); n = len(kin["joint_names"])+ base = None+ if body.get("base_pose") is not None:+ if kin.get("frame") != "base":+ raise ValueError("base_pose is only accepted by a mobile robot (spec kinematics.frame == 'base')")+ base = _pose(body["base_pose"], "base_pose")+ if op == "fk":+ links = body.get("links") or list(kin["links"])+ if not isinstance(links, list) or any(l not in kin["links"] for l in links):+ raise ValueError(f"links must be a list of names from spec kinematics.links: {kin['links']}")+ return {"op": "fk", "q": _vec(body.get("q"), n, "q"), "links": links, "base_pose": base}+ if op == "ik":+ tg = body.get("targets")+ if not isinstance(tg, dict) or not tg or any(k not in kin["ik_targets"] for k in tg):+ raise ValueError(f"targets must map frames from spec kinematics.ik_targets {kin['ik_targets']} to poses")+ ik = kin.get("ik", {})+ seed = None if body.get("seed") is None else _vec(body["seed"], n, "seed")+ tol_p = float(body.get("tol_pos_m", ik.get("tol_pos_m", 0.005)))+ tol_r = float(body.get("tol_rot_rad", ik.get("tol_rot_rad", 0.05)))+ it = int(body.get("max_iters", ik.get("max_iters", 200)))+ if not (1e-5 <= tol_p <= 0.5 and 1e-4 <= tol_r <= 3.2 and 1 <= it <= 5000):+ raise ValueError("tol_pos_m in [1e-5, 0.5], tol_rot_rad in [1e-4, 3.2], max_iters in [1, 5000]")+ return {"op": "ik", "targets": {k: _pose(v, f"targets[{k}]") for k, v in tg.items()}, "seed": seed, "base_pose": base,+ "tol_pos_m": tol_p, "tol_rot_rad": tol_r, "max_iters": it}+ raise ValueError("op must be 'fk' or 'ik'")+++def fk_response(poses: dict, frame: str) -> dict:+ return {"ok": True, "op": "fk", "frame": frame, "poses": {k: [float(v) for v in np.asarray(p, dtype=np.float64).reshape(7)] for k, p in poses.items()}}+++def ik_response(q, ok: bool, errors: dict, frame: str, note: str | None = None) -> dict:+ """errors: {frame: (position error m, rotation error rad)} of the returned q (None / non-finite -> null: no solution)."""+ fin = lambda v: float(v) if v is not None and math.isfinite(float(v)) else None # noqa: E731+ out = {"ok": bool(ok), "op": "ik", "frame": frame, "q": None if q is None else [float(v) for v in np.asarray(q).reshape(-1)],+ "error": {k: {"pos_m": fin(e[0]), "rot_rad": fin(e[1])} for k, e in errors.items()}}+ if note:+ out["note"] = note+ return out+++def quat_angle(q1, q2) -> float:+ """Rotation angle (rad) between two unit quaternions of the same order."""+ d = abs(float(np.dot(np.asarray(q1, dtype=np.float64), np.asarray(q2, dtype=np.float64))))+ return 2.0 * math.acos(min(1.0, d))+++# ---------------------------------------------------------------- /spec self-check+FORBIDDEN_KEY = re.compile(r"mask|segment|semantic(?!s$)|instance_?id|bbox|bounding|categor|object|\bobj_|label|mass|friction|"+ r"restitution|inertia|density|damping|stiffness", re.I)+GAIN_PATHS = ("robot_spec.controller",) # joint drive gains (stiffness, damping) are the robot's own, and allowed there+POSITION_KEY = re.compile(r"(?:^|_)(?:pos|position|positions|pose|poses|origin|location|coords?|coordinates|world|translation)(?:_|$)|"+ r"(?:^|_)cent(?:er|re)s?(?:_|$)|(?:^|_)xyz?$|(?:^|_)(?:top|surface|floor|table|plane|height|elevation)?_?z$", re.I)+WORLD_TEXT = re.compile(r"\bworld\s+[xyz]\s*=", re.I)+COORDS = re.compile(r"\(\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*(?:,\s*-?\d+(?:\.\d+)?\s*)?\)")+++def world_text(s: str) -> bool:+ """A text that gives a world coordinate: a pixel-to-world formula, or a coordinate tuple with a decimal point that is+ not the robot's own pose ("robot base at (0, 0, 1.08)" stays)."""+ return bool(WORLD_TEXT.search(s)) or any("." in m.group(0) and not re.search(r"base|robot|origin", s[max(0, m.start() - 40):m.start()], re.I)+ for m in COORDS.finditer(s))+CONVENTIONS = {"static.floor_z": 0.0} # BEHAVIOR: the floor is the plane z = 0 (the world frame's definition)+++def static_positions(obj: Any, path: str = "static") -> list[str]:+ """Paths in /spec static that say WHERE something is (keys naming positions, heights, centres; texts with world+ coordinates). Names, inventories, sizes and colours may stay in static; positions never (docs § Never provided)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}"+ if POSITION_KEY.search(str(k)) and CONVENTIONS.get(p, object()) != v:+ out.append(p)+ else:+ out += static_positions(v, p)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += static_positions(v, f"{path}[{i}]")+ elif isinstance(obj, str) and world_text(obj):+ out.append(path)+ return out+++SPEC_REQUIRED = ("protocol", "protocol_compat", "simulator", "robot", "task_text", "control_hz", "cameras", "default_cameras",+ "action_types", "proprio_layout", "proprio_groups", "static", "world", "budget", "robot_spec", "kinematics", "depth")+++def forbidden_keys(obj: Any, path: str = "", skip: tuple = ()) -> list[str]:+ """Key paths that name something the protocol never provides (key paths in `skip` are not searched)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}" if path else str(k)+ if p in skip:+ continue+ if FORBIDDEN_KEY.search(str(k)) and not (re.search(r"damping|stiffness", str(k), re.I) and p.startswith(GAIN_PATHS)):+ out.append(p)+ out += forbidden_keys(v, p, skip)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += forbidden_keys(v, f"{path}[{i}]", skip)+ return out+++def check_spec(spec: dict) -> None:+ """Raise if /spec is not a complete 2.2 spec or names anything forbidden (run at startup, before binding :8000)."""+ miss = [k for k in SPEC_REQUIRED if k not in spec]+ if miss:+ raise RuntimeError(f"/spec misses {miss}")+ if spec["protocol"] != PROTOCOL:+ raise RuntimeError(f"/spec protocol {spec['protocol']!r} != {PROTOCOL}")+ bad = forbidden_keys(spec, skip=())+ if bad:+ raise RuntimeError(f"/spec names forbidden fields: {bad}")+ pos = static_positions(spec["static"])+ if pos:+ raise RuntimeError(f"/spec static says where things are (never provided): {pos}")+ lay = spec["proprio_layout"]+ if len(set(lay)) != len(lay):+ raise RuntimeError("proprio_layout names are not unique")+ for g in PROPRIO_GROUPS_REQUIRED:+ if g not in spec["proprio_groups"]:+ raise RuntimeError(f"proprio_groups misses {g}")+ for g, (first, n, _meaning) in spec["proprio_groups"].items():+ if not (0 <= first and first + n <= len(lay)):+ raise RuntimeError(f"proprio group {g} [{first}, +{n}) outside the {len(lay)} columns")+ kin = spec["kinematics"]+ for k in ("endpoint", "joint_names", "frame", "quaternion_order", "links", "tcp_frames", "ee_frames", "ik_targets"):+ if k not in kin:+ raise RuntimeError(f"kinematics misses {k}")+ if any(j not in lay for j in kin["joint_names"]):+ raise RuntimeError("kinematics.joint_names must be proprio_layout columns (the measured joint positions)")+ if any(f not in kin["links"] for f in list(kin["tcp_frames"]) + list(kin["ee_frames"]) + list(kin["ik_targets"])):+ raise RuntimeError("kinematics tcp_frames / ee_frames / ik_targets must be listed in kinematics.links")+ if spec["proprio_groups"]["tcp_pose"][1] != 7 * len(kin["tcp_frames"]):+ raise RuntimeError("proprio group tcp_pose must hold 7 columns per kinematics.tcp_frames entry")+ for c, cam in spec["cameras"].items():+ for k in ("rgb", "depth", "mounted", "resolution", "intrinsic_cv", "mount"):+ if k not in cam:+ raise RuntimeError(f"cameras.{c} misses {k}")+ if cam["mount"].get("type") not in ("static", "link"):+ raise RuntimeError(f"cameras.{c}.mount.type must be static|link")+ if any(c not in spec["cameras"] for c in spec["default_cameras"]):+ raise RuntimeError("default_cameras must be cameras")+++# ---------------------------------------------------------------- crash recovery (PROTOCOL §4.7; docs/STANDARD_MODE_2_2.md)+MAX_RESUMES = int(os.environ.get("RCB_MAX_RESUMES", "2"))+STARTUP_TIMEOUT_S = float(os.environ.get("RCB_STARTUP_TIMEOUT_S", "900")) # a task with a slower scene build sets more+MAX_CALL_WALL_S = float(os.environ.get("RCB_MAX_CALL_WALL_S", "900")) # < the client's 1800 s /submit read timeout+RESUME_MAX_DEV_M = float(os.environ.get("RCB_RESUME_MAX_DEV_M", "0.05")) # approx resumes: the gross-divergence guard+ON_SERVICE_ERROR = ("a connection error means the service crashed: it restarts and resumes the SAME episode (never a reset) "+ "in the state after the last call it completed, which you may not have received. Wait until GET /status "+ "answers again (rcb_client: Robot.wait_ready(); resuming replays the episode so far, which can take "+ "minutes in a long episode, and the wall clock keeps running), then check calls and control_steps "+ "before you continue. A 500 means the simulator failed: the episode is over (reason \"error\"). A call "+ "that runs longer than max_call_wall_s seconds stops at the next control step and returns what it "+ "executed (meta.stopped, executed_rows).")+++def _jsonable(v: Any) -> Any:+ if isinstance(v, np.ndarray):+ return v.tolist()+ if isinstance(v, (np.floating, np.integer, np.bool_)):+ return v.item()+ if isinstance(v, (list, tuple)):+ return [_jsonable(x) for x in v]+ if isinstance(v, dict):+ return {str(k): _jsonable(x) for k, x in v.items()}+ return v+++def _peer_closed(sock) -> bool:+ """True when the client of an HTTP request has closed its connection (it gave up on the call): the socket reads as+ end-of-file. A client never sends anything while it waits for the response, so readable means closed."""+ try:+ r, _, _ = select.select([sock], [], [], 0)+ return bool(r) and sock.recv(1, socket.MSG_PEEK) == b""+ except (OSError, ValueError):+ return True+++def _read_json(path: str) -> dict:+ try:+ with open(path) as f:+ d = json.load(f)+ return d if isinstance(d, dict) else {}+ except (OSError, ValueError):+ return {}+++def _write_json(path: str, obj: dict) -> None:+ tmp = f"{path}.{os.getpid()}.tmp"+ with open(tmp, "w") as f:+ json.dump(obj, f)+ os.replace(tmp, path)+++def final_verdict(data: str) -> dict | None:+ """final.json if it already holds a verdict that nothing may overwrite: the grading result (finalized, with+ `deterministic`) or the end of an episode the service gave up after crashes (`gave_up`)."""+ fin = _read_json(os.path.join(data, "final.json"))+ if fin.get("finalized") and (fin.get("gave_up") or fin.get("deterministic") is not None):+ return fin+ return None+++class Episode:+ """Crash-safe episode bookkeeping, the same rules as the RoboTwin and MuJoCo services (PROTOCOL §4.7):++ - startup(): before the scene is built. One line in startups.jsonl; a back-off of min(120, 20 (n - 1)) s when the+ earlier starts never began an episode (they crashed while building, e.g. GPU memory taken by other trials); the+ startup watchdog (faulthandler, a C thread: it fires even when a native scene build holds the GIL) dumps every+ thread's traceback and exits 1 after RCB_STARTUP_TIMEOUT_S, so compose restarts the build. Until begin() a SIGUSR1+ (the collect hook's "the agent phase is over") is only remembered.+ - journal(row): every executed control step (the exact row given to the simulator's step) goes to journal.f64.+ - checkpoint(): after every completed call (the HTTP layer calls it): the journal is flushed, then the call's+ checkpoint is logged in episode.jsonl (rows, control steps, state hash, the robot's proprio row, `persist` keys).+ - begin(): a fresh episode, or after a crash (run.sh exits non-zero, compose restarts the container, `restart:+ on-failure:N`) the SAME episode resumed: the journal is replayed up to the last checkpoint, the journal truncated+ there (the call that was in flight is lost as a whole: its caller got an error, not a result), the state hash+ compared, the service's counters restored; the wall clock keeps running from the first start.+ - Resume check, by the simulator's determinism class: `exact` (bit-exact in a fresh process): the hash must match,+ else the episode ends `resume_failed` (infra_error). `approx` (a simulator declared nondeterministic): a+ mismatch is recorded (resume_state_mismatch, and the robot's deviation from its checkpointed proprio: joint_pos and+ tcp_pose) and the episode continues, unless a TCP is more than RCB_RESUME_MAX_DEV_M from where it was+ (resume_failed, infra_error). The verdict never comes from the live state but from fresh replays of the complete+ recorded trajectory, so continuing cannot raise a score.+ - More than RCB_MAX_RESUMES crashes end the episode: `sim_crashed_on_call` if every crash happened while a call was+ being served (the agent's failure), else `sim_crashed` (infra_error = 1). A verdict already on disk is never+ overwritten; the service then idles with its PID file for the collect hook.+ - Per call, two bounds keep one call from holding the single-threaded service: a call that runs longer than+ max_call_wall_s, or whose client has hung up, stops at the next control step and returns what it executed+ (journal() returns True; meta.stopped says why). Neither bounds the episode: the wall clock is its only budget."""++ def __init__(self, data: str, dim: int, resume: str = "exact", persist: tuple = ()):+ if resume not in ("exact", "approx"):+ raise ValueError("resume must be 'exact' or 'approx'")+ self.data, self.dim, self.resume_class, self.persist = data, int(dim), resume, tuple(persist)+ os.makedirs(data, exist_ok=True)+ p = lambda n: os.path.join(data, n) # noqa: E731+ self.f_events, self.f_journal, self.f_final, self.f_pid, self.f_startups = (+ p("episode.jsonl"), p("journal.f64"), p("final.json"), p("server.pid"), p("startups.jsonl"))+ self.rows = 0 # control steps executed in this episode (journaled)+ self.max_call_wall_s = MAX_CALL_WALL_S+ self.n_startups = 0; self.resumes = 0; self.mismatches = 0; self.max_tcp_dev = 0.0; self.max_joint_dev = 0.0+ self._jf = None; self._call: dict | None = None; self._ids = 0; self._ck: tuple | None = None+ self._on_end: Callable | None = None; self._end_pending = False++ # ---- startup+ def startup(self) -> None:+ signal.signal(signal.SIGUSR1, self._usr1)+ try:+ os.remove(self.f_pid) # a PID file from before a crash would send the collect hook to a dead process+ except OSError:+ pass+ with open(self.f_startups, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid()}) + "\n")+ with open(self.f_startups) as f:+ self.n_startups = sum(1 for line in f if line.strip())+ if self.n_startups > 1 and not any(e.get("ev") == "start" for e in self.events()):+ time.sleep(min(120.0, 20.0 * (self.n_startups - 1)))+ faulthandler.dump_traceback_later(STARTUP_TIMEOUT_S, exit=True)++ def scene_built(self) -> None:+ faulthandler.cancel_dump_traceback_later() # the scene exists: a resume replay may take long, it is not a hang++ def _usr1(self, *_):+ if self._on_end is None:+ self._end_pending = True+ else:+ threading.Thread(target=self._on_end, daemon=True).start()++ # ---- the record+ def log(self, ev: dict) -> None:+ with open(self.f_events, "a") as f:+ f.write(json.dumps(_jsonable({"ts": time.time(), **ev})) + "\n")++ def events(self) -> list:+ out = []+ try:+ with open(self.f_events) as f:+ for line in f:+ try:+ out.append(json.loads(line))+ except ValueError: # a line cut by a crash+ pass+ except OSError:+ pass+ return [e for e in out if isinstance(e, dict)]++ def journal(self, row) -> bool:+ """One executed control step. True: the call in progress must stop at this step boundary (meta.stopped)."""+ a = np.asarray(row, dtype=np.float64).reshape(-1)+ if a.size != self.dim:+ raise ValueError(f"journal rows have {self.dim} entries, got {a.size}")+ if self._jf is None:+ self._jf = open(self.f_journal, "ab")+ self._jf.write(a.tobytes()); self.rows += 1+ c = self._call+ if c is None:+ return False+ if c["stopped"] is None:+ now = time.monotonic()+ if now - c["t0"] > self.max_call_wall_s:+ c["stopped"] = "max_call_wall_s"+ elif c["sock"] is not None and now - c["polled"] >= 0.2:+ c["polled"] = now+ if _peer_closed(c["sock"]):+ c["stopped"] = "client_disconnected"+ return c["stopped"] is not None++ @property+ def stopping(self) -> bool:+ """The call in progress must stop (adapters whose loops test E["done"] test this too)."""+ return bool(self._call and self._call["stopped"])++ @property+ def stop_reason(self) -> str | None:+ return self._call["stopped"] if self._call else None++ def call_begin(self, path: str, sock=None) -> int:+ self._ids += 1+ if path != "/kinematics":+ self._call = {"id": self._ids, "t0": time.monotonic(), "sock": sock, "polled": 0.0, "stopped": None}+ self.log({"ev": "call_begin", "id": self._ids, "path": path})+ return self._ids++ def call_end(self, cid: int, path: str, **extra) -> None:+ self.log({"ev": "call_end", "id": cid, "path": path, **extra})+ if path != "/kinematics":+ self._call = None++ def checkpoint(self, state: dict, state_sha: Callable | None, proprio: Callable | None) -> None:+ if self._jf is not None:+ self._jf.flush() # the rows reach the file before the checkpoint that counts them+ if self._ck is not None and self._ck[0] == self.rows:+ sha, pr = self._ck[1], self._ck[2] # no physics since the last checkpoint+ else:+ try:+ sha = state_sha() if state_sha else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); sha = None+ pr = self._proprio_row(proprio)+ self._ck = (self.rows, sha, pr)+ self.log({"ev": "checkpoint", "call": int(state.get("calls") or 0), "step": int(state.get("step") or 0),+ "control_steps": self.rows, "success": bool(state.get("success")), "done": bool(state.get("done")),+ "reason": state.get("reason"), "state_sha": sha, "proprio": pr,+ **({"persist": {k: state.get(k) for k in self.persist}} if self.persist else {})})++ @staticmethod+ def _proprio_row(proprio: Callable | None) -> list | None:+ try:+ return [round(float(v), 6) for v in np.asarray(proprio(), dtype=np.float64).reshape(-1)] if proprio else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); return None++ def final_fields(self) -> dict:+ """Crash-recovery fields for final.json / episode.json (all numeric, for reward.json)."""+ return {"sim_startups": self.n_startups, "resumes": self.resumes, "resume_state_mismatch": int(self.mismatches > 0),+ "resume_max_tcp_dev_m": round(self.max_tcp_dev, 6), "resume_max_joint_dev": round(self.max_joint_dev, 6)}++ # ---- start or resume+ def begin(self, *, state: dict, step: Callable, state_sha: Callable, proprio: Callable, spec: dict,+ start_event: dict | None = None, on_end: Callable | None = None) -> bool:+ """Start the episode, or resume it after a crash. `step(row)` executes one journaled row on the simulator (the+ recorder on, no rendering needed); `on_end` is what the collect hook's SIGUSR1 runs (in a thread). Returns True+ if the episode was resumed."""+ try: # a line cut by the crash must not swallow the next record+ with open(self.f_events, "rb+") as f:+ f.seek(0, os.SEEK_END)+ if f.tell():+ f.seek(-1, os.SEEK_END)+ if f.read(1) != b"\n":+ f.write(b"\n")+ except OSError:+ pass+ ev = self.events()+ starts = [e for e in ev if e.get("ev") == "start"]+ if not starts:+ try:+ os.remove(self.f_journal)+ except OSError:+ pass+ sha = state_sha()+ self._ck = (0, sha, self._proprio_row(proprio))+ self.log({**(start_event or {}), "ev": "start", "state_sha": sha, "protocol": PROTOCOL, "resume": self.resume_class,+ "journal_dim": self.dim})+ state["t0"] = time.time()+ self._arm(on_end)+ return False+ tries = [e for e in ev if e.get("ev") == "resuming"] # earlier resumes (a crash during one counts too)+ resumed = [e for e in ev if e.get("ev") == "resumed"]+ self.resumes = len(tries) # the record so far, also for a give-up below (final_fields)+ self.mismatches = sum(1 for e in resumed if e.get("exact") is False)+ self.max_tcp_dev = max([float(e.get("tcp_dev_m") or 0) for e in resumed] + [0.0])+ self.max_joint_dev = max([float(e.get("joint_dev") or 0) for e in resumed] + [0.0])+ if final_verdict(self.data):+ self.give_up("restarted after finalize", infra=False)+ k = max(i for i, e in enumerate(ev) if e.get("ev") in ("start", "resuming", "resumed"))+ tail = ev[k + 1:]+ in_call = bool({e.get("id") for e in tail if e.get("ev") == "call_begin"} - {e.get("id") for e in tail if e.get("ev") == "call_end"})+ if len(tries) >= MAX_RESUMES:+ agent = sum(1 for e in tries if e.get("crashed_in_call")) + int(in_call) == len(tries) + 1+ self.give_up("sim_crashed_on_call" if agent else "sim_crashed", infra=not agent)+ self.log({"ev": "resuming", "attempt": len(tries) + 1, "crashed_in_call": in_call,+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self.resumes = len(tries) + 1 # this attempt counts, whether or not it succeeds+ cps = [e for e in ev if e.get("ev") == "checkpoint"]+ last = cps[-1] if cps else {"call": 0, "step": 0, "control_steps": 0, "success": False, "state_sha": starts[0].get("state_sha")}+ n = int(last.get("control_steps") or 0)+ try:+ R = np.fromfile(self.f_journal, dtype=np.float64)+ except (OSError, ValueError):+ R = np.zeros(0)+ if R.size < n * self.dim:+ self.give_up("resume_failed: journal shorter than the log", infra=True)+ R = R[: n * self.dim].reshape(n, self.dim)+ t = time.time()+ for row in R:+ step(row)+ replay_s = time.time() - t+ R.tofile(self.f_journal) # drop the rows of the call that was in flight+ self.rows = n+ sha = state_sha(); want = last.get("state_sha")+ exact = None if want is None else sha == want+ dev = self._deviation(last.get("proprio"), proprio, spec)+ if exact is False: # recorded first: a give-up below reports it too+ self.mismatches += 1+ self.max_tcp_dev = max(self.max_tcp_dev, dev.get("tcp_m") or 0.0)+ self.max_joint_dev = max(self.max_joint_dev, dev.get("joint") or 0.0)+ if self.resume_class == "exact":+ self.give_up("resume_failed: replayed state differs from the logged one", infra=True)+ if dev.get("tcp_m") is not None and dev["tcp_m"] > RESUME_MAX_DEV_M:+ self.give_up(f"resume_failed: a replayed TCP is {dev['tcp_m']:.3f} m from its checkpoint (> {RESUME_MAX_DEV_M} m)", infra=True)+ state["calls"] = int(last.get("call") or 0); state["step"] = int(last.get("step") or 0)+ if "success" in state:+ state["success"] = bool(last.get("success"))+ for key, v in (last.get("persist") or {}).items():+ state[key] = v+ state["t0"] = float(starts[0]["ts"])+ ended = [e for e in ev if e.get("ev") == "end" and int(e.get("control_steps") or 0) <= n] # not the lost call's+ if ended:+ state["done"] = True; state["reason"] = ended[-1].get("reason"); state["t_end"] = float(ended[-1]["ts"])+ state["episode_control_steps"] = int(ended[-1].get("control_steps") or n)+ self._ck = (n, sha, self._proprio_row(proprio)) # the replayed state's row (it may differ under approx)+ self.log({"ev": "resumed", "attempt": self.resumes, "control_steps": n, "calls": state["calls"], "state_sha": sha,+ "logged_sha": want, "exact": exact, "class": self.resume_class, "tcp_dev_m": dev.get("tcp_m"),+ "joint_dev": dev.get("joint"), "crashed_in_call": in_call, "replay_s": round(replay_s, 1),+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self._arm(on_end)+ return True++ @staticmethod+ def _deviation(ref, proprio: Callable, spec: dict) -> dict:+ """The replayed robot against its checkpointed proprio row: max |joint_pos| difference (rad or m) and the largest+ TCP position error (m) over the tcp_pose frames (7 columns each: x y z + quaternion)."""+ if ref is None:+ return {}+ try:+ now = np.asarray(proprio(), dtype=np.float64).reshape(-1); ref = np.asarray(ref, dtype=np.float64).reshape(-1)+ except Exception: # noqa: BLE001+ return {}+ if now.shape != ref.shape:+ return {}+ g, out = spec.get("proprio_groups") or {}, {}+ if "joint_pos" in g:+ f, n = int(g["joint_pos"][0]), int(g["joint_pos"][1])+ out["joint"] = float(np.max(np.abs(now[f:f + n] - ref[f:f + n]))) if n else 0.0+ if "tcp_pose" in g:+ f, n = int(g["tcp_pose"][0]), int(g["tcp_pose"][1]); m = n // 7+ d = (now[f:f + 7 * m] - ref[f:f + 7 * m]).reshape(m, 7)[:, :3]+ out["tcp_m"] = float(np.max(np.linalg.norm(d, axis=1))) if m else 0.0+ return out++ def _arm(self, on_end: Callable | None) -> None:+ self._on_end = on_end+ signal.signal(signal.SIGUSR1, self._usr1)+ if on_end is not None and self._end_pending:+ self._end_pending = False+ threading.Thread(target=on_end, daemon=True).start()++ def give_up(self, reason: str, infra: bool) -> None:+ """End the trial's episode without a new one (never a reset): log it, write the verdict unless one is on disk,+ leave the PID file for the collect hook, and idle until the container is removed."""+ faulthandler.cancel_dump_traceback_later()+ self.log({"ev": "restart_refused", "reason": reason})+ if not final_verdict(self.data):+ fin = _read_json(self.f_final)+ fin.update({"success": False, "done": True, "reason": reason, "finalized": True, "gave_up": True, "protocol": PROTOCOL,+ **self.final_fields(), **({"infra_error": 1} if infra else {})})+ _write_json(self.f_final, fin)+ with open(self.f_pid, "w") as f:+ f.write(str(os.getpid()))+ signal.signal(signal.SIGUSR1, lambda *_: None)+ print(f"[{PROTOCOL}] restart refused: {reason}", flush=True)+ while True:+ time.sleep(3600)+++# ---------------------------------------------------------------- the HTTP layer+class Service:+ """What a sim service hands to serve(): spec (dict), lock, state (the service's E dict: done, reason, exiting, error),+ submit(meta, actions) and observe(meta) -> (meta_out, rcb1 parts), kinematics(req) -> dict, status() -> dict,+ on_submit_error(exc) (a simulator error in /submit or /observe: it ends the episode, reason "error"), log(event dict),+ and for crash recovery the Episode with the simulator's state_sha() and proprio row()."""++ def __init__(self, *, spec: dict, lock, state: dict, submit: Callable, observe: Callable, kinematics: Callable,+ status: Callable, on_submit_error: Callable, log: Callable, max_resp: int = MAX_RESP,+ episode: Episode | None = None, state_sha: Callable | None = None, proprio: Callable | None = None):+ self.spec, self.lock, self.state, self.submit, self.observe = spec, lock, state, submit, observe+ self.kinematics, self.status, self.on_submit_error, self.log, self.max_resp = kinematics, status, on_submit_error, log, max_resp+ self.episode, self.state_sha, self.proprio = episode, state_sha, proprio+ self.kin_calls = 0+++def make_handler(svc: Service):+ class H(BaseHTTPRequestHandler):+ def _send(self, code: int, ctype: str, body: bytes) -> None:+ try:+ self.send_response(code); self.send_header("Content-Type", ctype); self.send_header("Content-Length", str(len(body)))+ self.end_headers(); self.wfile.write(body)+ except (BrokenPipeError, ConnectionResetError): # the client hung up (its call was abandoned)+ pass++ def _json(self, code: int, obj: dict) -> None:+ self._send(code, "application/json", json.dumps(obj).encode())++ def _rcb1(self, meta: dict, parts: list) -> None:+ self._send(200, "application/x-rcb1", encode_response(meta, parts, svc.max_resp))++ def log_message(self, *a):+ pass++ def _body(self):+ try:+ n = int(self.headers.get("Content-Length", 0))+ except ValueError:+ raise ValueError("bad Content-Length")+ if n > MAX_BODY:+ raise ValueError("request too large")+ raw = self.rfile.read(n) if n else b""+ if raw[:4] == rcb1.MAGIC:+ return rcb1.decode(raw)+ body = json.loads(raw or b"{}")+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object or an RCB1 frame")+ return body, {}++ def do_GET(self):+ if self.path == "/spec":+ return self._json(200, svc.spec)+ if self.path == "/status":+ st = svc.status()+ return self._json(200, {**st, "resumes": svc.episode.resumes} if svc.episode else st)+ return self._json(404, {"error": "no such endpoint"})++ def do_POST(self):+ if self.path not in ("/submit", "/observe", "/kinematics"):+ return self._json(404, {"error": "no such endpoint"})+ try:+ meta, parts = self._body()+ except Exception as exc: # noqa: BLE001+ return self._json(413 if "too large" in str(exc) else 400, {"error": str(exc)[:200]})+ E, ep = svc.state, svc.episode+ if self.path == "/kinematics": # stateless: never steps physics, never waits for the episode lock+ cid = ep.call_begin(self.path) if ep else 0+ try:+ req = parse_kinematics(meta, svc.spec["kinematics"])+ out = svc.kinematics(req); svc.kin_calls += 1+ except ValueError as exc:+ return self._json(400, {"error": str(exc)[:300]})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); return self._json(500, {"error": "kinematics error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ ep.call_end(cid, self.path)+ return self._json(200, out)+ with svc.lock:+ if E.get("exiting") or (self.path == "/submit" and E.get("done")):+ return self._json(409, {"error": "episode finished", "reason": E.get("reason")})+ cid = ep.call_begin(self.path, self.connection) if ep else 0+ rows0 = ep.rows if ep else 0+ out = blobs = err = None; stopped = None+ try:+ if self.path == "/submit":+ A = np.asarray(parts["actions"]["data"] if "actions" in parts else meta.get("actions", []), dtype=np.float64)+ out, blobs = svc.submit(meta, A)+ else:+ out, blobs = svc.observe(meta)+ except ValueError as exc:+ err = (400, {"error": str(exc)})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); E["error"] = repr(exc); svc.log({"ev": "error", "path": self.path, "error": repr(exc)})+ try:+ svc.on_submit_error(exc) # PROTOCOL §4.6: a simulator error ends the episode (reason "error")+ except Exception: # noqa: BLE001+ traceback.print_exc()+ err = (500, {"error": "simulator error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ stopped = ep.stop_reason+ if err is None or ep.rows != rows0:+ try:+ ep.checkpoint(E, svc.state_sha, svc.proprio)+ except Exception: # noqa: BLE001+ traceback.print_exc()+ ep.call_end(cid, self.path, **({"stopped": stopped} if stopped else {}))+ if err is not None:+ return self._json(*err)+ return self._rcb1({**out, "stopped": stopped}, blobs)+ return H+++def serve(svc: Service, port: int = 8000) -> None:+ """Check the spec, then serve forever (one request at a time, as every 2.x service)."""+ svc.spec.setdefault("on_service_error", ON_SERVICE_ERROR)+ if svc.episode is not None:+ svc.spec.setdefault("max_call_wall_s", svc.episode.max_call_wall_s)+ check_spec(svc.spec)+ HTTPServer(("0.0.0.0", port), make_handler(svc)).serve_forever()+++# ---------------------------------------------------------------- the collect hook's first half+def _alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ try: # a zombie (exited, not yet reaped) counts as gone+ with open(f"/proc/{pid}/stat") as f:+ return f.read().rsplit(")", 1)[-1].split()[0] != "Z"+ except OSError:+ return True+++def end_episode(data: str, timeout: float = 21600.0, wait_key: str | None = None, resend_s: float = 30.0) -> int:+ """Tell the service that the agent phase is over and wait until it has ended the episode. The service may be+ resuming after a crash (no PID file until it is ready again), so there is no fixed start-up wait, and a signal goes+ only to the process that wrote the newest line of startups.jsonl (its SIGUSR1 handler is installed by then).+ Returns 2: final.json already holds the verdict (the service gave up after crashes, or graded in-process; with+ `wait_key`, also waits for that final.json key, e.g. video_done): keep it, run no replays.+ Returns 0: the service dumped the episode (episode.json) and exited: the hook replays it next.+ Returns 1: timed out."""+ t0, sent = time.time(), 0.0+ f_pid, f_dump, f_starts = (os.path.join(data, n) for n in ("server.pid", "episode.json", "startups.jsonl"))+ while time.time() - t0 < timeout:+ fin = final_verdict(data)+ if fin is not None:+ if not wait_key or fin.get(wait_key) or fin.get("gave_up"):+ return 2+ time.sleep(2); continue+ try:+ with open(f_pid) as f:+ pid = int(f.read().strip())+ except (OSError, ValueError):+ pid = None+ try:+ with open(f_starts) as f:+ cur = json.loads([x for x in f if x.strip()][-1]).get("pid")+ except (OSError, ValueError, IndexError):+ cur = None # a service without Episode.startup(): signal what the PID file names+ if pid is not None and (cur is None or pid == cur):+ if not _alive(pid):+ if os.path.exists(f_dump):+ return 0+ elif time.time() - sent >= resend_s:+ try:+ os.kill(pid, signal.SIGUSR1); sent = time.time()+ except OSError:+ pass+ time.sleep(2)+ return 1+++if __name__ == "__main__":+ a = sys.argv[1:]+ if len(a) >= 2 and a[0] == "end":+ wk = a[a.index("--wait-key") + 1] if "--wait-key" in a else None+ to = float(a[a.index("--timeout") + 1]) if "--timeout" in a else 21600.0+ rc = end_episode(a[1], timeout=to, wait_key=wk)+ print({0: "[collect] episode dumped by the service", 1: "[collect] timed out waiting for the service",+ 2: "[collect] final.json already holds the verdict"}[rc], flush=True)+ sys.exit(rc)+ if len(a) == 2 and a[0] == "final-verdict":+ fin = final_verdict(a[1])+ print(json.dumps(fin) if fin else "no final verdict")+ sys.exit(0 if fin else 1)+ print("usage: rcb_limited.py end <data dir> [--wait-key KEY] [--timeout S] | final-verdict <data dir>")+ sys.exit(2)diff --git a/tasks/mujoco_playground_spot_getup-standard/environment/sim/rcb_quadruped.py b/tasks/mujoco_playground_spot_getup-standard/environment/sim/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/environment/sim/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_spot_getup-standard/environment/sim/run.sh b/tasks/mujoco_playground_spot_getup-standard/environment/sim/run.shnew file mode 100755index 0000000000..49d4d045d4--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/environment/sim/run.sh@@ -0,0 +1,22 @@+#!/bin/sh+# eai-standard/2.2 sidecar entrypoint: PID 1 of the `sim` container, shared by every 2.2 service+# (scripts/eai_standard/run.sh, copied unchanged into each standard task's environment/sim/).+# - The service crashed (a non-zero exit: an exception, a signal, the startup watchdog): exit with its code, so compose+# restarts the container (`restart: on-failure:6`) and the service resumes the same episode from its journal+# (rcb_limited.Episode). The container keeps its /data (or /out) across the restart.+# - The service exited cleanly (0: it dumped its episode on the collect hook's SIGUSR1 and released the simulator): keep+# the container up for the collect hook's fresh-process replays. If the service were PID 1 itself, that exit would+# stop the container and kill the hook with it (Harbor reports exit 137).+# - Everything the service prints also goes to $RCB_DATA/server.log (an artifact: Harbor keeps no sidecar output, and a+# simulator that dies while it loads leaves no other trace).+DATA="${RCB_DATA:-/data}"+mkdir -p "$DATA"+rm -f "$DATA/.service_rc"+{ python -u "${RCB_SERVER:-/srv/server.py}" 2>&1; echo "$?" > "$DATA/.service_rc"; } | tee -a "$DATA/server.log"+rc="$(cat "$DATA/.service_rc" 2>/dev/null)"; rc="${rc:-1}"+if [ "$rc" != 0 ]; then+ echo "[sim] service exited ($rc): leaving, so compose restarts the container (the service resumes the episode if one began)" | tee -a "$DATA/server.log"+ exit "$rc"+fi+echo "[sim] service exited (0); holding the container open for the collect hook" | tee -a "$DATA/server.log"+while true; do sleep 3600; donediff --git a/tasks/mujoco_playground_spot_getup-standard/environment/sim/server.py b/tasks/mujoco_playground_spot_getup-standard/environment/sim/server.pynew file mode 100644index 0000000000..b0c774b183--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/environment/sim/server.py@@ -0,0 +1,478 @@+"""eai-standard/2.2 sim service for MuJoCo Playground's quadruped tasks (docs/STANDARD_MODE_2_2.md): the adapter of the+shared layer rcb_limited.py; the simulator is rcb_quadruped.Session (plain MuJoCo on the CPU).+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to+/data/episode.jsonl.++The episode is the frozen instance's: one control step = 1/50 s. A joystick episode ends after the whole command schedule+(the horizon), when the robot meets Playground's termination rule (it falls over: a failure), when the agent submits+`done`, or when its time is over; success = the task's check on the steps executed. A getup episode ends the moment the+check holds (success), after the horizon, on `done` or on timeout.++Crash recovery (rcb_limited.Episode, resume class `exact`: MuJoCo on the CPU repeats bit for bit in a fresh process):+every executed row is journaled; after a crash the service rebuilds the episode and replays the journal. When the+episode ends the service writes /data/trajectory.npz + /data/episode.json; the collect hook (finalize.sh) makes it exit+and replays the trajectory in two fresh processes."""++import math+import os+import sys+import threading+import time+import traceback++import numpy as np++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import rcb_limited as L # noqa: E402++DATA = os.environ.get("RCB_DATA", "/data")+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.json"))+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "3600"))+MAX_CHUNK_S = float(os.environ.get("RCB_MAX_CHUNK_S", "10"))+MAX_WATCH_S = float(os.environ.get("RCB_MAX_WATCH_S", "30"))+CAM_W, CAM_H = 320, 240+LOCK = threading.Lock()+PID_FILE = os.path.join(DATA, "server.pid")+E = {"ready": False, "step": 0, "calls": 0, "done": False, "reason": None, "success": False, "t0": time.time(), "error": None}++os.environ["RCB_SESSION_LOG"] = ""+os.environ["RCB_AGENT_TRACE_DIR"] = ""+import rcb_quadruped as Q # noqa: E402 (first: it picks the rendering backend before mujoco loads)+import mujoco # noqa: E402++EP = L.Episode(DATA, dim=Q.N, resume="exact")+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()+S = Q.Session(INSTANCE)+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz+DT = S.control_dt # one control step of simulated time (Barkour: 10 ms, as Playground steps it)+CTRL_HZ = 1.0 / DT+SUBSTEPS = S.substeps+M = S.model+CAMS = list(S.cameras)+FEET = S.robot["feet"]+LIMITS = np.stack([S.lower, S.upper], axis=1)+GROUPS = [+ ("joint_pos", S.joint_names, "measured joint positions (rad), in the action's order"),+ ("joint_vel", [f"{j}_vel" for j in S.joint_names], "measured joint velocities (rad/s)"),+ ("joint_effort", [f"{j}_effort" for j in S.joint_names], "actuator torques of those joints (N m)"),+ ("gripper_opening", [], "none (no gripper)"),+ ("tcp_pose", [], "none (no gripper)"),+ ("imu_gyro", ["gyro_x", "gyro_y", "gyro_z"], "angular velocity of the trunk, IMU frame (rad/s)"),+ ("imu_accelerometer", ["acc_x", "acc_y", "acc_z"], "specific force at the IMU, IMU frame (m/s^2; +9.81 up at rest)"),+ ("imu_gravity", ["gravity_x", "gravity_y", "gravity_z"], "unit vector of gravity's direction in the IMU frame "+ "([0, 0, -1] when the trunk is level)"),+ ("imu_linvel", ["linvel_x", "linvel_y", "linvel_z"], "linear velocity of the trunk at the IMU, IMU frame (m/s; the "+ "IMU's velocimeter, what a state estimator gives)"),+ ("foot_contact", [f"{f}_contact" for f in FEET], "1 when the foot touches the ground, else 0"),+]+PROPRIO_LAYOUT = [n for _, names, _ in GROUPS for n in names]+PROPRIO_GROUPS, _i = {}, 0+for _g, _names, _meaning in GROUPS:+ PROPRIO_GROUPS[_g] = [_i, len(_names), _meaning]+ _i += len(_names)+++# ------------------------------------------------------------------------------------------------- cameras+def _intrinsic(cam: str) -> list:+ fovy = math.radians(float(M.cam_fovy[M.camera(cam).id]))+ f = 0.5 * CAM_H / math.tan(fovy / 2)+ return [[f, 0.0, CAM_W / 2], [0.0, f, CAM_H / 2], [0.0, 0.0, 1.0]]+++def camera_info(cam: str) -> dict:+ """World -> camera (OpenCV axes) and camera -> world (OpenGL axes) at the current state."""+ i = M.camera(cam).id+ R_gl = S.data.cam_xmat[i].reshape(3, 3) # camera axes (OpenGL: x right, y up, z back) in the world+ p = S.data.cam_xpos[i].copy()+ R_cv = R_gl @ np.diag([1.0, -1.0, -1.0])+ ext = np.zeros((3, 4))+ ext[:, :3] = R_cv.T+ ext[:, 3] = -R_cv.T @ p+ c2w = np.eye(4)+ c2w[:3, :3] = R_gl+ c2w[:3, 3] = p+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": ext.tolist(), "cam2world_gl": c2w.tolist(),+ "image_size": [CAM_W, CAM_H]}+++# ------------------------------------------------------------------------------------------------- kinematics+KD = mujoco.MjData(M) # kinematics only: the trunk at the origin, level; never stepped+_FOOT = {f: M.site(f).id for f in FEET}+_LEG_DOF = {f: [6 + 3 * k + j for j in range(3)] for k, f in enumerate(FEET)} # actuator order = leg order = FEET+++def _fk_kd(q) -> None:+ KD.qpos[:] = 0.0+ KD.qpos[3] = 1.0+ KD.qpos[7:] = q+ mujoco.mj_kinematics(M, KD)+++def _foot_pose(f: str) -> list:+ quat = np.zeros(4)+ mujoco.mju_mat2Quat(quat, KD.site_xmat[_FOOT[f]])+ return [*KD.site_xpos[_FOOT[f]].tolist(), *quat.tolist()]+++def do_kinematics(req: dict) -> dict:+ """Feet in the trunk frame (the trunk body's origin and axes; x forward, y left, z up). IK solves positions only, one+ leg (3 joints) per foot target, damped least squares within the joint ranges; a foot's orientation is ignored."""+ if req["op"] == "fk":+ _fk_kd(np.asarray(req["q"]))+ return L.fk_response({f: _foot_pose(f) for f in req["links"]}, "trunk")+ q = np.array(req["seed"] if req["seed"] is not None else S.data.qpos[7:], dtype=np.float64)+ errors = {}+ jac = np.zeros((3, M.nv))+ for f, pose in req["targets"].items():+ tgt = np.asarray(pose[:3])+ idx = _LEG_DOF[f]+ for _ in range(req["max_iters"]):+ _fk_kd(q)+ err = tgt - KD.site_xpos[_FOOT[f]]+ if np.linalg.norm(err) < req["tol_pos_m"]:+ break+ mujoco.mj_jacSite(M, KD, jac, None, _FOOT[f])+ J = jac[:, idx]+ dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(3), err)+ q[[i - 6 for i in idx]] = np.clip(q[[i - 6 for i in idx]] + dq, S.lower[[i - 6 for i in idx]],+ S.upper[[i - 6 for i in idx]])+ _fk_kd(q)+ errors[f] = (float(np.linalg.norm(tgt - KD.site_xpos[_FOOT[f]])), 0.0)+ ok = all(e[0] <= req["tol_pos_m"] for e in errors.values())+ return L.ik_response(q, ok, errors, "trunk", note="feet: position only (a foot is a sphere; its orientation is ignored)")+++# ------------------------------------------------------------------------------------------------- spec+def schedule_text() -> list:+ if S.commands is None:+ return []+ return [{"from_s": round(int(c["start_step"]) * DT, 2), "vx_mps": round(c["vx"], 4), "vy_mps": round(c["vy"], 4),+ "wz_radps": round(c["wz"], 4)} for c in S.inst["commands"]]+++TASK_EPISODE = {+ "joystick": f"one episode, no reset: it ends after {S.horizon} control steps (the {S.horizon * DT:g} s command "+ f"schedule), when the robot meets its termination rule ({S.spec.get('term_text')}: a failure), when you "+ "submit `done`, or when your time is over",+ "getup": f"one episode, no reset: it ends the moment the robot has stood upright for {Q.HOLD_STEPS} control steps in a "+ f"row (success), after {S.horizon} control steps, when you submit `done`, or when your time is over",+ "stand_on_two": f"one episode, no reset: it ends the moment the pose has been held for {Q.POSE_HOLD_STEPS} control steps "+ "in a row (success), when the robot meets the termination rule (a failure: its trunk's up axis below "+ f"-0.25, or {'a leg' if S.spec.get('hind_leg_contact') else 'a front leg'}'s thigh, calf or hip on the "+ f"floor), after {S.horizon} control steps, when you "+ "submit `done`, or when your time is over",+}[S.kind]+_ctl = {"type": "joint position actuators (PD)", "kp_nm_per_rad": float(M.actuator_gainprm[0, 0]),+ "kd_nms_per_rad": float(M.dof_damping[6] - M.actuator_biasprm[0, 2])}+SPEC = {+ "protocol": L.PROTOCOL,+ "protocol_compat": list(L.COMPAT),+ "simulator": "MuJoCo 3.3.7 (MuJoCo Playground's scene, plain MuJoCo on the CPU)",+ "robot": S.robot["name"],+ "task_text": S.inst["text"],+ "control_hz": CTRL_HZ,+ "physics_substeps": SUBSTEPS,+ "max_chunk_s": MAX_CHUNK_S,+ "max_watch_s": MAX_WATCH_S,+ "cameras": {c: {"rgb": True, "depth": True, "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),+ **({"mounted": "follows the robot", "mount": {"type": "link", "link": S.robot["root"], "note":+ "follows the robot's centre of mass at a fixed offset; it does not turn with the robot"}}+ if int(M.cam_mode[M.camera(c).id]) != 0 else+ {"mounted": "on the robot's head", "mount": {"type": "link", "link": M.body(M.cam_bodyid[M.camera(c).id]).name+ or S.robot["root"], "note": "fixed to the robot: moves and turns with it"}})}+ for c in CAMS},+ "default_cameras": ["track"],+ "action_types": {+ "joint_position": {+ "dim": Q.N,+ "layout": S.joint_names,+ "limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "units": "rad",+ "semantics": "absolute targets of the 12 joint position actuators, one per control step (1/50 s); rows `dt` "+ "apart (a multiple of the control period, at most 0.5 s), `hold` or `linear` between rows; values "+ "outside the limits are clipped and reported",+ },+ "done": {"dim": 0, "layout": [], "semantics": 'ends the episode now, in the current state (no physics); r.submit("done", [])'},+ "not_yet": ["joint_velocity", "joint_torque", "joint_delta"],+ },+ "proprio_layout": PROPRIO_LAYOUT,+ "proprio_groups": PROPRIO_GROUPS,+ "static": {},+ "world": {"frame": "z up; the robot starts where the episode puts it (no world coordinates are given)", "up": "+z",+ "units": {"length": "m", "angle": "rad", "time": "s"}, "quaternion_order": "wxyz",+ "camera_axes": "intrinsic_cv / extrinsic_cv: OpenCV camera axes (x right, y down, z forward); cam2world_gl: OpenGL axes"},+ "budget": {"reset": 0, "steps": None, "wall_clock_s": WALL_CLOCK_S},+ "max_control_steps": S.horizon,+ "episode": TASK_EPISODE,+ "command_schedule": schedule_text(),+ **({"gait": {k: S.gait[k] for k in ("name", "frequency_hz", "foot_height_m", "phase0", "phase_dt")} | {+ "feet": FEET, "rule": "foot i's target height at control step t is get_rz(wrap(phase0[i] + t * phase_dt)) with "+ "Playground's gait.get_rz (a cubic Bezier from 0 up to foot_height_m over the first half of the phase, then "+ "down); phases in rad, wrapped to [-pi, pi)"}} if S.gait else {}),+ "robot_spec": {"name": S.robot["name"], "joints": S.joint_names, "joint_limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "joint_order": S.robot["joint_text"], "home_pose": dict(zip(S.joint_names, S.home.tolist())),+ "feet": FEET, "controller": _ctl},+ "kinematics": {"endpoint": "/kinematics", "joint_names": S.joint_names, "frame": "trunk", "quaternion_order": "wxyz",+ "links": FEET, "tcp_frames": [], "ee_frames": FEET, "ik_targets": FEET,+ "ik": {"tol_pos_m": 0.002, "tol_rot_rad": 3.2, "max_iters": 100},+ "note": "poses of the feet in the trunk frame (x forward, y left, z up, metres) for joint positions q; "+ "ik: one leg per foot, positions only"},+ "depth": {"modes": list(L.DEPTH_MODES), "default": "none", "kind": "z-depth", "unit": "m", "invalid": 0,+ "max_m": L.DEPTH_MAX_M, "frames_encoding": "uint16 mm, zlib", "noise": L.DEPTH_NOISE},+}+L.check_spec(SPEC) # a spec that misses a 2.2 field or names a forbidden one never starts the episode+EP.scene_built()++_RENDER = {}+++def _renderer():+ if "r" not in _RENDER:+ _RENDER["r"] = mujoco.Renderer(M, CAM_H, CAM_W)+ return _RENDER["r"]+++def ctrl_steps() -> int:+ return S.steps+++def proprio_row() -> np.ndarray:+ d = S.data+ return np.concatenate([d.qpos[7:], d.qvel[6:], d.actuator_force, S.sensor("gyro"), S.sensor("accelerometer"), S.gravity(),+ S.sensor("local_linvel"), S.foot_contacts()]).astype(np.float32)+++def grab(cams, want_depth: bool):+ r = _renderer()+ rgb, dep = {}, {}+ for c in cams:+ r.update_scene(S.data, camera=c)+ rgb[c] = r.render().copy()+ if want_depth:+ r.enable_depth_rendering()+ r.update_scene(S.data, camera=c)+ dep[c] = r.render().astype(np.float32).copy()+ r.disable_depth_rendering()+ return rgb, dep+++def extrinsics(cams) -> dict:+ return {c: np.asarray(camera_info(c)["extrinsic_cv"], dtype=np.float64) for c in cams}+++def write_final() -> None:+ if L.final_verdict(DATA): # finalize.sh's verdict, or a give-up after crashes: never overwritten+ return+ L._write_json(os.path.join(DATA, "final.json"), {**summary(), "finalized": False, "live_sha": E.get("live_sha")})+++def summary() -> dict:+ n = int(E.get("episode_control_steps") or ctrl_steps())+ chk = E.get("check") or {}+ return {"success": bool(E["success"]), "steps": E["step"], "calls": E["calls"], "control_steps": n,+ "physics_steps": n * SUBSTEPS, "elapsed_s": round((E.get("t_end") or time.time()) - E["t0"], 1),+ "reason": E["reason"], "done": E["done"], "env": S.env, "protocol": L.PROTOCOL, "n_actions": len(ROWS),+ "fell_at": chk.get("fell_at"), "worst_lin_err": chk.get("worst_lin_err"), "worst_yaw_err": chk.get("worst_yaw_err"),+ "tilt_deg": chk.get("tilt_deg"), "imu_height": chk.get("imu_height"), "pose_angle_deg": chk.get("pose_angle_deg"),+ **EP.final_fields()}+++def finish(reason: str) -> None:+ """The episode is over: the task's check on the steps executed, then the record for the collect hook."""+ if E["done"]:+ return+ E["done"] = True+ E["reason"] = reason+ E["t_end"] = time.time()+ E["episode_control_steps"] = ctrl_steps()+ try:+ chk = S.check()+ E["check"] = {k: v for k, v in chk.items() if k != "segments"}+ E["success"] = bool(chk["success"])+ except Exception: # noqa: BLE001+ traceback.print_exc()+ EP.log({"ev": "end", "reason": reason, "step": E["step"], "control_steps": ctrl_steps(), "success": bool(E["success"])})+ dump()+++def dump() -> None:+ if E.get("dumped"):+ return+ E["dumped"] = True+ E["live_sha"] = S.state_sha()+ np.savez(os.path.join(DATA, "trajectory.npz"), actions=np.asarray(ROWS, dtype=np.float64).reshape(-1, Q.N),+ env=S.env, action_layout=",".join(S.joint_names))+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})+ write_final()+++def after_step() -> None:+ if S.kind in ("joystick", "stand_on_two") and S.fell_at is not None:+ finish("fell")+ elif S.kind in ("getup", "stand_on_two") and S.check()["success"]:+ finish("success")+ elif S.done:+ finish("horizon")+++def ctrl_step(a, rec) -> bool:+ """One executed control step, journaled. True when the call must stop here."""+ S.step(a)+ ROWS.append(np.asarray(a, dtype=np.float64))+ stop = EP.journal(a)+ rec.tick()+ after_step()+ return E["done"] or stop+++def recorder(cams, fps: int, meta: dict) -> L.Recorder:+ return L.Recorder(cams, max(1, int(round(CTRL_HZ / max(1, fps)))), grab, proprio_row, extrinsics, ctrl_steps,+ depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+++def video_fps(meta: dict) -> int:+ fps = meta.get("video_fps")+ if fps is None:+ return 10+ if isinstance(fps, bool) or not isinstance(fps, (int, float)) or not (1 <= fps <= 50):+ raise ValueError("video_fps must be in [1, 50]")+ return int(fps)+++def cameras_of(meta: dict) -> list:+ cams = meta.get("cameras") or ["track"]+ bad = [c for c in cams if c not in CAMS]+ if bad:+ raise ValueError(f"unknown cameras {bad}; cameras: {CAMS}")+ return list(cams)+++def meta_common(cams) -> dict:+ n = ctrl_steps()+ out = {"step": E["step"], "calls": E["calls"], "control_steps": n, "physics_steps": n * SUBSTEPS,+ "sim_time_s": round(n * DT, 3), "time_s": round(time.time() - E["t0"], 2),+ "time_left_s": max(0.0, round(WALL_CLOCK_S - (time.time() - E["t0"]), 1)),+ "proprio": {"layout": PROPRIO_LAYOUT, "now": proprio_row().tolist()}, "done": E["done"], "reason": E["reason"],+ "cameras": {c: camera_info(c) for c in cams}}+ if S.kind == "joystick":+ out["command_now"] = dict(zip(("vx_mps", "vy_mps", "wz_radps"), S.command_now().round(4).tolist()))+ return out+++def do_submit(meta: dict, A: np.ndarray):+ typ = meta.get("type")+ if typ == "done":+ rec = recorder(cameras_of(meta), 5, meta)+ rec.tick(force=True, last=True) # every response carries the last frames+ E["calls"] += 1+ finish("done")+ return {**meta_common(cameras_of(meta)), "chunk_id": E["calls"], "type": typ, "executed_rows": 0, "ok": True}, rec.parts("none", 5)+ if typ != "joint_position":+ raise ValueError(f"type must be joint_position or done (not yet: {SPEC['action_types']['not_yet']})")+ dt = float(meta.get("dt", DT))+ interp = meta.get("interpolate", "linear")+ video = meta.get("video", "mp4")+ cams, fps = cameras_of(meta), video_fps(meta)+ k = dt / DT+ if A.ndim != 2 or A.shape[1] != Q.N:+ raise ValueError(f"joint_position actions must be (T, {Q.N}), got {list(A.shape)}")+ if not np.all(np.isfinite(A)):+ raise ValueError("actions contain NaN/inf")+ if not (math.isfinite(dt) and dt <= 0.5 + 1e-9 and round(k) >= 1 and abs(k - round(k)) < 1e-6):+ raise ValueError(f"dt must be a whole multiple of the {DT:g} s control period and at most 0.5 s; got {dt}")+ if A.shape[0] * dt > MAX_CHUNK_S + 1e-9:+ raise ValueError(f"chunk longer than max_chunk_s={MAX_CHUNK_S}: {A.shape[0]} rows x {dt} s")+ if interp not in ("hold", "linear"):+ raise ValueError("interpolate must be hold|linear")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, clipped = recorder(cams, fps, meta), []+ E["calls"] += 1+ step0, before = E["step"], ctrl_steps()+ rec.tick(force=True)+ prev = S.targets.copy()+ for ri, row in enumerate(A):+ E["step"] += 1+ target = np.clip(row, LIMITS[:, 0], LIMITS[:, 1])+ for j in np.flatnonzero(target != row)[:20]:+ clipped.append({"row": ri, "index": int(j), "reason": f"{S.joint_names[j]} limit [{LIMITS[j, 0]:g}, {LIMITS[j, 1]:g}]"})+ n = int(round(k))+ stop = False+ for s in range(1, n + 1):+ a = target if interp == "hold" else prev + (target - prev) * (s / n)+ if ctrl_step(a, rec):+ stop = True+ break+ prev = target+ if stop:+ break+ rec.tick(force=True, last=True)+ out = {**meta_common(cams), "chunk_id": E["calls"], "type": typ, "executed_rows": E["step"] - step0,+ "control_steps_chunk": ctrl_steps() - before, "physics_steps_chunk": (ctrl_steps() - before) * SUBSTEPS,+ "clipped": clipped[:200], "n_clipped": len(clipped), "plan": [], "ok": True}+ EP.log({"ev": "submit", "call": E["calls"], "rows": E["step"] - step0, "dt": dt, "interpolate": interp, "cameras": cams,+ "control_steps": ctrl_steps() - before, "n_clipped": len(clipped), "note": (meta.get("note") or "")[:500],+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video, fps)+++def do_observe(meta: dict):+ cams, fps = cameras_of(meta), video_fps(meta)+ seconds = float(meta.get("seconds", 0))+ video = meta.get("video", "frames")+ if not math.isfinite(seconds) or seconds < 0 or seconds > MAX_WATCH_S:+ raise ValueError(f"seconds must be in [0, {MAX_WATCH_S}]")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, before = recorder(cams, fps, meta), ctrl_steps()+ if seconds > 0 and not E["done"]:+ rec.tick(force=True)+ hold = S.targets.copy()+ for _ in range(int(round(seconds / DT))):+ if ctrl_step(hold, rec):+ break+ rec.tick(force=True, last=True)+ E["calls"] += 1+ out = {**meta_common(cams), "obs_id": E["calls"], "seconds": seconds, "control_steps_watch": ctrl_steps() - before,+ "physics_steps_watch": (ctrl_steps() - before) * SUBSTEPS, "ok": True}+ EP.log({"ev": "observe", "call": E["calls"], "seconds": seconds, "cameras": cams, "control_steps": ctrl_steps() - before,+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video if seconds > 0 else ("frames" if video == "mp4" else video), fps)+++def status() -> dict:+ return {"step": E["step"], "calls": E["calls"], "control_steps": ctrl_steps(), "done": E["done"], "reason": E["reason"],+ "elapsed_s": round(time.time() - E["t0"], 1)}+++def end_from_signal() -> None:+ """The collect hook's SIGUSR1: end the episode (the agent's time is over), dump it, exit so the replays can start."""+ with LOCK:+ E["exiting"] = True+ if not E["done"]:+ finish("timeout")+ EP.log({"ev": "exit", "reason": "collect hook: episode dumped"})+ if not os.path.exists(PID_FILE):+ open(PID_FILE, "w").write(str(os.getpid()))+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(0)+++def replay_row(row) -> None:+ """A journaled row during a resume."""+ S.step(row)+ ROWS.append(np.asarray(row, dtype=np.float64))+++EP.begin(state=E, step=replay_row, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, on_end=end_from_signal,+ start_event={"env": S.env, "seed": S.inst.get("seed"), "cameras": CAMS})+if E["done"]:+ dump() # resumed after the episode had ended: the record is rewritten from the replay+E["ready"] = True+write_final()+open(PID_FILE, "w").write(str(os.getpid()))+print(f"{L.PROTOCOL} MuJoCo Playground quadruped sim ready ({S.env}; startup {EP.n_startups}, resumes {EP.resumes})", flush=True)+L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics, status=status,+ on_submit_error=lambda exc: finish("error"), log=EP.log, episode=EP, state_sha=S.state_sha,+ proprio=proprio_row), port=int(os.environ.get("RCB_PORT", "8000")))diff --git a/tasks/mujoco_playground_spot_getup-standard/instruction.md b/tasks/mujoco_playground_spot_getup-standard/instruction.mdnew file mode 100644index 0000000000..2ceb28543c--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/instruction.md@@ -0,0 +1,46 @@+# MuJoCo Playground · SpotGetup — STANDARD MODE (robot as a service, eai-standard/2.2)++**Task:** Boston Dynamics Spot has fallen over. Make it get up and stand upright at its standing height.++You control the Boston Dynamics Spot quadruped — **as if it were real hardware** — in one episode of MuJoCo Playground's+`SpotGetup` environment (plain MuJoCo 3.3.7 with Playground's scene, commit 4057c14). The simulator runs in a service you+cannot open. You get one client and one episode.++## The episode+The robot was dropped from 1 m in a random orientation with random joint angles (no base velocity) and settled for 0.5 s with its joints held: at the start it lies with its trunk tilted 128.4 deg from upright. You have 300 control steps (6 s).++## Rules (real-robot rules)+- **No reset.** One episode. You see four cameras that follow the robot (RGB, depth if you ask) and the robot's own+ sensors: joint positions, velocities and torques, the IMU (gyro, accelerometer, gravity's direction, the trunk's+ velocity), foot contacts. No world positions, no success check.+- **The episode ends** the moment the robot has been upright for 25 control steps in a row (success), after 300 control steps (`spec["max_control_steps"]`, counted by `meta["control_steps"]`), when you submit `done`, or when your time is up.+- **Success** is 25 control steps in a row with the trunk within 10 deg of upright and the IMU at least 0.4 m above the floor (the Spot stands at 0.44 m), judged after every control step; when the episode ends otherwise, it is judged on its last control steps.+- Your wall-clock budget is 3600 s from your start. Simulated time only advances with your commands (and+ `get_obs(seconds=...)`, which holds the current targets).+- Nothing to hand in: the service records the episode and grades it. Leave your script at `/app/output/gen.py`.+- **If the service crashes**, a call fails with a connection error: it restarts and resumes the SAME episode (never a+ reset) in the state after the last call it completed. `r.wait_ready()` waits for it; then check `r.status()`.+- Nothing is put into your context automatically: images come back as arrays in Python objects.++## Client (`/opt/tools/rcb_client.py`)+```python+from rcb_client import Robot+r = Robot() # connects (waits while the service starts)+spec = r.spec() # action types, limits, cameras, robot_spec (home pose, gains), kinematics+obs = r.get_obs() # obs.last[cam] -> uint8 (240, 320, 3); obs.meta["proprio"] {"layout", "now"}+res = r.submit("joint_position", A, dt=0.02) # A: (T, 12) rows dt apart; res.proprio (one row per frame), res.meta+obs = r.get_obs(seconds=1.0, video="mp4") # hold the current targets and watch for 1 s (max 30)+r.fk(q); r.ik({"FL": [x, y, z, 1, 0, 0, 0]}, seed=q) # feet in the trunk frame <-> joints (no physics)+r.submit("done", []) # end the episode now+r.status() # calls, control steps, done, reason, elapsed time+```+Cameras: `track`, `side`, `back`, `top` (they follow the robot); `spec["cameras"]` gives each one's mounting and intrinsics, and every response carries its pose. Proprioception (`spec["proprio_groups"]`): `joint_pos`, `joint_vel`, `joint_effort` (12 each, action+order), `imu_gyro`, `imu_accelerometer`, `imu_gravity`, `imu_linvel` (3 each, IMU frame: x forward, y left, z up),+`foot_contact` (FL, FR, HL, HR).++### `joint_position` (12)+FL, FR, HL, HR legs, each hx (abduction), hy (hip pitch), kn (knee): absolute targets of the joint position actuators (rad; kp = 400 N m/rad, joint damping 20 N m s/rad).+Rows are `dt` apart (a whole multiple of the 0.02 s control period, at most 0.5 s), `interpolate="linear"` (default) or+`"hold"` between rows; a chunk covers at most 10 s; values outside the limits+(`spec["action_types"]["joint_position"]["limits"]`) are clipped and listed in `res.meta["clipped"]`. Feedback control+means short chunks: each response tells you where the robot is now.diff --git a/tasks/mujoco_playground_spot_getup-standard/solution/oracle.npy b/tasks/mujoco_playground_spot_getup-standard/solution/oracle.npynew file mode 100644index 0000000000..1198383fb3Binary files /dev/null and b/tasks/mujoco_playground_spot_getup-standard/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_spot_getup-standard/solution/oracle_replay.py b/tasks/mujoco_playground_spot_getup-standard/solution/oracle_replay.pynew file mode 100644index 0000000000..b6a9824592--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/solution/oracle_replay.py@@ -0,0 +1,42 @@+"""Oracle (standard mode): streams the reference rows (one per 1/50 s control step, `hold`) as `joint_position` chunks+through the client, the same interface an agent has. Uses no privileged information at run time; the service's recorded+trajectory is then exactly the privileged reference. If the service crashes it resumes the same episode+(spec["on_service_error"]): the oracle waits until it answers again and goes on from the control step it reports."""+import os+import sys+import time++import numpy as np+import requests++sys.path.insert(0, "/opt/tools")+from rcb_client import EpisodeOver, Robot # noqa: E402++Q = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy")).astype(np.float64)+r = Robot()+spec = r.spec()+dt = 1.0 / float(spec["control_hz"])+per_chunk = max(1, int(spec.get("max_chunk_s", 10) / dt + 1e-9))+print("spec:", spec["protocol"], "rows:", len(Q), flush=True)+t0, i = time.time(), 0+while i < len(Q):+ chunk = Q[i:i + per_chunk]+ try:+ res = r.submit("joint_position", chunk, dt=dt, interpolate="hold", cameras=["track"], video="none", note=f"oracle rows {i}+")+ except EpisodeOver as e:+ print("episode over:", e)+ break+ except requests.exceptions.RequestException as e: # the service crashed: it restarts and resumes the same episode+ print("service unreachable:", repr(e)[:200], "- waiting for it to resume", flush=True)+ st = r.wait_ready()+ n = int(st["control_steps"])+ if not i <= n <= i + len(chunk):+ raise SystemExit(f"resumed at control step {n}: outside the chunk in flight (rows {i}..{i + len(chunk)})")+ i = n+ continue+ n = int(res.meta["control_steps"])+ print(f"rows {i}..{n}: clipped={res.meta['n_clipped']} done={res.meta['done']} reason={res.meta['reason']}", flush=True)+ if res.meta["done"] or n <= i:+ break+ i = n+print("status:", r.status(), "wall %.0fs" % (time.time() - t0))diff --git a/tasks/mujoco_playground_spot_getup-standard/solution/solve.sh b/tasks/mujoco_playground_spot_getup-standard/solution/solve.shnew file mode 100755index 0000000000..ecb1f6c954--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/solution/solve.sh@@ -0,0 +1,8 @@+#!/bin/bash+# Oracle (standard mode): streams the reference trajectory's joint targets (solution/oracle.npy, one row per control step)+# as `joint_position` chunks through the client. Uses no privileged information at run time (only the pre-recorded+# targets); the service's recorded trajectory is then exactly the privileged reference.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_spot_getup-standard/task.toml b/tasks/mujoco_playground_spot_getup-standard/task.tomlnew file mode 100644index 0000000000..f71057affc--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/task.toml@@ -0,0 +1,54 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = [+ { source = "/data/final.json", service = "sim" },+ { source = "/data/episode.jsonl", service = "sim" },+ { source = "/data/trajectory.npz", service = "sim" },+ { source = "/data/replay.mp4", service = "sim" },+ { source = "/data/server.log", service = "sim" }, # the service's own output (Harbor keeps none)+ { source = "/data/journal.f64", service = "sim" }, # crash recovery: every executed control step (float64 rows)+ { source = "/data/startups.jsonl", service = "sim" }, # crash recovery: one line per service start+ { source = "/data/replay1.log", service = "sim" }, # the collect hook's two fresh-process replays+ { source = "/data/replay2.log", service = "sim" },+ { source = "/data/replay3.log", service = "sim" }, # and its third, which renders replay.mp4+ "/app/output/",+]++[task]+name = "robot-coding-bench/mujoco_playground_spot_getup-standard"+description = "STANDARD MODE (robot as a service, eai-standard/2.2): MuJoCo Playground SpotGetup (Boston Dynamics Spot) on the same frozen instance as mujoco_playground_spot_getup-privileged: Boston Dynamics Spot has fallen over. Make it get up and stand upright at its standing height. The agent only gets a client: four cameras that follow the robot (RGB, optional depth), the robot's joints and IMU, joint position chunks at 50 Hz, the feet's kinematics; one episode, no reset, no world state; the sim service records the episode, replays it in fresh processes and grades it."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "boston-dynamics-spot", "quadruped", "locomotion", "getup", "code-as-policy", "trajectory", "standard-mode"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "boston-dynamics-spot"+family = "mujoco_playground/SpotGetup"+mode = "standard"+protocol = "eai-standard/2.2"+oracle = "full"+instance_seed = 1+expert_time_estimate_hours = 3.0++[verifier]+timeout_sec = 600.0+environment_mode = "separate"+network_mode = "no-network"++[[verifier.collect]]+service = "sim"+command = "sh /srv/finalize.sh" # end + dump + exit the service, replay twice in fresh processes, write final.json, video+timeout_sec = 1200++[agent]+timeout_sec = 3600.0+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_spot_getup-standard/tests/Dockerfile b/tasks/mujoco_playground_spot_getup-standard/tests/Dockerfilenew file mode 100644index 0000000000..26bc699ebe--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/tests/Dockerfile@@ -0,0 +1,5 @@+# Separate verifier sandbox: grades the sim service's own artifacts; needs nothing but python (the shared client base).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY test.sh /tests/test.sh+COPY grade.py /tests/grade.py+RUN chmod +x /tests/test.shdiff --git a/tasks/mujoco_playground_spot_getup-standard/tests/grade.py b/tasks/mujoco_playground_spot_getup-standard/tests/grade.pynew file mode 100644index 0000000000..5b990bf458--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/tests/grade.py@@ -0,0 +1,64 @@+"""Standard-mode verifier (MuJoCo Playground quadrupeds): reads what the sim service (which the agent could not touch) wrote:+/data/final.json (live success, two fresh-process replays of the recorded trajectory, determinism, crash-recovery+fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, the+replays having started in the instance's t = 0 state. Numeric-only reward.json."""++import json, os, shutil++LOG = "/logs/verifier"+os.makedirs(LOG, exist_ok=True)+++def write(ok, out):+ open(f"{LOG}/reward.txt", "w").write("1\n" if ok else "0\n")+ json.dump(out, open(f"{LOG}/reward.json", "w"))+ print(out)+++p = "/data/final.json"+if not os.path.exists(p):+ write(False, {"success": 0, "missing_log": 1, "grader_error": 0, "infra_error": 0})+ raise SystemExit+d = json.load(open(p))+for f in ("replay.mp4", "trajectory.npz", "episode.jsonl"):+ if os.path.exists(f"/data/{f}"):+ shutil.copy(f"/data/{f}", f"{LOG}/{f}")+ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic"))+ok = ok and not d.get("instance_mismatch")+num = lambda k: float(d.get(k) or 0) # noqa: E731+write(+ ok,+ {+ "success": int(ok),+ "live_success": int(bool(d.get("success"))),+ "replay_success": int(bool(d.get("replay_success"))),+ "deterministic": int(bool(d.get("deterministic"))),+ "live_matches_replay": int(bool(d.get("live_matches_replay"))),+ "finalized": int(bool(d.get("finalized"))),+ "n_actions": int(d.get("n_actions") or 0),+ "sim_steps": int(d.get("control_steps") or 0),+ "physics_steps": int(d.get("physics_steps") or 0),+ "steps": int(d.get("steps") or 0),+ "elapsed_s": float(d.get("elapsed_s") or 0),+ "video_rendered": int(bool(d.get("video"))),+ "fell": int(d.get("fell_at") is not None),+ "worst_lin_err": float(d["worst_lin_err"]) if d.get("worst_lin_err") is not None else -1.0,+ "worst_yaw_err": float(d["worst_yaw_err"]) if d.get("worst_yaw_err") is not None else -1.0,+ "end_tilt_deg": float(d["tilt_deg"]) if d.get("tilt_deg") is not None else -1.0,+ "end_imu_height": float(d["imu_height"]) if d.get("imu_height") is not None else -1.0,+ "end_pose_angle_deg": float(d["pose_angle_deg"]) if d.get("pose_angle_deg") is not None else -1.0,+ # a replay process gave no result, or the image no longer builds the frozen start: not the agent's 0+ "grader_error": int(bool(d.get("replay_failed") or d.get("instance_mismatch"))),+ "instance_mismatch": int(bool(d.get("instance_mismatch"))),+ # an infrastructure failure, not the agent's (PROTOCOL §2.6): a give-up after crashes between calls or a failed+ # resume (docs/STANDARD_MODE_2_2.md §13), the service not ending its episode for the collect hook, a replay+ # process that gave no result, replays that did not start in the instance's t = 0 state+ "infra_error": int(bool(d.get("infra_error"))),+ "gave_up": int(bool(d.get("gave_up"))),+ "sim_error": int(d.get("reason") == "error"),+ "sim_startups": int(d.get("sim_startups") or 0),+ "resumes": int(d.get("resumes") or 0),+ "resume_state_mismatch": int(d.get("resume_state_mismatch") or 0),+ "resume_max_joint_dev": num("resume_max_joint_dev"),+ },+)diff --git a/tasks/mujoco_playground_spot_getup-standard/tests/test.sh b/tasks/mujoco_playground_spot_getup-standard/tests/test.shnew file mode 100755index 0000000000..bc608aa8b9--- /dev/null+++ b/tasks/mujoco_playground_spot_getup-standard/tests/test.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Verifier (separate sandbox): the sim sidecar's artifacts were uploaded to /data by Harbor.+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)+mkdir -p /logs/verifier+python /tests/grade.py 2> /logs/verifier/grade.logdiff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/README.md b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/README.mdnew file mode 100644index 0000000000..b27924a857--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/README.md@@ -0,0 +1,42 @@+# mujoco_playground_spot_joystick_gait_tracking-privileged++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | privileged |+| Twin | `mujoco_playground_spot_joystick_gait_tracking-standard` |+| Simulator / robot | `mujoco` / `boston-dynamics-spot` |+| Family / instance | `mujoco_playground/SpotJoystickGaitTracking` / seed 0 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `SpotJoystickGaitTracking` (Boston Dynamics Spot), rebuilt in plain MuJoCo from Playground's scene files: Make Boston Dynamics Spot follow the joystick command schedule for the whole 20 s episode with the commanded gait (the feet's swing pattern, frequency and height) without falling over.+For 20 s the robot gets a joystick command schedule (5 segments: planar velocity and yaw rate in its own frame) and must track it without falling over. Its feet must follow a pace gait. The deliverable is one replayable trajectory of joint position targets+(`/app/output/trajectory.npz`, `(T, 12)`, T = 1000 (the whole schedule)).++## Difficulty+Velocity tracking for 20 s: the agent has to make a 12-joint quadruped walk (a gait, not one motion) and steer it through the schedule's changes of speed, direction and turning rate, and an open-loop trajectory of 1000 steps only works if it is computed against the simulator. On top of the velocity commands the feet have to follow a commanded gait: which feet swing together, at a fixed frequency and to a commanded height.++## Reference solution+A policy trained here on Playground's SpotJoystickGaitTracking reward (PPO on the CPU, `scripts/mujoco-playground/train/`, not in the image), with the command added to its observation (`train/qenv.py` SpotJoystickGaitTrackingCmd: Playground's observation leaves the command out, so a policy trained on it marches in place and cannot track the joystick its reward asks for), its targets recorded (`scripts/mujoco-playground/oracle.py`): worst segment errors 0.183 m/s and 0.136 rad/s, foot height 0.038 m. Replayed by `solution/solve.sh` (`solution/oracle.npy`, 1000 rows); the rows are float32-exact, so the+standard twin's client executes the same targets. Re-verified by `scripts/mujoco-playground/select_instances.py`: two+fresh-process replays succeed and end in the same state.++## Verification+`tests/grade.py` in a separate sandbox without network: two replays, each in a fresh process, from the verifier's own+copy of the instance (`tests/instance.json`; the start state is checked against its hash on every load); pass iff both+succeed and end in the same state (`deterministic`). Oracle: success, worst segment errors 0.183 m/s and 0.136 rad/s. `nop`: no trajectory, reward 0.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml`; MuJoCo Menagerie @ 1b86ece (`boston_dynamics_spot`); simulated in MuJoCo 3.3.7 on the CPU |+| Instance | Playground's `reset` with `jax.random.PRNGKey(0)` and Playground's command process over the 1000 steps; chosen by `scripts/mujoco-playground/select_instances.py` (seed 0; the first candidate) |+| Actions | 12 joint position targets per control step (0.02 s of simulated time); kp = 400 N m/rad, joint damping 10 N m s/rad, plus the actuators' own damping of 20 N m s/rad |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py` from `scripts/mujoco-playground/instances/SpotJoystickGaitTracking.json`+(`make_instances.py`, `select_instances.py`) and `scripts/mujoco-playground/oracles/SpotJoystickGaitTracking.npy` (`oracle.py`).diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/environment/Dockerfile b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/environment/Dockerfilenew file mode 100644index 0000000000..7bdd7d2938--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/environment/Dockerfile@@ -0,0 +1,8 @@+# MuJoCo Playground quadruped task (privileged): plain MuJoCo with Playground's and Menagerie's assets+# (images/mujoco/prepare_assets.sh), the task's tooling and its frozen instance.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY instance.json /app/instance.json+COPY rcb_quadruped.py /opt/tools/rcb_quadruped.py+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/environment/instance.json b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/environment/instance.jsonnew file mode 100644index 0000000000..51247a4914--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/environment/instance.json@@ -0,0 +1,114 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "SpotJoystickGaitTracking",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 0.46000000834465027,+ 1.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842+ ],+ "qvel0": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 0.9938757419586182,+ "vy": 0.37067461013793945,+ "wz": 0.44742894172668457+ },+ {+ "start_step": 201,+ "vx": 0.9238066673278809,+ "vy": -0.3616582155227661,+ "wz": -0.32676148414611816+ },+ {+ "start_step": 402,+ "vx": -0.9385867118835449,+ "vy": 0.09156465530395508,+ "wz": 0.44982028007507324+ },+ {+ "start_step": 603,+ "vx": -0.9596819877624512,+ "vy": -0.29509055614471436,+ "wz": 0.5688352584838867+ },+ {+ "start_step": 804,+ "vx": 0.8662233352661133,+ "vy": 0.1854252815246582,+ "wz": -0.2966732978820801+ }+ ],+ "gait": {+ "type": 2,+ "name": "pace",+ "frequency_hz": 3.6585731506347656,+ "foot_height_m": 0.12916938960552216,+ "phase0": [+ 0.0,+ 3.1415927410125732,+ 0.0,+ 3.1415927410125732+ ],+ "phase_dt": 0.45974987745285034+ },+ "text": "Make Boston Dynamics Spot follow the joystick command schedule for the whole 20 s episode with the commanded gait (the feet's swing pattern, frequency and height) without falling over.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": 0.0,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.46,+ "reference_rows": 1000,+ "torso_mass_kg": 50.34,+ "reference_worst_lin_err": 0.1827,+ "reference_worst_yaw_err": 0.1358,+ "reference_worst_gait_err": 0.0383+ },+ "state_sha": "53128662ae17",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s), when its pushes (Barkour) are null or\n weak (peak under 20% of the torso's weight), or when the reference trajectory (oracle.py) fails the task's\n success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/environment/rcb_quadruped.py b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/environment/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/environment/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/instruction.md b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/instruction.mdnew file mode 100644index 0000000000..22c775b5d9--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/instruction.md@@ -0,0 +1,65 @@+# MuJoCo Playground · SpotJoystickGaitTracking — frozen episode++**Task:** Make Boston Dynamics Spot follow the joystick command schedule for the whole 20 s episode with the commanded gait (the feet's swing pattern, frequency and height) without falling over.++You control the Boston Dynamics Spot quadruped in one episode of MuJoCo Playground's `SpotJoystickGaitTracking` environment, rebuilt in plain+MuJoCo 3.3.7 from Playground's own scene files (Apache-2.0, commit 4057c14) and the robot from MuJoCo Menagerie. The+episode is frozen: it starts the same way after every reset (Playground's `reset` with seed 0), and you may reset+as often as you like. Your deliverable is **one open-loop trajectory**, not a general policy.++## The episode+The robot starts standing still at Playground's `home` pose (this environment's reset does not move it). The ground is flat.+For 20 s (1000 control steps) it is given this command schedule, drawn by Playground's command process (a new draw every 201 control steps, zero with probability 0.1). A command is a velocity in the robot's own frame: vx forward, vy to the left (the trunk's planar velocity), and the yaw rate:++| from (s) | vx (m/s) | vy (m/s) | yaw rate (rad/s) |+|---:|---:|---:|---:|+| 0.00 | +0.994 | +0.371 | +0.447 |+| 4.02 | +0.924 | -0.362 | -0.327 |+| 8.04 | -0.939 | +0.092 | +0.450 |+| 12.06 | -0.960 | -0.295 | +0.569 |+| 16.08 | +0.866 | +0.185 | -0.297 |++The feet must also follow a **pace** gait at 3.66 Hz with a swing height of 0.129 m: foot i's target height at control step t is Playground's `gait.get_rz(wrap(phase0[i] + t * phase_dt), foot_height)` (a cubic Bezier up over the first half of the phase, then down), with phase0 = [0.0, 3.1416, 0.0, 3.1416] (feet FL, FR, HL, HR) and phase_dt = 0.4597 rad.++`s.commands` holds the schedule per control step; `s.state()["command"]` is the current one.++## Success+The episode lasts exactly 1000 control steps: the trajectory must have T = 1000 rows. Success iff+1. the robot never meets Playground's termination rule for this environment: the trunk tilted by more than about 32 deg (the z component of the IMU frame's z axis below 0.85); and+2. in every command segment, over its control steps after the first 25 (0.5 s): the mean planar velocity error |v_xy - cmd_xy| is at most 0.2 m/s, with v the IMU's velocimeter (`local_linvel`, trunk frame), and the mean yaw-rate error |w_z - cmd_wz| at most 0.3 rad/s, with w the IMU's gyro; and the mean, over the same steps, of the feet's RMS height error to their target heights is at most 0.05 m.++`s.check()` reports `fell_at`, each segment's errors and `success`.++## Deliverable+`/app/output/trajectory.npz` with `actions`: float64 (T, 12), one row per control step (0.02 s): absolute targets of+the 12 joint position actuators, in `s.joint_names` order (FL, FR, HL, HR legs, each hx (abduction), hy (hip pitch), kn (knee)), in radians; T = 1000 (the whole schedule). Values+outside the actuator ranges (`s.lower`, `s.upper`) are clipped. `s.save_trajectory(rows)` writes it. Also leave the+script that produced it at `/app/output/gen.py`. Save a working trajectory as soon as you have one and overwrite it as+you improve it: whatever is in `/app/output/` when your 3600 s are up is graded. The tooling logs your sessions and+resets (cost accounting, not graded).++## Tooling (installed; `python` from any directory)+```python+from rcb_quadruped import Session+s = Session("/app/instance.json") # the frozen episode at t = 0 (checked against the instance's state hash)+s.joint_names; s.lower; s.upper # the actuator order and ranges (rad)+s.home # Playground's standing pose (its `home` keyframe), in that order+s.step(row) # one control step: 12 joint targets, 5 physics steps of 0.004 s; returns s.check()+s.check() # the task's check on the steps so far (see Success)+s.state() # qpos, qvel, IMU (local_linvel, gyro, gravity, accelerometer, pose), feet, contacts, command+s.sensor(name); s.gravity() # one MuJoCo sensor; gravity's direction in the IMU frame+s.model, s.data # the live MuJoCo model and data (read them; changing them is not part of the replay)+s.render(cam); s.cameras # uint8 (240, 320, 3) from cameras that follow the robot: `track`, `side`, `back`, `top` (they follow the robot)+s.reset() # back to t = 0+s.replay(rows) # reset, run the rows, return the check and the final state's hash+s.render_video(rows, "/app/output/try.mp4")+s.save_trajectory(rows, "/app/output/trajectory.npz")+```+The grader runs exactly this CLI in two fresh processes, so run it to check yourself:+`python /opt/tools/rcb_quadruped.py replay --instance /app/instance.json --traj /app/output/trajectory.npz`++## Conventions+- Joint position actuators (PD): kp = 400 N m/rad, joint damping 10 N m s/rad, plus the actuators' own damping of 20 N m s/rad, as Playground's environment sets them; the physics step is 0.004 s,+ the control step 0.02 s (5 physics steps); a row holds until the next one.+- World frame z up, metres; quaternions **wxyz**. The IMU frame is the trunk's: x forward, y left, z up.+- Physics is MuJoCo on the CPU: the same rows from the same start give the same result in every fresh process.diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/solution/oracle.npy b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/solution/oracle.npynew file mode 100644index 0000000000..565259883eBinary files /dev/null and b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/solution/oracle_replay.py b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/solution/oracle_replay.pynew file mode 100644index 0000000000..46987df1d0--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/solution/oracle_replay.py@@ -0,0 +1,15 @@+"""Oracle (privileged): replay the reference rows in the tooling, check them, and save them as the deliverable."""+import json+import os+import sys++import numpy as np++sys.path.insert(0, "/opt/tools")+from rcb_quadruped import Session # noqa: E402++rows = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy"))+s = Session("/app/instance.json")+r = s.replay(rows)+s.save_trajectory(rows, "/app/output/trajectory.npz", meta={"source": "reference trajectory (solution/oracle.npy)"})+print(json.dumps({k: v for k, v in r.items() if k != "segments"}))diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/solution/solve.sh b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/solution/solve.shnew file mode 100755index 0000000000..430ffb6017--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/solution/solve.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Oracle (privileged): write the reference trajectory frozen at generation time (solution/oracle.npy; how it was made:+# scripts/mujoco-playground/oracle.py) as the deliverable.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/task.toml b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/task.tomlnew file mode 100644index 0000000000..364afd5a6a--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/task.toml@@ -0,0 +1,43 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = ["/app/output/", "/logs/agent/rcb/"]++[task]+name = "robot-coding-bench/mujoco_playground_spot_joystick_gait_tracking-privileged"+description = "MuJoCo Playground SpotJoystickGaitTracking in plain MuJoCo (Boston Dynamics Spot, joint position control every 0.02 s): Make Boston Dynamics Spot follow the joystick command schedule for the whole 20 s episode with the commanded gait (the feet's swing pattern, frequency and height) without falling over. Produce one replayable trajectory of joint position targets on a frozen instance (Playground's reset with seed 0); graded by velocity tracking over the whole 20 s schedule without a fall (two fresh-process replays)."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "boston-dynamics-spot", "quadruped", "locomotion", "joystick", "code-as-policy", "trajectory", "privileged"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "boston-dynamics-spot"+family = "mujoco_playground/SpotJoystickGaitTracking"+mode = "privileged"+oracle = "full"+instance_seed = 0 # the PRNGKey of Playground's reset (and, for the joystick tasks, its command process)+expert_time_estimate_hours = 3.0++[verifier]+timeout_sec = 1200.0+environment_mode = "separate"+network_mode = "no-network"++[verifier.environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192++[agent]+timeout_sec = 3600.0+# MuJoCo Playground's trained policies are public upstream, so the agent reaches the model APIs and nothing else+# (scripts/set_agent_egress.py HOSTS).+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/tests/Dockerfile b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/tests/Dockerfilenew file mode 100644index 0000000000..f49c79154d--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/tests/Dockerfile@@ -0,0 +1,7 @@+# Separate verifier sandbox (PROTOCOL §4): the same image with the verifier's own copies of the tooling and the frozen+# instance. Nothing the agent did in its container reaches this one: Harbor uploads only the declared artifacts.+FROM ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+COPY grade.py instance.json rcb_quadruped.py test.sh /tests/+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier+ENV PYTHONPATH=/tests+WORKDIR /testsdiff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/tests/grade.py b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/tests/grade.pynew file mode 100644index 0000000000..e5668de85f--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/tests/grade.py@@ -0,0 +1,126 @@+"""Verifier (privileged): replay /app/output/trajectory.npz from the frozen instance and write Harbor's rewards.++ python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz++Two replays, each in its own fresh process (`rcb_quadruped.py replay`: the frozen start, one control step per row, the+task's success check on the whole trajectory). success = both replays succeed and end in the same state. Writes+/logs/verifier/reward.txt (1/0) and reward.json (numbers only); then a third replay renders replay.mp4, after the+verdict is on disk (it never changes it).+"""+import argparse+import json+import os+import subprocess+import sys+import tempfile+import traceback++import numpy as np++LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")+TOOL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rcb_quadruped.py")+REPLAY_TIMEOUT_S = 300 # a 1000-step replay takes a few seconds; the video replay renders 4 views every 2nd step+++def write(ok: bool, out: dict) -> None:+ os.makedirs(LOG_DIR, exist_ok=True)+ open(os.path.join(LOG_DIR, "reward.txt"), "w").write("1\n" if ok else "0\n")+ json.dump(out, open(os.path.join(LOG_DIR, "reward.json"), "w"))+ print(json.dumps(out), flush=True)+++def agent_cost() -> dict:+ """Self-reported cost from the tooling's log in the agent's container (accounting, not evidence)."""+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_replays": 0, "agent_cost_self_reported": 1}+ for path in ("/logs/agent/rcb/rcb_session_log.jsonl", "/app/output/rcb_session_log.jsonl"):+ if not os.path.exists(path):+ continue+ try:+ with open(path) as f:+ for i, line in enumerate(f):+ if i > 200_000 or len(line) > 10_000:+ break+ try:+ e = json.loads(line)+ ev = e.get("ev") if isinstance(e, dict) else None+ if ev == "session_start":+ cost["agent_sessions"] += 1+ elif ev == "reset":+ cost["agent_resets"] += 1+ elif ev == "replay":+ cost["agent_replays"] += 1+ elif ev == "session_end":+ cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)+ except Exception: # noqa: BLE001 -- one bad line must not sink the verdict+ continue+ except OSError:+ pass+ break+ return cost+++def replay(instance: str, traj: str, video: str | None) -> dict:+ """One replay in a fresh process; its result (`--out`), or {"error": ...}."""+ with tempfile.NamedTemporaryFile(suffix=".json") as out:+ cmd = [sys.executable, TOOL, "replay", "--instance", instance, "--traj", traj, "--out", out.name]+ try:+ p = subprocess.run(cmd + (["--video", video] if video else []), stdout=subprocess.DEVNULL, stderr=sys.stderr,+ timeout=REPLAY_TIMEOUT_S, env={**os.environ, "RCB_SESSION_LOG": "", "RCB_AGENT_TRACE_DIR": ""})+ except subprocess.TimeoutExpired:+ return {"error": f"replay took over {REPLAY_TIMEOUT_S} s"}+ try:+ return json.load(open(out.name))+ except ValueError:+ return {"error": f"replay process rc={p.returncode}"}+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--instance", required=True)+ ap.add_argument("--traj", default="/app/output/trajectory.npz")+ a = ap.parse_args()+ cost = agent_cost()+ if not os.path.isfile(a.traj):+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost})+ return 0+ try:+ horizon = int(json.load(open(a.instance))["horizon"])+ d = np.load(a.traj, allow_pickle=False)+ acts = np.asarray(d["actions"], dtype=np.float64) if "actions" in d.files else np.zeros((0, 0))+ if acts.ndim != 2 or acts.shape[1] != 12 or len(acts) > horizon or not np.all(np.isfinite(acts)):+ write(False, {"success": 0, "bad_trajectory": 1, "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0,+ "grader_error": 0, **cost})+ return 0+ runs = [replay(a.instance, a.traj, None), replay(a.instance, a.traj, None)]+ if any("error" in r and not r.get("bad_trajectory") for r in runs):+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ if not all(r.get("instance_ok") for r in runs): # the image no longer builds the frozen start: not the agent's 0+ write(False, {"success": 0, "grader_error": 1, "instance_mismatch": 1, **cost})+ return 0+ all_success = all(bool(r.get("success")) for r in runs)+ deterministic = runs[0].get("state_sha") == runs[1].get("state_sha")+ ok = all_success and deterministic+ r = runs[0]+ num = lambda k: float(r.get(k) if r.get(k) is not None else -1) # noqa: E731+ out = {"success": int(ok), "replay_success": int(all_success), "deterministic": int(deterministic),+ "n_actions": int(len(acts)), "horizon": horizon, "fell": int(r.get("fell_at") is not None),+ "fell_at_step": num("fell_at"), "worst_lin_err": num("worst_lin_err"), "worst_yaw_err": num("worst_yaw_err"),+ "end_tilt_deg": num("tilt_deg"), "end_imu_height": num("imu_height"), "end_pose_angle_deg": num("pose_angle_deg"),+ "grader_error": 0,+ "video_rendered": 0, **cost}+ write(ok, out) # the verdict, before any video+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ write(False, {"success": 0, "grader_error": 1, **cost})+ return 0+ try: # the video, for humans: it never changes the verdict+ if replay(a.instance, a.traj, os.path.join(LOG_DIR, "replay.mp4")).get("video"):+ write(ok, {**out, "video_rendered": 1})+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/tests/instance.json b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/tests/instance.jsonnew file mode 100644index 0000000000..51247a4914--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/tests/instance.json@@ -0,0 +1,114 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "SpotJoystickGaitTracking",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 0.46000000834465027,+ 1.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842+ ],+ "qvel0": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 0.9938757419586182,+ "vy": 0.37067461013793945,+ "wz": 0.44742894172668457+ },+ {+ "start_step": 201,+ "vx": 0.9238066673278809,+ "vy": -0.3616582155227661,+ "wz": -0.32676148414611816+ },+ {+ "start_step": 402,+ "vx": -0.9385867118835449,+ "vy": 0.09156465530395508,+ "wz": 0.44982028007507324+ },+ {+ "start_step": 603,+ "vx": -0.9596819877624512,+ "vy": -0.29509055614471436,+ "wz": 0.5688352584838867+ },+ {+ "start_step": 804,+ "vx": 0.8662233352661133,+ "vy": 0.1854252815246582,+ "wz": -0.2966732978820801+ }+ ],+ "gait": {+ "type": 2,+ "name": "pace",+ "frequency_hz": 3.6585731506347656,+ "foot_height_m": 0.12916938960552216,+ "phase0": [+ 0.0,+ 3.1415927410125732,+ 0.0,+ 3.1415927410125732+ ],+ "phase_dt": 0.45974987745285034+ },+ "text": "Make Boston Dynamics Spot follow the joystick command schedule for the whole 20 s episode with the commanded gait (the feet's swing pattern, frequency and height) without falling over.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": 0.0,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.46,+ "reference_rows": 1000,+ "torso_mass_kg": 50.34,+ "reference_worst_lin_err": 0.1827,+ "reference_worst_yaw_err": 0.1358,+ "reference_worst_gait_err": 0.0383+ },+ "state_sha": "53128662ae17",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s), when its pushes (Barkour) are null or\n weak (peak under 20% of the torso's weight), or when the reference trajectory (oracle.py) fails the task's\n success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/tests/rcb_quadruped.py b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/tests/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/tests/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/tests/test.sh b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/tests/test.shnew file mode 100755index 0000000000..1c3d2f767b--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-privileged/tests/test.sh@@ -0,0 +1,9 @@+#!/bin/bash+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in two fresh processes (the+# verdict), then a third that renders replay.mp4.+# Writes /logs/verifier/reward.txt (1/0) and reward.json (numeric fields, docs/PROTOCOL.md §2.6).+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/*+mkdir -p /logs/verifier+python /tests/grade.py --instance /tests/instance.json --traj /app/output/trajectory.npz 2> /logs/verifier/grade.logdiff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/README.md b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/README.mdnew file mode 100644index 0000000000..f86d9cbe57--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/README.md@@ -0,0 +1,44 @@+# mujoco_playground_spot_joystick_gait_tracking-standard++| | |+|---|---|+| Benchmark | MuJoCo Playground |+| Mode | standard (`eai-standard/2.2`) |+| Twin | `mujoco_playground_spot_joystick_gait_tracking-privileged` |+| Simulator / robot | `mujoco` / `boston-dynamics-spot` |+| Family / instance | `mujoco_playground/SpotJoystickGaitTracking` / seed 0 |+| Oracle | `full` |+| Agent time budget | 3600 s; tokens: protocol default (PROTOCOL §5) |+| Base image | `ghcr.io/mll-lab-nu/eai-mujoco:0.1.3` |++## Task+MuJoCo Playground `SpotJoystickGaitTracking` (Boston Dynamics Spot) on the same frozen instance as `mujoco_playground_spot_joystick_gait_tracking-privileged`: Make Boston Dynamics Spot follow the joystick command schedule for the whole 20 s episode with the commanded gait (the feet's swing pattern, frequency and height) without falling over.+For 20 s the robot gets a joystick command schedule (5 segments: planar velocity and yaw rate in its own frame) and must track it without falling over. Its feet must follow a pace gait. Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with only+the robot's own sensors and four cameras that follow it.++## Difficulty+Same instance and success check as `mujoco_playground_spot_joystick_gait_tracking-privileged`. In standard mode the agent loses resets, the simulator and+the world state: it sees camera images and proprioception (joints, IMU, foot contacts), acts in joint position chunks,+and gets one episode, so it has to close the loop on the robot's own sensors and recover from its own mistakes without+starting over.++## Reference solution+`solution/oracle_replay.py` streams the privileged reference's rows (`solution/oracle.npy`, 1000 rows, float32-exact)+through the client in `hold` chunks; it uses no privileged information at run time. The service's recorded trajectory+is then exactly the privileged reference, and the episode ends after the 1000 steps of the schedule, with success.++## Verification+The sim service judges the episode live and records every executed control step; the collect hook+(`environment/sim/finalize.sh`) ends the service, replays the recorded trajectory in two fresh processes and writes+`final.json`; `tests/grade.py` (separate sandbox, no network) passes iff the live check succeeded, both replays succeed,+and they end in the same state. Oracle: success, worst segment errors 0.183 m/s and 0.136 rad/s.++## Details+| | |+|---|---|+| Upstream | MuJoCo Playground @ 4057c14 (Apache-2.0): `locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml`; MuJoCo Menagerie @ 1b86ece (`boston_dynamics_spot`); MuJoCo 3.3.7 on the CPU |+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); cameras `track`, `side`, `back`, `top` (they follow the robot) (320 x 240), the feet's kinematics in the trunk frame |+| Resources | 4 CPUs, no GPU (CPU physics, EGL or OSMesa rendering) |++### Provenance+Generated by `scripts/mujoco-playground/generate.py`, as its privileged twin.diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/Dockerfile b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/Dockerfilenew file mode 100644index 0000000000..ed5eee3703--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/Dockerfile@@ -0,0 +1,9 @@+# Standard mode: the agent container has NO simulator and no Playground code, only Python and the client, on the shared+# pinned client base with the shared pins (scripts/eai_standard/client.env, client-requirements.txt).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY client-requirements.txt /tmp/client-requirements.txt+RUN pip install --no-cache-dir -r /tmp/client-requirements.txt+COPY rcb_client.py rcb1.py /opt/tools/+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/client-requirements.txt b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/client-requirements.txtnew file mode 100644index 0000000000..8aa73a968f--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/client-requirements.txt@@ -0,0 +1,11 @@+# Exact pins for what the standard agent container installs (and a verifier, if it installs anything): the closure of+# `pip install requests numpy pillow scipy`, the unpinned line of every standard task at 9eb18edf, resolved on+# 2026-10-01 in CLIENT_IMAGE (client.env: Python 3.12.14, pip 25.0.1). A change here is a shared-files PR.+certifi==2026.7.22+charset-normalizer==3.5.2+idna==3.20+numpy==2.5.3+pillow==12.3.0+requests==2.34.2+scipy==1.18.1+urllib3==2.8.0diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/docker-compose.yaml b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/docker-compose.yamlnew file mode 100644index 0000000000..8ec63c582e--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/docker-compose.yaml@@ -0,0 +1,23 @@+# Standard mode: the simulator runs in the `sim` sidecar (the agent cannot open it); the agent only reaches port 8000.+# No `expose`/`ports` on sim: under Harbor's egress control it shares main's network namespace (localhost:8000).+# CPU only: MuJoCo physics and rendering (EGL when a GPU is there, else OSMesa); no GPU reservation.+# Crash recovery (docs/STANDARD_MODE_2_2.md §13): run.sh exits non-zero when the service crashes, compose restarts the+# container (same container, same /data) and the service replays its journal into the same episode, never a reset.+services:+ main:+ depends_on: [sim]+ sim:+ image: ghcr.io/mll-lab-nu/eai-mujoco:0.1.3+ volumes:+ - ./sim:/srv:ro+ working_dir: /tmp+ command: sh /srv/run.sh+ restart: on-failure:6 # N >= 3 (PROTOCOL §4.1); a resume continues the episode+ environment:+ RCB_INSTANCE: /srv/instance.json+ RCB_TOOL: /srv/rcb_quadruped.py+ RCB_DATA: /data+ RCB_WALL_CLOCK_S: "3600"+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in about a second+ PYTHONPATH: /srv+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction logdiff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/rcb1.py b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/rcb_client.py b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/rcb_client.pynew file mode 100644index 0000000000..aa25b0e050--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/rcb_client.py@@ -0,0 +1,211 @@+"""eai-standard/2.2 client (formerly rcb-limited/2.x) — the only thing a standard-mode agent gets (installed at+/opt/tools/rcb_client.py).++ from rcb_client import Robot+ r = Robot() # finds the service (sim:8000, then localhost:8000), waits for warm-up+ spec = r.spec() # actions, cameras (+ intrinsics, mounting), robot_spec, world, budget, kinematics+ obs = r.get_obs() # current frames: obs.last[cam] -> uint8 (H,W,3); obs.meta["proprio"]+ obs = r.get_obs(depth=True) # + obs.last_depth[cam] -> float32 (H,W) z-depth in metres, 0 = no reading+ res = r.submit("joint_position", A, dt=0.1) # A: (T, dim) rows dt apart; returns the execution video+ res = r.submit("ee_pose", P) # (T, dim) end-effector targets (see spec()["action_types"])+ res.video[cam] -> mp4 bytes res.frames[cam] -> uint8 (N,H,W,3) if video="frames"/"both" res.last[cam]+ res.proprio -> float32 (N, D), one row per frame (names: spec()["proprio_layout"]; res.group("tcp_pose"))+ res.frame_step -> int64 (N,) control step of each frame res.frame_time_s -> float64 (N,) simulated time+ res.extrinsic_cv[cam] -> float64 (N,3,4) world->camera per frame (res.meta["cameras"]: intrinsics + the last frame's pose)+ res = r.submit(..., depth="frames") # + res.depth[cam] -> float32 (N,H,W) metres, one per frame (1 mm steps)+ r.fk(q) # {"ok", "poses": {frame: [x,y,z, quaternion]}}: forward kinematics, no physics+ r.ik({frame: pose}, seed=q) # {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}: inverse kinematics+ res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, frames/<cam>/NNN.jpg, proprio.npy, depth, frame_meta.npz+ obs = r.get_obs(seconds=3, video="both") # hold the last command, let physics run 3 s, return the video+ r.status() # calls, control steps, done, reason, elapsed time++Nothing is put into your context automatically: what you look at, and where you store it, is your code's decision.++If a call fails with a connection error or a 5xx, the service may have crashed; it restarts and resumes the SAME episode+(never a reset) in the state after the last call it completed, which you may not have received. r.wait_ready() waits+until it answers again (resuming replays the episode so far: long episodes can take minutes); then check r.status()+before you continue (spec()["on_service_error"]).+"""+from __future__ import annotations+import json, os, pathlib, sys, time, zlib+import numpy as np+import requests+import rcb1++PROTOCOL = "eai-standard/2.2" # also talks to 2.0 / 2.1 services (they ignore depth and send no frame metadata)+ACCEPTED = ("eai-standard/2.", "rcb-limited/2.") # every 2.x service, under the protocol's current and former name+++class EpisodeOver(RuntimeError):+ pass+++def _decode_depth_frames(p: dict) -> np.ndarray:+ a = np.frombuffer(zlib.decompress(p["data"]), dtype="<u2").reshape(p["shape"])+ return a.astype(np.float32) / 1000.0+++class Result:+ """Decoded RCB1 response: meta (dict), video (cam -> mp4 bytes), frames (cam -> uint8 (N,H,W,3)), last (cam -> uint8+ (H,W,3)), last_depth (cam -> float32 (H,W) m), depth (cam -> float32 (N,H,W) m, one per frame), proprio (float32 (N,D)),+ frame_step (int64 (N,)), frame_time_s (float64 (N,)), extrinsic_cv (cam -> float64 (N,3,4)). save(dir) writes it out;+ show(cam, k) returns one frame; group(name) the proprio columns of one spec()["proprio_groups"] group. stopped: None,+ or why the service stopped the call early ("max_call_wall_s": it ran longer than spec()["max_call_wall_s"]); then+ meta["executed_rows"] < the rows sent, and meta["proprio"]["now"] is where the robot is."""+ def __init__(self, meta: dict, parts: dict, spec: dict | None = None):+ self.meta = meta; self.raw = parts; self._spec = spec or {}; self.stopped = meta.get("stopped")+ self.video, self.frames, self.last, self.last_depth, self.depth, self.extrinsic_cv = {}, {}, {}, {}, {}, {}+ self.proprio = None; self.frame_step = None; self.frame_time_s = None+ for name, p in parts.items():+ kind, data = p["kind"], p["data"]+ if name.startswith("video/") and kind == "mp4": self.video[name[6:]] = data+ elif name.startswith("frames/") and kind == "array": self.frames[name[7:]] = data+ elif name.startswith("last/") and kind == "array": self.last[name[5:]] = data+ elif name.startswith("last_depth/") and kind == "array": self.last_depth[name[11:]] = np.asarray(data, dtype=np.float32)+ elif name.startswith("depth_frames/") and p.get("codec") == "zlib": self.depth[name[13:]] = _decode_depth_frames(p)+ elif name.startswith("depth/") and kind == "array": self.depth[name[6:]] = np.asarray(data, dtype=np.float32) # 2.1 form+ elif name.startswith("extrinsic_cv/") and kind == "array": self.extrinsic_cv[name[13:]] = data+ elif name == "proprio": self.proprio = data+ elif name == "frame_step": self.frame_step = data+ elif name == "frame_time_s": self.frame_time_s = data++ @property+ def done(self) -> bool: return bool(self.meta.get("done"))++ def show(self, camera: str, k: int = -1) -> np.ndarray:+ if camera in self.frames: return self.frames[camera][k]+ return self.last[camera]++ def group(self, name: str, now: bool = False) -> np.ndarray:+ """Columns of proprio group `name` (spec()["proprio_groups"]): (N, n) over the frames, or (n,) of meta["proprio"]["now"]."""+ first, n = self._spec["proprio_groups"][name][:2]+ if now: return np.asarray(self.meta["proprio"]["now"], dtype=np.float64)[first:first + n]+ return self.proprio[:, first:first + n]++ def save(self, out_dir: str) -> str:+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ (out / "meta.json").write_text(json.dumps(self.meta, indent=1))+ for cam, b in self.video.items(): (out / f"{cam}.mp4").write_bytes(b)+ try:+ from PIL import Image+ for cam, img in self.last.items():+ (out / "last").mkdir(exist_ok=True); Image.fromarray(np.ascontiguousarray(img)).save(out / "last" / f"{cam}.jpg", quality=90)+ for cam, arr in self.frames.items():+ d = out / "frames" / cam; d.mkdir(parents=True, exist_ok=True)+ for i, f in enumerate(arr): Image.fromarray(np.ascontiguousarray(f)).save(d / f"{i:03d}.jpg", quality=85)+ except ImportError:+ for cam, img in self.last.items(): np.save(out / f"last_{cam}.npy", img)+ for cam, arr in self.frames.items(): np.save(out / f"frames_{cam}.npy", arr)+ for cam, arr in self.last_depth.items(): np.save(out / f"last_depth_{cam}.npy", arr)+ for cam, arr in self.depth.items(): np.savez_compressed(out / f"depth_{cam}.npz", depth_mm=np.rint(arr * 1000).astype(np.uint16))+ if self.proprio is not None: np.save(out / "proprio.npy", self.proprio)+ if self.frame_step is not None:+ np.savez(out / "frame_meta.npz", frame_step=self.frame_step, frame_time_s=self.frame_time_s,+ **{f"extrinsic_cv/{c}": e for c, e in self.extrinsic_cv.items()})+ return str(out)+++class Robot:+ def __init__(self, base: str | None = None, timeout: float = 600.0):+ cands = [base or os.environ.get("SIM_URL"), "http://sim:8000", "http://localhost:8000"]+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ for b in [c for c in cands if c]:+ try:+ r = requests.get(b + "/spec", timeout=(5, 30))+ if r.status_code == 503: last = "warming up"; break+ r.raise_for_status(); self.base = b; self._spec = r.json()+ if not str(self._spec.get("protocol", "")).startswith(ACCEPTED):+ raise RuntimeError(f"not a 2.x service: protocol {self._spec.get('protocol')!r}")+ return+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(2)+ raise RuntimeError(f"sim service unavailable: {last}")++ def spec(self) -> dict:+ return self._spec++ def _post(self, path: str, meta: dict, parts: list, timeout: float) -> Result:+ body = rcb1.encode(meta, parts)+ r = requests.post(self.base + path, data=body, headers={"Content-Type": "application/x-rcb1"}, timeout=(5, timeout))+ if r.status_code == 409:+ raise EpisodeOver(r.json().get("reason") if r.headers.get("Content-Type", "").startswith("application/json") else "episode finished")+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ m, p = rcb1.decode(r.content); return Result(m, p, self._spec)++ def _common(self, cameras, video_fps, depth, include_depth) -> dict:+ cams = list(cameras) if cameras is not None else self._spec.get("default_cameras")+ if depth is None or depth is False: depth = "frames" if include_depth else "none"+ elif depth is True: depth = "last"+ m = {"cameras": cams, "video_fps": None if video_fps is None else int(video_fps), "depth": depth}+ return {k: v for k, v in m.items() if v is not None}++ def submit(self, action_type: str, actions, dt: float | None = None, interpolate: str = "linear", cameras=None,+ video_fps: int | None = None, video: str = "mp4", depth=None, include_depth: bool = False, note: str = "") -> Result:+ """Execute a chunk of low-level actions (T, dim); see spec()['action_types'] for dims, layouts, limits and semantics.+ dt defaults to one control period, cameras to spec()['default_cameras']; depth: None | True (= "last") | "frames"."""+ a = np.asarray(actions, dtype=np.float32)+ if a.ndim == 1: a = a[None, :]+ if dt is None and self._spec.get("control_hz"): dt = 1.0 / float(self._spec["control_hz"])+ meta = {"type": action_type, "interpolate": interpolate, "video": video, "note": note,+ **({} if dt is None else {"dt": float(dt)}), **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/submit", meta, [rcb1.array_part("actions", a)], timeout=1800)+ if res.stopped:+ print(f"[rcb_client] the service stopped this call early ({res.stopped}): {res.meta.get('executed_rows')} of {len(a)} rows "+ "executed; meta['proprio']['now'] is where the robot is", file=sys.stderr)+ return res++ def get_obs(self, cameras=None, seconds: float = 0.0, video_fps: int | None = None, depth=None, include_depth: bool = False,+ video: str = "frames") -> Result:+ """Current frames (seconds=0, free) or hold the last command and watch for `seconds` (returns the video).+ depth: None | True (= "last": the last frame's depth) | "frames" (one depth map per frame)."""+ meta = {"seconds": float(seconds), "video": video, **self._common(cameras, video_fps, depth, include_depth)}+ res = self._post("/observe", meta, [], timeout=600)+ if res.stopped:+ print(f"[rcb_client] the service stopped this watch early ({res.stopped}) after {res.meta.get('control_steps_watch')} control "+ "steps", file=sys.stderr)+ return res++ def status(self) -> dict:+ r = requests.get(self.base + "/status", timeout=(5, 60)); r.raise_for_status(); return r.json()++ def wait_ready(self, timeout: float = 3600.0) -> dict:+ """After a connection error: wait until the service answers GET /status again (it resumes the same episode after a+ crash), then return the status. Raises RuntimeError after `timeout` seconds."""+ t0 = time.time(); last = None+ while time.time() - t0 < timeout:+ try:+ return self.status()+ except requests.exceptions.RequestException as e:+ last = e+ time.sleep(5)+ raise RuntimeError(f"sim service did not come back within {timeout:.0f} s: {last}")++ def kinematics(self, body: dict) -> dict:+ """POST /kinematics (stateless: never moves the robot, never advances time). Raises ValueError on a bad request."""+ r = requests.post(self.base + "/kinematics", json=body, timeout=(5, 120))+ if r.status_code >= 400:+ try: err = r.json()+ except Exception: err = {"error": r.text[:300]}+ raise ValueError(f"{r.status_code}: {err.get('error')} {err.get('detail', '')}".strip())+ return r.json()++ def fk(self, q, links=None, base_pose=None) -> dict:+ """Forward kinematics: q in spec()['kinematics']['joint_names'] order -> {"ok", "frame", "poses": {link: [x,y,z, quat]}}+ (quaternion order spec()['world']['quaternion_order']; a mobile robot answers in its base frame unless base_pose is given)."""+ body = {"op": "fk", "q": [float(v) for v in np.asarray(q).reshape(-1)]}+ if links is not None: body["links"] = list(links)+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)++ def ik(self, targets: dict, seed=None, base_pose=None, **opts) -> dict:+ """Inverse kinematics: {frame: [x,y,z, quat]} (frames from spec()['kinematics']['ik_targets']) and an optional seed q ->+ {"ok", "q", "error": {frame: {"pos_m", "rot_rad"}}}. opts: tol_pos_m, tol_rot_rad, max_iters."""+ body = {"op": "ik", "targets": {k: [float(v) for v in p] for k, p in targets.items()}, **opts}+ if seed is not None: body["seed"] = [float(v) for v in np.asarray(seed).reshape(-1)]+ if base_pose is not None: body["base_pose"] = [float(v) for v in base_pose]+ return self.kinematics(body)diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/finalize.sh b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/finalize.shnew file mode 100755index 0000000000..02048ddc74--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/finalize.sh@@ -0,0 +1,80 @@+#!/bin/sh+# [[verifier.collect]] hook, run inside the `sim` sidecar once Harbor has stopped the agent's container.+# 1. `rcb_limited.py end` (docs/STANDARD_MODE_2_2.md §13.3): SIGUSR1 to the service, which ends the episode if the+# agent had not (reason "timeout"), writes trajectory.npz + episode.json (live verdict, final-state hash) and exits.+# It exits 2 when final.json already holds the verdict (the service gave up after crashes): that verdict stays.+# 2. replay the trajectory from the frozen instance in TWO fresh processes (`rcb_quadruped.py replay`, the privileged+# verifier's replay): determinism = fresh process == fresh process; live_matches_replay = live == replay.+# 3. merge everything into final.json, the only thing the verifier sandbox grades;+# 4. a third replay renders replay.mp4, after the verdict is on disk (it never changes it).+set -u+DATA="${RCB_DATA:-/data}"; TOOL="${RCB_TOOL:?}"; INSTANCE="${RCB_INSTANCE:?}"+python /srv/rcb_limited.py end "$DATA" --timeout "${RCB_COLLECT_END_TIMEOUT_S:-900}"; rc=$?+if [ "$rc" = 2 ]; then+ echo "[finalize] final.json already holds the verdict; no replay"; exit 0+fi+if [ "$rc" != 0 ]; then+ echo "[finalize] the service did not end and dump the episode in time (rc $rc): an infrastructure failure"+ python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data"); p = os.path.join(d, "final.json")+try:+ out = json.load(open(p))+except Exception:+ out = {}+out.update({"finalized": True, "success": False, "replay_success": False, "deterministic": False, "infra_error": 1,+ "error": "collect hook: the sim service did not end and dump the episode in time"})+json.dump(out, open(p, "w"))+print(json.dumps(out))+PY+ exit 0+fi+replay() { # <n> [--video FILE]: one replay in a fresh process, its result in $DATA/replay<n>.json+ n=$1; shift+ RCB_SESSION_LOG= python "$TOOL" replay --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --out "$DATA/replay$n.json" \+ "$@" > /dev/null 2> "$DATA/replay$n.log"+ echo "[finalize] replay $n exit $?"+}+echo "[finalize] episode dumped; replaying twice in fresh processes"+rm -f "$DATA/replay1.json" "$DATA/replay2.json" "$DATA/replay3.json"+replay 1+replay 2+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+def result(name):+ try:+ v = json.load(open(os.path.join(d, name)))+ except (OSError, ValueError):+ return {}+ return v if isinstance(v, dict) else {}+out = {"replay_success": False, "deterministic": False, "video": False}+try:+ out.update(json.load(open(os.path.join(d, "episode.json"))))+except Exception as exc:+ out["error"] = f"no episode.json: {exc!r}"+a, b = result("replay1.json"), result("replay2.json")+out["replay_success"] = bool(a.get("success")) and bool(b.get("success"))+out["replay_sha"], out["replay_sha2"] = a.get("state_sha"), b.get("state_sha")+out["deterministic"] = bool(a.get("state_sha")) and a.get("state_sha") == b.get("state_sha")+out["live_matches_replay"] = bool(a.get("state_sha")) and a.get("state_sha") == out.get("live_sha")+if not (a.get("state_sha") and b.get("state_sha")): # a replay process died (it crashed or timed out): not the agent's 0+ out.update({"replay_failed": 1, "infra_error": 1,+ "error": "a replay process gave no result (replay1.log / replay2.log)"})+elif not (a.get("instance_ok") and b.get("instance_ok")): # the image no longer builds the frozen start: not the agent's 0+ out.update({"instance_mismatch": 1, "infra_error": 1, "error": "a replay did not start in the instance's t = 0 state"})+out["finalized"] = True+json.dump(out, open(os.path.join(d, "final.json"), "w"))+print(json.dumps(out))+PY+replay 3 --video "$DATA/replay.mp4"+python - <<'PY'+import json, os+d = os.environ.get("RCB_DATA", "/data")+try:+ shown = json.load(open(os.path.join(d, "replay3.json"))).get("video")+except (OSError, ValueError):+ shown = False+if shown:+ p = os.path.join(d, "final.json"); out = json.load(open(p)); out["video"] = True; json.dump(out, open(p, "w"))+PYdiff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/instance.json b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/instance.jsonnew file mode 100644index 0000000000..51247a4914--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/instance.json@@ -0,0 +1,114 @@+{+ "benchmark": "MuJoCo Playground",+ "env": "SpotJoystickGaitTracking",+ "seed": 0,+ "playground": "4057c14",+ "jax": "0.11.2",+ "qpos0": [+ 0.0,+ 0.0,+ 0.46000000834465027,+ 1.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842,+ 0.0,+ 1.0399999618530273,+ -1.7999999523162842+ ],+ "qvel0": [+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0,+ 0.0+ ],+ "commands": [+ {+ "start_step": 0,+ "vx": 0.9938757419586182,+ "vy": 0.37067461013793945,+ "wz": 0.44742894172668457+ },+ {+ "start_step": 201,+ "vx": 0.9238066673278809,+ "vy": -0.3616582155227661,+ "wz": -0.32676148414611816+ },+ {+ "start_step": 402,+ "vx": -0.9385867118835449,+ "vy": 0.09156465530395508,+ "wz": 0.44982028007507324+ },+ {+ "start_step": 603,+ "vx": -0.9596819877624512,+ "vy": -0.29509055614471436,+ "wz": 0.5688352584838867+ },+ {+ "start_step": 804,+ "vx": 0.8662233352661133,+ "vy": 0.1854252815246582,+ "wz": -0.2966732978820801+ }+ ],+ "gait": {+ "type": 2,+ "name": "pace",+ "frequency_hz": 3.6585731506347656,+ "foot_height_m": 0.12916938960552216,+ "phase0": [+ 0.0,+ 3.1415927410125732,+ 0.0,+ 3.1415927410125732+ ],+ "phase_dt": 0.45974987745285034+ },+ "text": "Make Boston Dynamics Spot follow the joystick command schedule for the whole 20 s episode with the commanded gait (the feet's swing pattern, frequency and height) without falling over.",+ "facts": {+ "start_xy_m": [+ 0.0,+ 0.0+ ],+ "start_yaw_deg": 0.0,+ "start_tilt_deg": 0.0,+ "start_imu_height_m": 0.46,+ "reference_rows": 1000,+ "torso_mass_kg": 50.34,+ "reference_worst_lin_err": 0.1827,+ "reference_worst_yaw_err": 0.1358,+ "reference_worst_gait_err": 0.0383+ },+ "state_sha": "53128662ae17",+ "horizon": 1000,+ "selection": {+ "rule": "joystick seeds in order 0, 1, 2, ...; a candidate is skipped when its command schedule is mostly standstill (less than\n half of the episode commands |v_xy| >= 0.3 m/s or |w_z| >= 0.3 rad/s), when its pushes (Barkour) are null or\n weak (peak under 20% of the torso's weight), or when the reference trajectory (oracle.py) fails the task's\n success check; the first remaining seed is the instance.\n getup seeds in order; skipped when Playground's reset did not drop the robot (it starts standing) or when, after the\n settle, the trunk is tilted less than 90 degrees (not fallen over), or when the reference fails; first remaining.\n stand (hand/footstand) seeds in order; skipped when the reference fails; first remaining.",+ "candidates_tried": 1+ }+}\ No newline at end of filediff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/rcb1.py b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/rcb1.pynew file mode 100644index 0000000000..6938c57e38--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/rcb1.py@@ -0,0 +1,83 @@+"""RCB1 — a tiny binary frame for one JSON header plus N raw blobs (videos, image arrays, depth, proprio).++ frame = b"RCB1" | header_len uint32 LE | header JSON (UTF-8) | blob_0 | blob_1 | ...+ header = {"v": 1, "meta": {...}, "parts": [{"name", "kind", "len", ...}, ...]} # blobs in the same order++kinds: "mp4" (fps, n), "jpeg", "array" (dtype, shape; C-order raw bytes), "json" (utf-8), "bytes".+Zero dependencies for bytes/json parts; numpy only when you ask for arrays. Used on both sides (server and client),+over HTTP bodies (Content-Type: application/x-rcb1) and equally usable over a raw socket. `python -m rcb1 unpack f dir`.+"""+from __future__ import annotations+import json, struct, sys, pathlib++MAGIC = b"RCB1"+++def encode(meta: dict, parts: list[tuple[str, str, bytes, dict]]) -> bytes:+ """parts: [(name, kind, blob, extra), ...]; extra carries dtype/shape/fps/n."""+ hdr_parts = []+ for name, kind, blob, extra in parts:+ d = {"name": name, "kind": kind, "len": len(blob)}+ d.update({k: v for k, v in (extra or {}).items() if v is not None})+ hdr_parts.append(d)+ header = json.dumps({"v": 1, "meta": meta, "parts": hdr_parts}, separators=(",", ":")).encode()+ return b"".join([MAGIC, struct.pack("<I", len(header)), header] + [blob for _, _, blob, _ in parts])+++def array_part(name: str, arr, extra: dict | None = None) -> tuple[str, str, bytes, dict]:+ import numpy as np+ a = np.ascontiguousarray(arr)+ return (name, "array", a.tobytes(), {"dtype": str(a.dtype), "shape": list(a.shape), **(extra or {})})+++def decode(buf: bytes, arrays: bool = True) -> tuple[dict, dict]:+ """-> (meta, parts) where parts[name] = {"kind", ..., "data"}; arrays become numpy arrays when arrays=True."""+ if buf[:4] != MAGIC:+ raise ValueError("not an RCB1 frame")+ n = struct.unpack("<I", buf[4:8])[0]+ header = json.loads(buf[8:8 + n].decode()); off = 8 + n+ out = {}+ for p in header["parts"]:+ blob = buf[off:off + p["len"]]; off += p["len"]+ d = dict(p)+ if p["kind"] == "array" and arrays:+ import numpy as np+ d["data"] = np.frombuffer(blob, dtype=np.dtype(p["dtype"])).reshape(p["shape"])+ elif p["kind"] == "json":+ d["data"] = json.loads(blob.decode())+ else:+ d["data"] = blob+ out[p["name"]] = d+ return header.get("meta", {}), out+++def unpack_to_dir(buf: bytes, out_dir: str) -> list[str]:+ """Write a frame's parts as files: mp4/jpeg/bytes verbatim, arrays as .npy, meta as meta.json."""+ import numpy as np+ out = pathlib.Path(out_dir); out.mkdir(parents=True, exist_ok=True)+ meta, parts = decode(buf, arrays=True); written = []+ (out / "meta.json").write_text(json.dumps(meta, indent=1)); written.append("meta.json")+ for name, p in parts.items():+ safe = name.replace("/", "__")+ if p["kind"] == "array":+ f = out / f"{safe}.npy"; np.save(f, p["data"])+ elif p["kind"] == "mp4":+ f = out / f"{safe}.mp4"; f.write_bytes(p["data"])+ elif p["kind"] == "jpeg":+ f = out / f"{safe}.jpg"; f.write_bytes(p["data"])+ elif p["kind"] == "json":+ f = out / f"{safe}.json"; f.write_text(json.dumps(p["data"], indent=1))+ else:+ f = out / f"{safe}.bin"; f.write_bytes(p["data"])+ written.append(f.name)+ return written+++if __name__ == "__main__":+ if len(sys.argv) == 4 and sys.argv[1] == "unpack":+ print("\n".join(unpack_to_dir(open(sys.argv[2], "rb").read(), sys.argv[3])))+ elif len(sys.argv) == 3 and sys.argv[1] == "info":+ meta, parts = decode(open(sys.argv[2], "rb").read(), arrays=False)+ print(json.dumps(meta, indent=1)); [print(n, {k: v for k, v in p.items() if k != "data"}) for n, p in parts.items()]+ else:+ print(__doc__)diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/rcb_limited.py b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/rcb_limited.pynew file mode 100644index 0000000000..1ce1171787--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/rcb_limited.py@@ -0,0 +1,930 @@+"""eai-standard/2.2 (formerly rcb-limited/2.2): the HTTP layer, the protocol helpers and the crash recovery that every+2.2 sim service shares (docs/STANDARD_MODE_2_2.md; the 2.1 base is docs/LIMITED_MODE_PROTOCOL.md).++The source is scripts/eai_standard/rcb_limited.py; the generators copy it unchanged into every standard task's+environment/sim/ (ci_checks/check-tooling-identity.sh). A service keeps its simulator to itself (scene, action+execution, cameras, kinematic model) and hands this module plain callables:++ import rcb_limited as L+ EP = L.Episode(DATA, dim=N, resume="exact") # before the scene is built; "approx" for a nondeterministic simulator+ EP.startup() # start count, back-off after failed starts, startup watchdog+ S = <build the scene>; EP.scene_built() # the watchdog stands down+ def ctrl_step(a, rec): # every executed control step+ S.step(a); stop = EP.journal(a); rec.tick(); return E["done"] or stop+ rec = L.Recorder(cams, every, grab, proprio_row, extrinsics, clock, depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+ rec.tick(force=True) # first frame (before the chunk / watch)+ ...; rec.tick(); ... # after every control step: a frame every `every` steps+ rec.tick(force=True, last=True) # last frame (+ its depth)+ parts = rec.parts(video, fps) # RCB1 parts: video/ frames/ last/ extrinsic_cv/ last_depth/ depth_frames/ depth/ proprio frame_*+ S.record_start()+ EP.begin(state=E, step=S.step, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, start_event={...}, on_end=end_fn)+ L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics,+ status=status, on_submit_error=lambda exc: finish("error"), log=EP.log,+ episode=EP, state_sha=S.state_sha, proprio=proprio_row))++ grab(cams, want_depth) -> ({cam: uint8 (H,W,3)}, {cam: float32 (H,W) z-depth in metres, 0 = no reading})+ extrinsics(cams) -> {cam: (3,4) world -> camera, OpenCV axes (x right, y down, z forward)}+ proprio_row() -> float32 (len(spec["proprio_layout"]),)+ clock() -> int, control steps since the episode start (the frame's step index)+ do_kinematics(req) -> dict; `req` is parse_kinematics(body, spec["kinematics"]); it must never step physics++None of the callables may step physics. check_spec(SPEC) runs in serve(): a service whose /spec misses a 2.2 field, or+carries a field the protocol forbids (segmentation, object identities or sizes, physical parameters), does not start.+Crash recovery (class Episode; PROTOCOL §4.7): every executed control step is journaled, every completed call+checkpointed (rows, state hash, the robot's proprio row); after a crash compose restarts the container and the service+replays the journal and continues the SAME episode, never a reset. `python rcb_limited.py end <data dir>` is the shared+first half of a collect hook."""+from __future__ import annotations+import faulthandler, json, math, os, re, select, signal, socket, sys, tempfile, threading, time, traceback, zlib+from http.server import BaseHTTPRequestHandler, HTTPServer+from typing import Any, Callable++import numpy as np++import rcb1++PROTOCOL = "eai-standard/2.2"+COMPAT = ["rcb-limited/2.0", "rcb-limited/2.1", "eai-standard/2.1"] # requests written for these are served unchanged+MAX_BODY = 64 * 1024 * 1024+MAX_RESP = 256 * 1024 * 1024+DEPTH_MODES = ("none", "last", "frames")+DEPTH_MAX_M = 65.535 # uint16 millimetres; a farther surface reads 0 (no reading)+DEPTH_NOISE = os.environ.get("RCB_DEPTH_NOISE", "off").strip().lower() # off | realsense (as rcb-limited/2.1)+_RNG = np.random.default_rng(int(os.environ.get("RCB_DEPTH_NOISE_SEED", "0")))+PROPRIO_GROUPS_REQUIRED = ("joint_pos", "joint_vel", "gripper_opening", "tcp_pose", "joint_effort")+PART_PREFIXES = ("video/", "frames/", "last/", "last_depth/", "depth_frames/", "depth/", "extrinsic_cv/")+PART_NAMES = ("proprio", "frame_step", "frame_time_s")+++# ---------------------------------------------------------------- depth+def depth_mode(meta: dict) -> str:+ """The request's depth mode: "none" | "last" | "frames" (2.2 field `depth`), or "legacy" for a 2.0/2.1 request that+ sets `include_depth: true` and no `depth` (answered as 2.1 did: `depth/<cam>` float16 (N,H,W) metres)."""+ d = meta.get("depth")+ if d is None or d is False:+ return "legacy" if meta.get("include_depth") is True else "none"+ if d is True:+ return "last"+ if isinstance(d, str) and d in DEPTH_MODES:+ return d+ raise ValueError(f"depth must be one of {'|'.join(DEPTH_MODES)} (got {d!r})")+++def clean_depth(z) -> np.ndarray:+ """float32 z-depth in metres: non-finite, negative and beyond-range pixels read 0 (no reading); the optional+ RCB_DEPTH_NOISE=realsense model (sigma = 2 mm + 2.5 mm * z^2, 1 % dropouts) is applied here, after rendering, so it+ never touches physics."""+ z = np.asarray(z, dtype=np.float32).copy()+ if z.ndim == 3 and z.shape[-1] == 1:+ z = z[..., 0]+ bad = ~np.isfinite(z) | (z <= 0) | (z > DEPTH_MAX_M)+ z[bad] = 0.0+ if DEPTH_NOISE == "realsense":+ valid = z > 0+ z = z + _RNG.normal(0.0, 1.0, z.shape).astype(np.float32) * (0.002 + 0.0025 * z * z)+ z[_RNG.random(z.shape) < 0.01] = 0.0+ z[~valid] = 0.0+ z[(z < 0) | (z > DEPTH_MAX_M)] = 0.0+ return z.astype(np.float32)+++def depth_frames_part(name: str, stack: np.ndarray) -> tuple[str, str, bytes, dict]:+ """(N,H,W) metres -> an RCB1 "bytes" part: zlib of C-order uint16 millimetres (0 = no reading). Clients that do not+ know it keep the raw bytes and ignore it; rcb_client decodes it back to float32 metres."""+ mm = np.rint(np.asarray(stack, dtype=np.float64) * 1000.0)+ mm[(mm < 0) | (mm > 65535)] = 0+ a = np.ascontiguousarray(mm.astype("<u2"))+ return (name, "bytes", zlib.compress(a.tobytes(), 1), {"codec": "zlib", "dtype": "uint16", "shape": list(a.shape), "unit": "mm"})+++def encode_mp4(frames: np.ndarray, fps: int) -> bytes:+ """H.264 mp4 (yuv420p, faststart) of uint8 (N,H,W,3) frames: the same encoding every 2.0 service used."""+ import imageio.v2 as imageio+ with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tf:+ path = tf.name+ try:+ with imageio.get_writer(path, format="FFMPEG", mode="I", fps=fps, codec="libx264", macro_block_size=1,+ output_params=["-movflags", "+faststart", "-pix_fmt", "yuv420p"]) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ return open(path, "rb").read()+ finally:+ try:+ os.unlink(path)+ except OSError:+ pass+++# ---------------------------------------------------------------- recording what the cameras see during one call+class Recorder:+ """Frames of the requested cameras every `every` clock ticks, plus forced first/last frames; for every frame the+ proprio row, the clock (step index), each camera's extrinsics and, if asked, its depth. All arrays share one frame+ axis N: frames/<cam>, the mp4's frames, proprio, frame_step, frame_time_s, extrinsic_cv/<cam>, depth_frames/<cam>."""++ def __init__(self, cameras, every: int, grab: Callable, proprio_row: Callable, extrinsics: Callable, clock: Callable,+ depth: str = "none", clock_hz: float = 1.0):+ if depth not in DEPTH_MODES + ("legacy",):+ raise ValueError(f"bad depth mode {depth!r}")+ self.cams = list(cameras); self.every = max(1, int(every)); self.mode = depth; self.hz = float(clock_hz)+ self._grab, self._prop, self._ext, self._clock = grab, proprio_row, extrinsics, clock+ self.frames: dict = {c: [] for c in self.cams}; self.depth: dict = {c: [] for c in self.cams}+ self.ext: dict = {c: [] for c in self.cams}; self.last_depth: dict = {}+ self.prop: list = []; self.steps: list = []; self.n = 0; self.missing = 0++ def tick(self, force: bool = False, last: bool = False) -> None:+ if force or last or self.n % self.every == 0:+ self._capture(last)+ self.n += 1++ def _capture(self, last: bool) -> None:+ want = self.mode in ("frames", "legacy") or (last and self.mode == "last")+ rgb, dep = self._grab(self.cams, want)+ ext = self._ext(self.cams)+ for c in self.cams:+ img = rgb.get(c)+ if img is not None:+ img = np.ascontiguousarray(np.asarray(img)[..., :3].astype(np.uint8))+ else: # a camera that failed to render: a black frame (sized in parts()) keeps one frame axis+ self.missing += 1+ self.frames[c].append(img)+ e = ext.get(c)+ self.ext[c].append(np.full((3, 4), np.nan) if e is None else np.asarray(e, dtype=np.float64).reshape(3, 4))+ if want:+ d = dep.get(c)+ if d is None:+ d = np.zeros(img.shape[:2] if img is not None else (1, 1), np.float32)+ else:+ d = clean_depth(d)+ if img is not None and d.shape != img.shape[:2]:+ raise RuntimeError(f"depth of {c} is {d.shape}, its RGB {img.shape[:2]}: they must be pixel-aligned")+ if self.mode in ("frames", "legacy"):+ self.depth[c].append(d)+ if last or self.mode == "frames":+ self.last_depth[c] = d+ self.prop.append(np.asarray(self._prop(), dtype=np.float32).reshape(-1))+ self.steps.append(int(self._clock()))++ def parts(self, video: str, fps: int) -> list:+ if self.mode == "last" and not self.last_depth and self.prop: # no last=True tick: the state has not moved since+ _, dep = self._grab(self.cams, True)+ self.last_depth = {c: clean_depth(dep[c]) for c in self.cams if c in dep}+ out = []+ for c in self.cams:+ good = [f for f in self.frames[c] if f is not None]+ hw = good[-1].shape[:2] if good else (1, 1)+ if len(good) < len(self.frames[c]):+ self.frames[c] = [f if f is not None else np.zeros(hw + (3,), np.uint8) for f in self.frames[c]]+ self.depth[c] = [d if d.shape == hw else np.zeros(hw, np.float32) for d in self.depth[c]]+ if c in self.last_depth and self.last_depth[c].shape != hw:+ self.last_depth[c] = np.zeros(hw, np.float32)+ fr = np.stack(self.frames[c]) if self.frames[c] else np.zeros((0, 1, 1, 3), np.uint8)+ if video in ("mp4", "both") and len(fr):+ out.append((f"video/{c}", "mp4", encode_mp4(fr, fps), {"fps": fps, "n": int(len(fr))}))+ if video in ("frames", "both"):+ out.append(rcb1.array_part(f"frames/{c}", fr))+ if len(fr):+ out.append(rcb1.array_part(f"last/{c}", fr[-1]))+ out.append(rcb1.array_part(f"extrinsic_cv/{c}", np.stack(self.ext[c]) if self.ext[c] else np.zeros((0, 3, 4))))+ if self.mode in ("last", "frames") and c in self.last_depth:+ out.append(rcb1.array_part(f"last_depth/{c}", self.last_depth[c]))+ if self.mode == "frames" and self.depth[c]:+ out.append(depth_frames_part(f"depth_frames/{c}", np.stack(self.depth[c])))+ if self.mode == "legacy" and self.depth[c]:+ out.append(rcb1.array_part(f"depth/{c}", np.stack(self.depth[c]).astype(np.float16)))+ out.append(rcb1.array_part("proprio", np.stack(self.prop) if self.prop else np.zeros((0, 0), np.float32)))+ st = np.asarray(self.steps, dtype=np.int64)+ out.append(rcb1.array_part("frame_step", st))+ out.append(rcb1.array_part("frame_time_s", st.astype(np.float64) / self.hz))+ return out+++def encode_response(meta: dict, parts: list, max_bytes: int = MAX_RESP) -> bytes:+ """The RCB1 body; over `max_bytes` the per-frame depth goes first, then the raw frames (mp4, last frames, last+ depth, proprio and the per-frame arrays always stay), and meta["degraded"] says what was dropped."""+ body = rcb1.encode(meta, parts)+ dropped = []+ for prefixes in (("depth_frames/", "depth/"), ("frames/",)):+ if len(body) <= max_bytes:+ break+ keep = [p for p in parts if not p[0].startswith(prefixes)]+ if len(keep) < len(parts):+ parts = keep; dropped += [x.rstrip("/") for x in prefixes]+ body = rcb1.encode({**meta, "degraded": f"response over {max_bytes} bytes: {', '.join(dropped)} dropped"}, parts)+ return body+++# ---------------------------------------------------------------- kinematics+def _vec(x, n: int, what: str) -> list:+ a = np.asarray(x, dtype=np.float64).reshape(-1) if x is not None else None+ if a is None or a.size != n or not np.all(np.isfinite(a)):+ raise ValueError(f"{what} must be {n} finite numbers")+ return a.tolist()+++def _pose(x, what: str) -> list:+ p = _vec(x, 7, what)+ nq = math.sqrt(sum(v * v for v in p[3:]))+ if nq < 1e-6:+ raise ValueError(f"{what}: quaternion has zero norm")+ return p[:3] + [v / nq for v in p[3:]]+++def parse_kinematics(body: dict, kin: dict) -> dict:+ """Validate a /kinematics request against spec["kinematics"] (ValueError -> 400). Returns+ {"op": "fk", "q", "links", "base_pose"} or {"op": "ik", "targets": {frame: pose7}, "seed", "base_pose", "tol_pos_m",+ "tol_rot_rad", "max_iters"}; poses are x y z + a unit quaternion in the spec's order; q follows kin["joint_names"]."""+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object")+ op = body.get("op"); n = len(kin["joint_names"])+ base = None+ if body.get("base_pose") is not None:+ if kin.get("frame") != "base":+ raise ValueError("base_pose is only accepted by a mobile robot (spec kinematics.frame == 'base')")+ base = _pose(body["base_pose"], "base_pose")+ if op == "fk":+ links = body.get("links") or list(kin["links"])+ if not isinstance(links, list) or any(l not in kin["links"] for l in links):+ raise ValueError(f"links must be a list of names from spec kinematics.links: {kin['links']}")+ return {"op": "fk", "q": _vec(body.get("q"), n, "q"), "links": links, "base_pose": base}+ if op == "ik":+ tg = body.get("targets")+ if not isinstance(tg, dict) or not tg or any(k not in kin["ik_targets"] for k in tg):+ raise ValueError(f"targets must map frames from spec kinematics.ik_targets {kin['ik_targets']} to poses")+ ik = kin.get("ik", {})+ seed = None if body.get("seed") is None else _vec(body["seed"], n, "seed")+ tol_p = float(body.get("tol_pos_m", ik.get("tol_pos_m", 0.005)))+ tol_r = float(body.get("tol_rot_rad", ik.get("tol_rot_rad", 0.05)))+ it = int(body.get("max_iters", ik.get("max_iters", 200)))+ if not (1e-5 <= tol_p <= 0.5 and 1e-4 <= tol_r <= 3.2 and 1 <= it <= 5000):+ raise ValueError("tol_pos_m in [1e-5, 0.5], tol_rot_rad in [1e-4, 3.2], max_iters in [1, 5000]")+ return {"op": "ik", "targets": {k: _pose(v, f"targets[{k}]") for k, v in tg.items()}, "seed": seed, "base_pose": base,+ "tol_pos_m": tol_p, "tol_rot_rad": tol_r, "max_iters": it}+ raise ValueError("op must be 'fk' or 'ik'")+++def fk_response(poses: dict, frame: str) -> dict:+ return {"ok": True, "op": "fk", "frame": frame, "poses": {k: [float(v) for v in np.asarray(p, dtype=np.float64).reshape(7)] for k, p in poses.items()}}+++def ik_response(q, ok: bool, errors: dict, frame: str, note: str | None = None) -> dict:+ """errors: {frame: (position error m, rotation error rad)} of the returned q (None / non-finite -> null: no solution)."""+ fin = lambda v: float(v) if v is not None and math.isfinite(float(v)) else None # noqa: E731+ out = {"ok": bool(ok), "op": "ik", "frame": frame, "q": None if q is None else [float(v) for v in np.asarray(q).reshape(-1)],+ "error": {k: {"pos_m": fin(e[0]), "rot_rad": fin(e[1])} for k, e in errors.items()}}+ if note:+ out["note"] = note+ return out+++def quat_angle(q1, q2) -> float:+ """Rotation angle (rad) between two unit quaternions of the same order."""+ d = abs(float(np.dot(np.asarray(q1, dtype=np.float64), np.asarray(q2, dtype=np.float64))))+ return 2.0 * math.acos(min(1.0, d))+++# ---------------------------------------------------------------- /spec self-check+FORBIDDEN_KEY = re.compile(r"mask|segment|semantic(?!s$)|instance_?id|bbox|bounding|categor|object|\bobj_|label|mass|friction|"+ r"restitution|inertia|density|damping|stiffness", re.I)+GAIN_PATHS = ("robot_spec.controller",) # joint drive gains (stiffness, damping) are the robot's own, and allowed there+POSITION_KEY = re.compile(r"(?:^|_)(?:pos|position|positions|pose|poses|origin|location|coords?|coordinates|world|translation)(?:_|$)|"+ r"(?:^|_)cent(?:er|re)s?(?:_|$)|(?:^|_)xyz?$|(?:^|_)(?:top|surface|floor|table|plane|height|elevation)?_?z$", re.I)+WORLD_TEXT = re.compile(r"\bworld\s+[xyz]\s*=", re.I)+COORDS = re.compile(r"\(\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*(?:,\s*-?\d+(?:\.\d+)?\s*)?\)")+++def world_text(s: str) -> bool:+ """A text that gives a world coordinate: a pixel-to-world formula, or a coordinate tuple with a decimal point that is+ not the robot's own pose ("robot base at (0, 0, 1.08)" stays)."""+ return bool(WORLD_TEXT.search(s)) or any("." in m.group(0) and not re.search(r"base|robot|origin", s[max(0, m.start() - 40):m.start()], re.I)+ for m in COORDS.finditer(s))+CONVENTIONS = {"static.floor_z": 0.0} # BEHAVIOR: the floor is the plane z = 0 (the world frame's definition)+++def static_positions(obj: Any, path: str = "static") -> list[str]:+ """Paths in /spec static that say WHERE something is (keys naming positions, heights, centres; texts with world+ coordinates). Names, inventories, sizes and colours may stay in static; positions never (docs § Never provided)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}"+ if POSITION_KEY.search(str(k)) and CONVENTIONS.get(p, object()) != v:+ out.append(p)+ else:+ out += static_positions(v, p)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += static_positions(v, f"{path}[{i}]")+ elif isinstance(obj, str) and world_text(obj):+ out.append(path)+ return out+++SPEC_REQUIRED = ("protocol", "protocol_compat", "simulator", "robot", "task_text", "control_hz", "cameras", "default_cameras",+ "action_types", "proprio_layout", "proprio_groups", "static", "world", "budget", "robot_spec", "kinematics", "depth")+++def forbidden_keys(obj: Any, path: str = "", skip: tuple = ()) -> list[str]:+ """Key paths that name something the protocol never provides (key paths in `skip` are not searched)."""+ out = []+ if isinstance(obj, dict):+ for k, v in obj.items():+ p = f"{path}.{k}" if path else str(k)+ if p in skip:+ continue+ if FORBIDDEN_KEY.search(str(k)) and not (re.search(r"damping|stiffness", str(k), re.I) and p.startswith(GAIN_PATHS)):+ out.append(p)+ out += forbidden_keys(v, p, skip)+ elif isinstance(obj, list):+ for i, v in enumerate(obj):+ out += forbidden_keys(v, f"{path}[{i}]", skip)+ return out+++def check_spec(spec: dict) -> None:+ """Raise if /spec is not a complete 2.2 spec or names anything forbidden (run at startup, before binding :8000)."""+ miss = [k for k in SPEC_REQUIRED if k not in spec]+ if miss:+ raise RuntimeError(f"/spec misses {miss}")+ if spec["protocol"] != PROTOCOL:+ raise RuntimeError(f"/spec protocol {spec['protocol']!r} != {PROTOCOL}")+ bad = forbidden_keys(spec, skip=())+ if bad:+ raise RuntimeError(f"/spec names forbidden fields: {bad}")+ pos = static_positions(spec["static"])+ if pos:+ raise RuntimeError(f"/spec static says where things are (never provided): {pos}")+ lay = spec["proprio_layout"]+ if len(set(lay)) != len(lay):+ raise RuntimeError("proprio_layout names are not unique")+ for g in PROPRIO_GROUPS_REQUIRED:+ if g not in spec["proprio_groups"]:+ raise RuntimeError(f"proprio_groups misses {g}")+ for g, (first, n, _meaning) in spec["proprio_groups"].items():+ if not (0 <= first and first + n <= len(lay)):+ raise RuntimeError(f"proprio group {g} [{first}, +{n}) outside the {len(lay)} columns")+ kin = spec["kinematics"]+ for k in ("endpoint", "joint_names", "frame", "quaternion_order", "links", "tcp_frames", "ee_frames", "ik_targets"):+ if k not in kin:+ raise RuntimeError(f"kinematics misses {k}")+ if any(j not in lay for j in kin["joint_names"]):+ raise RuntimeError("kinematics.joint_names must be proprio_layout columns (the measured joint positions)")+ if any(f not in kin["links"] for f in list(kin["tcp_frames"]) + list(kin["ee_frames"]) + list(kin["ik_targets"])):+ raise RuntimeError("kinematics tcp_frames / ee_frames / ik_targets must be listed in kinematics.links")+ if spec["proprio_groups"]["tcp_pose"][1] != 7 * len(kin["tcp_frames"]):+ raise RuntimeError("proprio group tcp_pose must hold 7 columns per kinematics.tcp_frames entry")+ for c, cam in spec["cameras"].items():+ for k in ("rgb", "depth", "mounted", "resolution", "intrinsic_cv", "mount"):+ if k not in cam:+ raise RuntimeError(f"cameras.{c} misses {k}")+ if cam["mount"].get("type") not in ("static", "link"):+ raise RuntimeError(f"cameras.{c}.mount.type must be static|link")+ if any(c not in spec["cameras"] for c in spec["default_cameras"]):+ raise RuntimeError("default_cameras must be cameras")+++# ---------------------------------------------------------------- crash recovery (PROTOCOL §4.7; docs/STANDARD_MODE_2_2.md)+MAX_RESUMES = int(os.environ.get("RCB_MAX_RESUMES", "2"))+STARTUP_TIMEOUT_S = float(os.environ.get("RCB_STARTUP_TIMEOUT_S", "900")) # a task with a slower scene build sets more+MAX_CALL_WALL_S = float(os.environ.get("RCB_MAX_CALL_WALL_S", "900")) # < the client's 1800 s /submit read timeout+RESUME_MAX_DEV_M = float(os.environ.get("RCB_RESUME_MAX_DEV_M", "0.05")) # approx resumes: the gross-divergence guard+ON_SERVICE_ERROR = ("a connection error means the service crashed: it restarts and resumes the SAME episode (never a reset) "+ "in the state after the last call it completed, which you may not have received. Wait until GET /status "+ "answers again (rcb_client: Robot.wait_ready(); resuming replays the episode so far, which can take "+ "minutes in a long episode, and the wall clock keeps running), then check calls and control_steps "+ "before you continue. A 500 means the simulator failed: the episode is over (reason \"error\"). A call "+ "that runs longer than max_call_wall_s seconds stops at the next control step and returns what it "+ "executed (meta.stopped, executed_rows).")+++def _jsonable(v: Any) -> Any:+ if isinstance(v, np.ndarray):+ return v.tolist()+ if isinstance(v, (np.floating, np.integer, np.bool_)):+ return v.item()+ if isinstance(v, (list, tuple)):+ return [_jsonable(x) for x in v]+ if isinstance(v, dict):+ return {str(k): _jsonable(x) for k, x in v.items()}+ return v+++def _peer_closed(sock) -> bool:+ """True when the client of an HTTP request has closed its connection (it gave up on the call): the socket reads as+ end-of-file. A client never sends anything while it waits for the response, so readable means closed."""+ try:+ r, _, _ = select.select([sock], [], [], 0)+ return bool(r) and sock.recv(1, socket.MSG_PEEK) == b""+ except (OSError, ValueError):+ return True+++def _read_json(path: str) -> dict:+ try:+ with open(path) as f:+ d = json.load(f)+ return d if isinstance(d, dict) else {}+ except (OSError, ValueError):+ return {}+++def _write_json(path: str, obj: dict) -> None:+ tmp = f"{path}.{os.getpid()}.tmp"+ with open(tmp, "w") as f:+ json.dump(obj, f)+ os.replace(tmp, path)+++def final_verdict(data: str) -> dict | None:+ """final.json if it already holds a verdict that nothing may overwrite: the grading result (finalized, with+ `deterministic`) or the end of an episode the service gave up after crashes (`gave_up`)."""+ fin = _read_json(os.path.join(data, "final.json"))+ if fin.get("finalized") and (fin.get("gave_up") or fin.get("deterministic") is not None):+ return fin+ return None+++class Episode:+ """Crash-safe episode bookkeeping, the same rules as the RoboTwin and MuJoCo services (PROTOCOL §4.7):++ - startup(): before the scene is built. One line in startups.jsonl; a back-off of min(120, 20 (n - 1)) s when the+ earlier starts never began an episode (they crashed while building, e.g. GPU memory taken by other trials); the+ startup watchdog (faulthandler, a C thread: it fires even when a native scene build holds the GIL) dumps every+ thread's traceback and exits 1 after RCB_STARTUP_TIMEOUT_S, so compose restarts the build. Until begin() a SIGUSR1+ (the collect hook's "the agent phase is over") is only remembered.+ - journal(row): every executed control step (the exact row given to the simulator's step) goes to journal.f64.+ - checkpoint(): after every completed call (the HTTP layer calls it): the journal is flushed, then the call's+ checkpoint is logged in episode.jsonl (rows, control steps, state hash, the robot's proprio row, `persist` keys).+ - begin(): a fresh episode, or after a crash (run.sh exits non-zero, compose restarts the container, `restart:+ on-failure:N`) the SAME episode resumed: the journal is replayed up to the last checkpoint, the journal truncated+ there (the call that was in flight is lost as a whole: its caller got an error, not a result), the state hash+ compared, the service's counters restored; the wall clock keeps running from the first start.+ - Resume check, by the simulator's determinism class: `exact` (bit-exact in a fresh process): the hash must match,+ else the episode ends `resume_failed` (infra_error). `approx` (a simulator declared nondeterministic): a+ mismatch is recorded (resume_state_mismatch, and the robot's deviation from its checkpointed proprio: joint_pos and+ tcp_pose) and the episode continues, unless a TCP is more than RCB_RESUME_MAX_DEV_M from where it was+ (resume_failed, infra_error). The verdict never comes from the live state but from fresh replays of the complete+ recorded trajectory, so continuing cannot raise a score.+ - More than RCB_MAX_RESUMES crashes end the episode: `sim_crashed_on_call` if every crash happened while a call was+ being served (the agent's failure), else `sim_crashed` (infra_error = 1). A verdict already on disk is never+ overwritten; the service then idles with its PID file for the collect hook.+ - Per call, two bounds keep one call from holding the single-threaded service: a call that runs longer than+ max_call_wall_s, or whose client has hung up, stops at the next control step and returns what it executed+ (journal() returns True; meta.stopped says why). Neither bounds the episode: the wall clock is its only budget."""++ def __init__(self, data: str, dim: int, resume: str = "exact", persist: tuple = ()):+ if resume not in ("exact", "approx"):+ raise ValueError("resume must be 'exact' or 'approx'")+ self.data, self.dim, self.resume_class, self.persist = data, int(dim), resume, tuple(persist)+ os.makedirs(data, exist_ok=True)+ p = lambda n: os.path.join(data, n) # noqa: E731+ self.f_events, self.f_journal, self.f_final, self.f_pid, self.f_startups = (+ p("episode.jsonl"), p("journal.f64"), p("final.json"), p("server.pid"), p("startups.jsonl"))+ self.rows = 0 # control steps executed in this episode (journaled)+ self.max_call_wall_s = MAX_CALL_WALL_S+ self.n_startups = 0; self.resumes = 0; self.mismatches = 0; self.max_tcp_dev = 0.0; self.max_joint_dev = 0.0+ self._jf = None; self._call: dict | None = None; self._ids = 0; self._ck: tuple | None = None+ self._on_end: Callable | None = None; self._end_pending = False++ # ---- startup+ def startup(self) -> None:+ signal.signal(signal.SIGUSR1, self._usr1)+ try:+ os.remove(self.f_pid) # a PID file from before a crash would send the collect hook to a dead process+ except OSError:+ pass+ with open(self.f_startups, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid()}) + "\n")+ with open(self.f_startups) as f:+ self.n_startups = sum(1 for line in f if line.strip())+ if self.n_startups > 1 and not any(e.get("ev") == "start" for e in self.events()):+ time.sleep(min(120.0, 20.0 * (self.n_startups - 1)))+ faulthandler.dump_traceback_later(STARTUP_TIMEOUT_S, exit=True)++ def scene_built(self) -> None:+ faulthandler.cancel_dump_traceback_later() # the scene exists: a resume replay may take long, it is not a hang++ def _usr1(self, *_):+ if self._on_end is None:+ self._end_pending = True+ else:+ threading.Thread(target=self._on_end, daemon=True).start()++ # ---- the record+ def log(self, ev: dict) -> None:+ with open(self.f_events, "a") as f:+ f.write(json.dumps(_jsonable({"ts": time.time(), **ev})) + "\n")++ def events(self) -> list:+ out = []+ try:+ with open(self.f_events) as f:+ for line in f:+ try:+ out.append(json.loads(line))+ except ValueError: # a line cut by a crash+ pass+ except OSError:+ pass+ return [e for e in out if isinstance(e, dict)]++ def journal(self, row) -> bool:+ """One executed control step. True: the call in progress must stop at this step boundary (meta.stopped)."""+ a = np.asarray(row, dtype=np.float64).reshape(-1)+ if a.size != self.dim:+ raise ValueError(f"journal rows have {self.dim} entries, got {a.size}")+ if self._jf is None:+ self._jf = open(self.f_journal, "ab")+ self._jf.write(a.tobytes()); self.rows += 1+ c = self._call+ if c is None:+ return False+ if c["stopped"] is None:+ now = time.monotonic()+ if now - c["t0"] > self.max_call_wall_s:+ c["stopped"] = "max_call_wall_s"+ elif c["sock"] is not None and now - c["polled"] >= 0.2:+ c["polled"] = now+ if _peer_closed(c["sock"]):+ c["stopped"] = "client_disconnected"+ return c["stopped"] is not None++ @property+ def stopping(self) -> bool:+ """The call in progress must stop (adapters whose loops test E["done"] test this too)."""+ return bool(self._call and self._call["stopped"])++ @property+ def stop_reason(self) -> str | None:+ return self._call["stopped"] if self._call else None++ def call_begin(self, path: str, sock=None) -> int:+ self._ids += 1+ if path != "/kinematics":+ self._call = {"id": self._ids, "t0": time.monotonic(), "sock": sock, "polled": 0.0, "stopped": None}+ self.log({"ev": "call_begin", "id": self._ids, "path": path})+ return self._ids++ def call_end(self, cid: int, path: str, **extra) -> None:+ self.log({"ev": "call_end", "id": cid, "path": path, **extra})+ if path != "/kinematics":+ self._call = None++ def checkpoint(self, state: dict, state_sha: Callable | None, proprio: Callable | None) -> None:+ if self._jf is not None:+ self._jf.flush() # the rows reach the file before the checkpoint that counts them+ if self._ck is not None and self._ck[0] == self.rows:+ sha, pr = self._ck[1], self._ck[2] # no physics since the last checkpoint+ else:+ try:+ sha = state_sha() if state_sha else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); sha = None+ pr = self._proprio_row(proprio)+ self._ck = (self.rows, sha, pr)+ self.log({"ev": "checkpoint", "call": int(state.get("calls") or 0), "step": int(state.get("step") or 0),+ "control_steps": self.rows, "success": bool(state.get("success")), "done": bool(state.get("done")),+ "reason": state.get("reason"), "state_sha": sha, "proprio": pr,+ **({"persist": {k: state.get(k) for k in self.persist}} if self.persist else {})})++ @staticmethod+ def _proprio_row(proprio: Callable | None) -> list | None:+ try:+ return [round(float(v), 6) for v in np.asarray(proprio(), dtype=np.float64).reshape(-1)] if proprio else None+ except Exception: # noqa: BLE001+ traceback.print_exc(); return None++ def final_fields(self) -> dict:+ """Crash-recovery fields for final.json / episode.json (all numeric, for reward.json)."""+ return {"sim_startups": self.n_startups, "resumes": self.resumes, "resume_state_mismatch": int(self.mismatches > 0),+ "resume_max_tcp_dev_m": round(self.max_tcp_dev, 6), "resume_max_joint_dev": round(self.max_joint_dev, 6)}++ # ---- start or resume+ def begin(self, *, state: dict, step: Callable, state_sha: Callable, proprio: Callable, spec: dict,+ start_event: dict | None = None, on_end: Callable | None = None) -> bool:+ """Start the episode, or resume it after a crash. `step(row)` executes one journaled row on the simulator (the+ recorder on, no rendering needed); `on_end` is what the collect hook's SIGUSR1 runs (in a thread). Returns True+ if the episode was resumed."""+ try: # a line cut by the crash must not swallow the next record+ with open(self.f_events, "rb+") as f:+ f.seek(0, os.SEEK_END)+ if f.tell():+ f.seek(-1, os.SEEK_END)+ if f.read(1) != b"\n":+ f.write(b"\n")+ except OSError:+ pass+ ev = self.events()+ starts = [e for e in ev if e.get("ev") == "start"]+ if not starts:+ try:+ os.remove(self.f_journal)+ except OSError:+ pass+ sha = state_sha()+ self._ck = (0, sha, self._proprio_row(proprio))+ self.log({**(start_event or {}), "ev": "start", "state_sha": sha, "protocol": PROTOCOL, "resume": self.resume_class,+ "journal_dim": self.dim})+ state["t0"] = time.time()+ self._arm(on_end)+ return False+ tries = [e for e in ev if e.get("ev") == "resuming"] # earlier resumes (a crash during one counts too)+ resumed = [e for e in ev if e.get("ev") == "resumed"]+ self.resumes = len(tries) # the record so far, also for a give-up below (final_fields)+ self.mismatches = sum(1 for e in resumed if e.get("exact") is False)+ self.max_tcp_dev = max([float(e.get("tcp_dev_m") or 0) for e in resumed] + [0.0])+ self.max_joint_dev = max([float(e.get("joint_dev") or 0) for e in resumed] + [0.0])+ if final_verdict(self.data):+ self.give_up("restarted after finalize", infra=False)+ k = max(i for i, e in enumerate(ev) if e.get("ev") in ("start", "resuming", "resumed"))+ tail = ev[k + 1:]+ in_call = bool({e.get("id") for e in tail if e.get("ev") == "call_begin"} - {e.get("id") for e in tail if e.get("ev") == "call_end"})+ if len(tries) >= MAX_RESUMES:+ agent = sum(1 for e in tries if e.get("crashed_in_call")) + int(in_call) == len(tries) + 1+ self.give_up("sim_crashed_on_call" if agent else "sim_crashed", infra=not agent)+ self.log({"ev": "resuming", "attempt": len(tries) + 1, "crashed_in_call": in_call,+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self.resumes = len(tries) + 1 # this attempt counts, whether or not it succeeds+ cps = [e for e in ev if e.get("ev") == "checkpoint"]+ last = cps[-1] if cps else {"call": 0, "step": 0, "control_steps": 0, "success": False, "state_sha": starts[0].get("state_sha")}+ n = int(last.get("control_steps") or 0)+ try:+ R = np.fromfile(self.f_journal, dtype=np.float64)+ except (OSError, ValueError):+ R = np.zeros(0)+ if R.size < n * self.dim:+ self.give_up("resume_failed: journal shorter than the log", infra=True)+ R = R[: n * self.dim].reshape(n, self.dim)+ t = time.time()+ for row in R:+ step(row)+ replay_s = time.time() - t+ R.tofile(self.f_journal) # drop the rows of the call that was in flight+ self.rows = n+ sha = state_sha(); want = last.get("state_sha")+ exact = None if want is None else sha == want+ dev = self._deviation(last.get("proprio"), proprio, spec)+ if exact is False: # recorded first: a give-up below reports it too+ self.mismatches += 1+ self.max_tcp_dev = max(self.max_tcp_dev, dev.get("tcp_m") or 0.0)+ self.max_joint_dev = max(self.max_joint_dev, dev.get("joint") or 0.0)+ if self.resume_class == "exact":+ self.give_up("resume_failed: replayed state differs from the logged one", infra=True)+ if dev.get("tcp_m") is not None and dev["tcp_m"] > RESUME_MAX_DEV_M:+ self.give_up(f"resume_failed: a replayed TCP is {dev['tcp_m']:.3f} m from its checkpoint (> {RESUME_MAX_DEV_M} m)", infra=True)+ state["calls"] = int(last.get("call") or 0); state["step"] = int(last.get("step") or 0)+ if "success" in state:+ state["success"] = bool(last.get("success"))+ for key, v in (last.get("persist") or {}).items():+ state[key] = v+ state["t0"] = float(starts[0]["ts"])+ ended = [e for e in ev if e.get("ev") == "end" and int(e.get("control_steps") or 0) <= n] # not the lost call's+ if ended:+ state["done"] = True; state["reason"] = ended[-1].get("reason"); state["t_end"] = float(ended[-1]["ts"])+ state["episode_control_steps"] = int(ended[-1].get("control_steps") or n)+ self._ck = (n, sha, self._proprio_row(proprio)) # the replayed state's row (it may differ under approx)+ self.log({"ev": "resumed", "attempt": self.resumes, "control_steps": n, "calls": state["calls"], "state_sha": sha,+ "logged_sha": want, "exact": exact, "class": self.resume_class, "tcp_dev_m": dev.get("tcp_m"),+ "joint_dev": dev.get("joint"), "crashed_in_call": in_call, "replay_s": round(replay_s, 1),+ "downtime_s": round(time.time() - float(ev[-1].get("ts") or time.time()), 1)})+ self._arm(on_end)+ return True++ @staticmethod+ def _deviation(ref, proprio: Callable, spec: dict) -> dict:+ """The replayed robot against its checkpointed proprio row: max |joint_pos| difference (rad or m) and the largest+ TCP position error (m) over the tcp_pose frames (7 columns each: x y z + quaternion)."""+ if ref is None:+ return {}+ try:+ now = np.asarray(proprio(), dtype=np.float64).reshape(-1); ref = np.asarray(ref, dtype=np.float64).reshape(-1)+ except Exception: # noqa: BLE001+ return {}+ if now.shape != ref.shape:+ return {}+ g, out = spec.get("proprio_groups") or {}, {}+ if "joint_pos" in g:+ f, n = int(g["joint_pos"][0]), int(g["joint_pos"][1])+ out["joint"] = float(np.max(np.abs(now[f:f + n] - ref[f:f + n]))) if n else 0.0+ if "tcp_pose" in g:+ f, n = int(g["tcp_pose"][0]), int(g["tcp_pose"][1]); m = n // 7+ d = (now[f:f + 7 * m] - ref[f:f + 7 * m]).reshape(m, 7)[:, :3]+ out["tcp_m"] = float(np.max(np.linalg.norm(d, axis=1))) if m else 0.0+ return out++ def _arm(self, on_end: Callable | None) -> None:+ self._on_end = on_end+ signal.signal(signal.SIGUSR1, self._usr1)+ if on_end is not None and self._end_pending:+ self._end_pending = False+ threading.Thread(target=on_end, daemon=True).start()++ def give_up(self, reason: str, infra: bool) -> None:+ """End the trial's episode without a new one (never a reset): log it, write the verdict unless one is on disk,+ leave the PID file for the collect hook, and idle until the container is removed."""+ faulthandler.cancel_dump_traceback_later()+ self.log({"ev": "restart_refused", "reason": reason})+ if not final_verdict(self.data):+ fin = _read_json(self.f_final)+ fin.update({"success": False, "done": True, "reason": reason, "finalized": True, "gave_up": True, "protocol": PROTOCOL,+ **self.final_fields(), **({"infra_error": 1} if infra else {})})+ _write_json(self.f_final, fin)+ with open(self.f_pid, "w") as f:+ f.write(str(os.getpid()))+ signal.signal(signal.SIGUSR1, lambda *_: None)+ print(f"[{PROTOCOL}] restart refused: {reason}", flush=True)+ while True:+ time.sleep(3600)+++# ---------------------------------------------------------------- the HTTP layer+class Service:+ """What a sim service hands to serve(): spec (dict), lock, state (the service's E dict: done, reason, exiting, error),+ submit(meta, actions) and observe(meta) -> (meta_out, rcb1 parts), kinematics(req) -> dict, status() -> dict,+ on_submit_error(exc) (a simulator error in /submit or /observe: it ends the episode, reason "error"), log(event dict),+ and for crash recovery the Episode with the simulator's state_sha() and proprio row()."""++ def __init__(self, *, spec: dict, lock, state: dict, submit: Callable, observe: Callable, kinematics: Callable,+ status: Callable, on_submit_error: Callable, log: Callable, max_resp: int = MAX_RESP,+ episode: Episode | None = None, state_sha: Callable | None = None, proprio: Callable | None = None):+ self.spec, self.lock, self.state, self.submit, self.observe = spec, lock, state, submit, observe+ self.kinematics, self.status, self.on_submit_error, self.log, self.max_resp = kinematics, status, on_submit_error, log, max_resp+ self.episode, self.state_sha, self.proprio = episode, state_sha, proprio+ self.kin_calls = 0+++def make_handler(svc: Service):+ class H(BaseHTTPRequestHandler):+ def _send(self, code: int, ctype: str, body: bytes) -> None:+ try:+ self.send_response(code); self.send_header("Content-Type", ctype); self.send_header("Content-Length", str(len(body)))+ self.end_headers(); self.wfile.write(body)+ except (BrokenPipeError, ConnectionResetError): # the client hung up (its call was abandoned)+ pass++ def _json(self, code: int, obj: dict) -> None:+ self._send(code, "application/json", json.dumps(obj).encode())++ def _rcb1(self, meta: dict, parts: list) -> None:+ self._send(200, "application/x-rcb1", encode_response(meta, parts, svc.max_resp))++ def log_message(self, *a):+ pass++ def _body(self):+ try:+ n = int(self.headers.get("Content-Length", 0))+ except ValueError:+ raise ValueError("bad Content-Length")+ if n > MAX_BODY:+ raise ValueError("request too large")+ raw = self.rfile.read(n) if n else b""+ if raw[:4] == rcb1.MAGIC:+ return rcb1.decode(raw)+ body = json.loads(raw or b"{}")+ if not isinstance(body, dict):+ raise ValueError("body must be a JSON object or an RCB1 frame")+ return body, {}++ def do_GET(self):+ if self.path == "/spec":+ return self._json(200, svc.spec)+ if self.path == "/status":+ st = svc.status()+ return self._json(200, {**st, "resumes": svc.episode.resumes} if svc.episode else st)+ return self._json(404, {"error": "no such endpoint"})++ def do_POST(self):+ if self.path not in ("/submit", "/observe", "/kinematics"):+ return self._json(404, {"error": "no such endpoint"})+ try:+ meta, parts = self._body()+ except Exception as exc: # noqa: BLE001+ return self._json(413 if "too large" in str(exc) else 400, {"error": str(exc)[:200]})+ E, ep = svc.state, svc.episode+ if self.path == "/kinematics": # stateless: never steps physics, never waits for the episode lock+ cid = ep.call_begin(self.path) if ep else 0+ try:+ req = parse_kinematics(meta, svc.spec["kinematics"])+ out = svc.kinematics(req); svc.kin_calls += 1+ except ValueError as exc:+ return self._json(400, {"error": str(exc)[:300]})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); return self._json(500, {"error": "kinematics error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ ep.call_end(cid, self.path)+ return self._json(200, out)+ with svc.lock:+ if E.get("exiting") or (self.path == "/submit" and E.get("done")):+ return self._json(409, {"error": "episode finished", "reason": E.get("reason")})+ cid = ep.call_begin(self.path, self.connection) if ep else 0+ rows0 = ep.rows if ep else 0+ out = blobs = err = None; stopped = None+ try:+ if self.path == "/submit":+ A = np.asarray(parts["actions"]["data"] if "actions" in parts else meta.get("actions", []), dtype=np.float64)+ out, blobs = svc.submit(meta, A)+ else:+ out, blobs = svc.observe(meta)+ except ValueError as exc:+ err = (400, {"error": str(exc)})+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(); E["error"] = repr(exc); svc.log({"ev": "error", "path": self.path, "error": repr(exc)})+ try:+ svc.on_submit_error(exc) # PROTOCOL §4.6: a simulator error ends the episode (reason "error")+ except Exception: # noqa: BLE001+ traceback.print_exc()+ err = (500, {"error": "simulator error", "detail": repr(exc)[:200]})+ finally:+ if ep:+ stopped = ep.stop_reason+ if err is None or ep.rows != rows0:+ try:+ ep.checkpoint(E, svc.state_sha, svc.proprio)+ except Exception: # noqa: BLE001+ traceback.print_exc()+ ep.call_end(cid, self.path, **({"stopped": stopped} if stopped else {}))+ if err is not None:+ return self._json(*err)+ return self._rcb1({**out, "stopped": stopped}, blobs)+ return H+++def serve(svc: Service, port: int = 8000) -> None:+ """Check the spec, then serve forever (one request at a time, as every 2.x service)."""+ svc.spec.setdefault("on_service_error", ON_SERVICE_ERROR)+ if svc.episode is not None:+ svc.spec.setdefault("max_call_wall_s", svc.episode.max_call_wall_s)+ check_spec(svc.spec)+ HTTPServer(("0.0.0.0", port), make_handler(svc)).serve_forever()+++# ---------------------------------------------------------------- the collect hook's first half+def _alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ try: # a zombie (exited, not yet reaped) counts as gone+ with open(f"/proc/{pid}/stat") as f:+ return f.read().rsplit(")", 1)[-1].split()[0] != "Z"+ except OSError:+ return True+++def end_episode(data: str, timeout: float = 21600.0, wait_key: str | None = None, resend_s: float = 30.0) -> int:+ """Tell the service that the agent phase is over and wait until it has ended the episode. The service may be+ resuming after a crash (no PID file until it is ready again), so there is no fixed start-up wait, and a signal goes+ only to the process that wrote the newest line of startups.jsonl (its SIGUSR1 handler is installed by then).+ Returns 2: final.json already holds the verdict (the service gave up after crashes, or graded in-process; with+ `wait_key`, also waits for that final.json key, e.g. video_done): keep it, run no replays.+ Returns 0: the service dumped the episode (episode.json) and exited: the hook replays it next.+ Returns 1: timed out."""+ t0, sent = time.time(), 0.0+ f_pid, f_dump, f_starts = (os.path.join(data, n) for n in ("server.pid", "episode.json", "startups.jsonl"))+ while time.time() - t0 < timeout:+ fin = final_verdict(data)+ if fin is not None:+ if not wait_key or fin.get(wait_key) or fin.get("gave_up"):+ return 2+ time.sleep(2); continue+ try:+ with open(f_pid) as f:+ pid = int(f.read().strip())+ except (OSError, ValueError):+ pid = None+ try:+ with open(f_starts) as f:+ cur = json.loads([x for x in f if x.strip()][-1]).get("pid")+ except (OSError, ValueError, IndexError):+ cur = None # a service without Episode.startup(): signal what the PID file names+ if pid is not None and (cur is None or pid == cur):+ if not _alive(pid):+ if os.path.exists(f_dump):+ return 0+ elif time.time() - sent >= resend_s:+ try:+ os.kill(pid, signal.SIGUSR1); sent = time.time()+ except OSError:+ pass+ time.sleep(2)+ return 1+++if __name__ == "__main__":+ a = sys.argv[1:]+ if len(a) >= 2 and a[0] == "end":+ wk = a[a.index("--wait-key") + 1] if "--wait-key" in a else None+ to = float(a[a.index("--timeout") + 1]) if "--timeout" in a else 21600.0+ rc = end_episode(a[1], timeout=to, wait_key=wk)+ print({0: "[collect] episode dumped by the service", 1: "[collect] timed out waiting for the service",+ 2: "[collect] final.json already holds the verdict"}[rc], flush=True)+ sys.exit(rc)+ if len(a) == 2 and a[0] == "final-verdict":+ fin = final_verdict(a[1])+ print(json.dumps(fin) if fin else "no final verdict")+ sys.exit(0 if fin else 1)+ print("usage: rcb_limited.py end <data dir> [--wait-key KEY] [--timeout S] | final-verdict <data dir>")+ sys.exit(2)diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/rcb_quadruped.py b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/rcb_quadruped.pynew file mode 100644index 0000000000..159513a5fd--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/rcb_quadruped.py@@ -0,0 +1,517 @@+"""rcb_quadruped — MuJoCo Playground's quadruped locomotion tasks in plain MuJoCo for robot_coding_bench.++Scenes = MuJoCo Playground's `locomotion/<robot>/xmls` (Apache-2.0, @4057c14) with the robots from MuJoCo Menagerie+(@1b86ece, the commit Playground pins), assembled the way Playground's `get_assets()` does; joint drive gains as+Playground's environments set them. Physics on the CPU (bit-exact replay); control 50 Hz.++The instance (instance.json) freezes one episode as Playground's own `reset` draws it with a seed: the robot's start+state and, for the joystick tasks, the command schedule Playground's command process draws over the episode. Playground+only has shaped RL rewards and a termination rule; success is defined here from them (see `check`):++ joystick every control step of the schedule is executed (T = horizon), the robot never meets Playground's termination+ rule (the trunk's up axis pointing below the horizon), and in every command segment, after its first+ SETTLE_STEPS steps, the mean planar velocity error |v_xy - cmd_xy| (the IMU's velocimeter, trunk frame) is at+ most LIN_TOL m/s and the mean yaw-rate error |w_z - cmd_wz| (the IMU's gyro) at most YAW_TOL rad/s.+ getup the trajectory ends with HOLD_STEPS control steps in a row in which the trunk is upright (tilt at most+ TILT_MAX_DEG) and the IMU at least `min_imu_height` m above the floor, within the horizon (Go1: 0.22 m; it+ stands at 0.255-0.26 m with Playground's gains, Playground's reward aims at 0.275 m, lying down is below 0.15 m).++trajectory = (T, 12) joint position targets (rad), one row per control step (1/50 s), in the actuator order+`s.joint_names`; values outside the actuator ranges are clipped (MuJoCo clamps them anyway).+"""+from __future__ import annotations++import hashlib+import json+import os+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+++def _pick_gl() -> None:+ """Rendering backend: EGL (GPU) if it works here, else OSMesa (CPU); checked once, before mujoco is imported."""+ if os.environ.get("RCB_MUJOCO_GL"):+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = os.environ["RCB_MUJOCO_GL"]+ return+ if os.environ.get("_RCB_GL_CHECKED"):+ return+ import subprocess+ probe = ("import mujoco; m = mujoco.MjModel.from_xml_string('<mujoco><worldbody><geom size=\\'.1\\'/></worldbody></mujoco>'); "+ "d = mujoco.MjData(m); mujoco.mj_forward(m, d); r = mujoco.Renderer(m, 240, 320); r.update_scene(d); r.render(); r.render()")+ try:+ ok = subprocess.run([sys.executable, "-c", probe], env={**os.environ, "MUJOCO_GL": "egl", "PYOPENGL_PLATFORM": "egl"},+ capture_output=True, timeout=60).returncode == 0+ except Exception:+ ok = False+ gl = "egl" if ok else "osmesa"+ os.environ["MUJOCO_GL"] = os.environ["PYOPENGL_PLATFORM"] = gl+ os.environ["_RCB_GL_CHECKED"] = gl+++_pick_gl()++ROOT = Path(os.environ.get("RCB_MJ_ROOT", "/opt/rcb_mj"))+CONTROL_DT = 0.02+N = 12+# joystick success+SETTLE_STEPS = 25 # the first 0.5 s of every command segment is not scored (the gait changes over)+LIN_TOL = 0.2 # m/s, mean |v_xy - cmd_xy| per segment+YAW_TOL = 0.3 # rad/s, mean |w_z - cmd_wz| per segment+# getup success+HOLD_STEPS = 25 # 0.5 s+TILT_MAX_DEG = 10.0+# gait tracking success+GAIT_TOL = 0.05 # m, mean (after each segment's first SETTLE_STEPS) of the feet's RMS height error to the gait's curve+# hand/footstand success+POSE_HOLD_STEPS = 100 # 2 s+FRONT_LEG_GEOMS = ["fl_calf1", "fl_calf2", "fr_calf1", "fr_calf2", "fl_thigh1", "fl_thigh2", "fl_thigh3", "fr_thigh1",+ "fr_thigh2", "fr_thigh3", "fl_hip", "fr_hip"] # handstand.py's termination contacts (both tasks)+HIND_LEG_GEOMS = [g.replace("fl_", "rl_").replace("fr_", "rr_") for g in FRONT_LEG_GEOMS] # the list Footstand sets up++GO1_FALL = "its trunk's up axis pointing below the horizon"+SPOT_FALL = "its trunk tilted by more than about 32 deg (the up axis's z component below 0.85)"++ROBOTS = {+ "go1": {+ "name": "Unitree Go1",+ "assets": [("playground/locomotion/go1/xmls", "*.xml"), ("playground/locomotion/go1/xmls/assets", "*"),+ ("menagerie/unitree_go1", "*.xml"), ("menagerie/unitree_go1/assets", "*")],+ "imu": "imu", "feet": ["FR", "FL", "RR", "RL"], "root": "trunk", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FR, FL, RR, RL legs; per leg hip (abduction), thigh (hip pitch), calf (knee)",+ },+ "spot": {+ "name": "Boston Dynamics Spot",+ "assets": [("playground/locomotion/spot/xmls", "*.xml"), ("menagerie/boston_dynamics_spot", "*.xml"),+ ("menagerie/boston_dynamics_spot/assets", "*")],+ "imu": "imu", "feet": ["FL", "FR", "HL", "HR"], "root": "body", "cameras": ["track", "side", "back", "top"],+ "joint_text": "FL, FR, HL, HR legs; per leg hx (abduction), hy (hip pitch), kn (knee)",+ },+ "barkour": {+ "name": "Google Barkour vB",+ "assets": [("menagerie/google_barkour_vb", "*.xml"), ("menagerie/google_barkour_vb/assets", "*")],+ "imu": "imu_frame", "feet": ["foot_front_left", "foot_hind_left", "foot_front_right", "foot_hind_right"],+ "root": "torso", "cameras": ["track", "realsense/rgb"],+ "joint_text": "front-left, hind-left, front-right, hind-right legs; per leg abduction, hip, knee",+ },+}+ENVS = {+ "Go1JoystickFlatTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "Go1JoystickRoughTerrain": {"robot": "go1", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5, "term_text": GO1_FALL,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_feetonly_rough_terrain.xml"},+ "Go1Getup": {"robot": "go1", "kind": "getup", "horizon": 300, "kp": 35.0, "kd": 0.5, "settle_s": 0.5,+ "z_des": 0.275, "min_imu_height": 0.22,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_fullcollisions_flat_terrain.xml"},+ "Go1Handstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, -1.0], "air_feet": ["RR", "RL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "Go1Footstand": {"robot": "go1", "kind": "stand_on_two", "horizon": 500, "kp": 35.0, "kd": 0.5,+ "forward": [0.0, 0.0, 1.0], "air_feet": ["FR", "FL"], "fwd_tol_deg": 30.0, "min_imu_height": 0.40,+ "hind_leg_contact": True,+ "xml": "playground/locomotion/go1/xmls/scene_mjx_flat_terrain.xml"},+ "SpotGetup": {"robot": "spot", "kind": "getup", "horizon": 300, "kp": 400.0, "kd": 20.0, "settle_s": 0.5,+ "z_des": 0.46, "min_imu_height": 0.40,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_flat_terrain.xml"},+ # Spot's joystick termination: upvector z < 0.85; the feet-only XML's actuator kv (20) stays, as in Playground+ "SpotFlatTerrainJoystick": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 300.0, "kd": 1.0, "up_z_min": 0.85,+ "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ "SpotJoystickGaitTracking": {"robot": "spot", "kind": "joystick", "horizon": 1000, "kp": 400.0, "kd": 10.0,+ "up_z_min": 0.85, "gait": True, "term_text": SPOT_FALL,+ "xml": "playground/locomotion/spot/xmls/scene_mjx_feetonly_flat_terrain.xml"},+ # Barkour: Playground loads Menagerie's scene as is (2 ms timestep) and takes 5 substeps, so a control step is+ # 10 ms of simulated time; its termination adds a joint box and a torso height; random pushes on the torso.+ "BarkourJoystick": {"robot": "barkour", "kind": "joystick", "horizon": 1000, "kp": 35.0, "kd": 0.5239, "up_z_min": 0.0,+ "control_dt": 0.01, "joint_box": [[-0.7, -1.0, 0.05], [0.52, 2.1, 2.1]], "torso_min_z": 0.18,+ "kicks": True, "xml": "menagerie/google_barkour_vb/scene_mjx.xml",+ "term_text": "its trunk's up axis pointing below the horizon, a joint outside its box (abduction "+ "[-0.7, 0.52], hip [-1.0, 2.1], knee [0.05, 2.1] rad) or the torso lower than 0.18 m"},+}++_LOGDIR = "/logs/agent/rcb" if os.path.isdir("/logs/agent") else "/app/output"+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", f"{_LOGDIR}/rcb_session_log.jsonl")+TRACE_DIR = os.environ.get("RCB_AGENT_TRACE_DIR", f"{_LOGDIR}/rcb_trace")+TRACE_MAX_FILES = 300+TRACE_MAX_BYTES = 400 * 1024 * 1024+++def _slog(ev: str, **kw) -> None:+ if not SESSION_LOG:+ return+ try:+ os.makedirs(os.path.dirname(SESSION_LOG), exist_ok=True)+ with open(SESSION_LOG, "a") as f:+ f.write(json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n")+ except OSError:+ pass+++def load_model(env: str):+ """The scene as Playground builds it: its XML with an asset dict of bare file names, then its gains."""+ import mujoco+ e = ENVS[env]+ assets = {}+ for d, pat in ROBOTS[e["robot"]]["assets"]:+ for f in sorted((ROOT / d).glob(pat)):+ if f.is_file():+ assets[f.name] = f.read_bytes()+ if e["robot"] == "barkour": # barkour/joystick.py: Menagerie's scene + a foot-floor contact sensor per foot+ spec = mujoco.MjSpec.from_file(str(ROOT / e["xml"]), assets=assets)+ for g in ROBOTS["barkour"]["feet"]:+ spec.add_sensor(name=f"{g}_floor_found", type=mujoco.mjtSensor.mjSENS_CONTACT, objtype=mujoco.mjtObj.mjOBJ_GEOM,+ objname=g, reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="floor", intprm=[1, 1, 1],+ datatype=mujoco.mjtDataType.mjDATATYPE_REAL, needstage=mujoco.mjtStage.mjSTAGE_ACC, dim=1)+ m = spec.compile()+ else:+ m = mujoco.MjModel.from_xml_string((ROOT / e["xml"]).read_text(), assets)+ m.dof_damping[6:] = e["kd"] # go1/base.py, spot/base.py: Kd as joint damping, Kp as the gain+ m.actuator_gainprm[:, 0] = e["kp"]+ m.actuator_biasprm[:, 1] = -e["kp"]+ return m+++def gait_rz(phi, swing_height):+ """mujoco_playground/_src/gait.py get_rz: a foot's target height over its phase (cubic Bezier up, then down)."""+ x = (np.asarray(phi) + np.pi) / (2 * np.pi)+ bez = lambda y0, y1, t: y0 + (y1 - y0) * (t ** 3 + 3 * (t ** 2 * (1 - t))) # noqa: E731+ return np.where(x <= 0.5, bez(0.0, swing_height, 2 * x), bez(swing_height, 0.0, 2 * x - 1))+++def schedule_of(inst: dict, horizon: int) -> np.ndarray:+ """(horizon, 3) command (vx, vy, wz) per control step from the instance's segments."""+ out = np.zeros((horizon, 3))+ seg = inst["commands"]+ for i, s in enumerate(seg):+ a = int(s["start_step"]); b = int(seg[i + 1]["start_step"]) if i + 1 < len(seg) else horizon+ out[a:b] = [s["vx"], s["vy"], s["wz"]]+ return out+++class Session:+ def __init__(self, instance: str | Path = "/app/instance.json", enable_render: bool = False, check_hash: bool = True):+ import mujoco+ self.mj = mujoco+ self.inst = json.load(open(instance))+ self.env = self.inst["env"]+ self.spec = ENVS[self.env]+ self.robot = ROBOTS[self.spec["robot"]]+ self.kind = self.spec["kind"]+ self.horizon = int(self.spec["horizon"])+ self.model = load_model(self.env)+ self.data = mujoco.MjData(self.model)+ m = self.model+ self.control_dt = float(self.spec.get("control_dt", CONTROL_DT))+ self.substeps = int(round(self.control_dt / m.opt.timestep))+ self.joint_names = [m.joint(m.actuator_trnid[i, 0]).name for i in range(m.nu)]+ self.lower = m.actuator_ctrlrange[:, 0].copy()+ self.upper = m.actuator_ctrlrange[:, 1].copy()+ self.home = m.keyframe("home").qpos[7:].copy()+ self._imu = m.site(self.robot["imu"]).id+ self._sens = {m.sensor(i).name: (m.sensor_adr[i], m.sensor_dim[i]) for i in range(m.nsensor)}+ self.cameras = list(self.robot["cameras"])+ self.commands = schedule_of(self.inst, self.horizon) if self.kind == "joystick" else None+ self._root = m.body(self.robot["root"]).id+ self._root_mass = float(m.body_subtreemass[self._root])+ self.kicks = self.inst.get("kicks", []) if self.spec.get("kicks") else []+ self.gait = self.inst.get("gait") if self.spec.get("gait") else None+ self._feet_sites = np.array([m.site(f).id for f in self.robot["feet"]])+ self._floor = m.geom("floor").id+ self._hind_ids = {m.geom(g).id for g in HIND_LEG_GEOMS} if self.spec.get("hind_leg_contact") else set()+ self._renderer = None+ self.enable_render = enable_render+ self._trace: list | None = None+ self.resets = 0+ self.total_steps = 0+ _slog("session_start", env=self.env, seed=self.inst.get("seed"))+ import atexit+ atexit.register(lambda: (self._trace_dump(), _slog("session_end", resets=self.resets,+ sim_steps=self.total_steps * self.substeps)))+ self.reset()+ self.instance_ok = self.state_sha() == self.inst.get("state_sha")+ if check_hash and self.inst.get("state_sha") and not self.instance_ok:+ raise RuntimeError(f"initial state hash {self.state_sha()} != instance {self.inst['state_sha']}")++ # ------------------------------------------------------------------------------------------------ episode+ def reset(self) -> None:+ """The frozen start state (t = 0): Playground's reset draw, then (getup) its 0.5 s settle with the joints held."""+ self._trace_dump()+ m, d = self.model, self.data+ self.mj.mj_resetData(m, d)+ d.qpos[:] = self.inst["qpos0"]+ d.qvel[:] = self.inst["qvel0"]+ d.ctrl[:] = self.inst["qpos0"][7:]+ self.mj.mj_forward(m, d)+ if self.spec.get("settle_s"):+ self.mj.mj_step(m, d, nstep=int(self.spec["settle_s"] / m.opt.timestep))+ d.time = 0.0+ self.targets = d.ctrl.copy()+ self.steps = 0+ self.resets += 1+ self.fell_at = None+ self.log: list[tuple] = [] # per control step: (lin_err, yaw_err, tilt_deg, imu_height, up_z)+ self.gait_log: list[float] = [] # gait tracking, per control step: RMS of the feet's height errors (m)+ self.pose_log: list[tuple] = [] # stand_on_two, per control step: (forward axis to target, deg; air feet down)+ self._trace = [] if TRACE_DIR else None+ _slog("reset", n=self.resets)++ def step(self, targets) -> dict[str, Any]:+ if self.steps >= self.horizon:+ raise RuntimeError(f"the episode is over: {self.horizon} control steps")+ tg = np.asarray(targets, dtype=np.float64).reshape(N)+ if not np.all(np.isfinite(tg)):+ raise ValueError("targets contain NaN/inf")+ tg = np.clip(tg, self.lower, self.upper)+ cmd = self.commands[self.steps] if self.commands is not None else np.zeros(3)+ self.targets = tg+ self.data.ctrl[:] = tg+ if self.kicks:+ self.data.xfrc_applied[self._root, :3] = self.push_force(self.steps)+ self.mj.mj_step(self.model, self.data, nstep=self.substeps)+ self.steps += 1+ self.total_steps += 1+ v, w = self.sensor("local_linvel"), self.sensor("gyro")+ up_z = float(self.data.site_xmat[self._imu][8])+ tilt = float(np.degrees(np.arccos(np.clip(up_z, -1.0, 1.0))))+ self.log.append((float(np.linalg.norm(v[:2] - cmd[:2])), float(abs(w[2] - cmd[2])), tilt,+ float(self.data.site_xpos[self._imu][2]), up_z))+ if self.kind == "stand_on_two":+ fwd = self.data.site_xmat[self._imu].reshape(3, 3)[:, 0]+ ang = float(np.degrees(np.arccos(np.clip(fwd @ np.asarray(self.spec["forward"]), -1.0, 1.0))))+ air_down = any(self.sensor(f"{f}_floor_found")[0] > 0 for f in self.spec["air_feet"])+ self.pose_log.append((ang, air_down))+ bad = up_z < -0.25 or any(self.sensor(f"{g}_floor_found")[0] > 0 for g in FRONT_LEG_GEOMS)+ if self.spec.get("hind_leg_contact") and not bad:+ bad = self._touches_floor(self._hind_ids)+ if bad and self.fell_at is None:+ self.fell_at = self.steps # handstand.py's termination: upvector z < -0.25 or a front-leg contact+ elif self.fell_at is None and self.terminated(up_z):+ self.fell_at = self.steps # the environment's own termination rule+ if self.gait:+ ph = np.fmod(np.asarray(self.gait["phase0"]) + (self.steps - 1) * self.gait["phase_dt"] + np.pi, 2 * np.pi) - np.pi+ err = self.data.site_xpos[self._feet_sites][:, 2] - gait_rz(ph, self.gait["foot_height_m"])+ self.gait_log.append(float(np.sqrt(np.mean(err ** 2))))+ if self._trace is not None:+ self._trace.append(tg.astype(np.float32))+ return self.check()++ def _touches_floor(self, geoms: set) -> bool:+ d, fl = self.data, self._floor+ return any((c.geom1 == fl and c.geom2 in geoms) or (c.geom2 == fl and c.geom1 in geoms) for c in d.contact[:d.ncon])++ def terminated(self, up_z: float) -> bool:+ """Playground's termination rule of a joystick environment: the trunk's up axis below up_z_min (Go1 0, Spot+ 0.85), and for Barkour also a joint outside its box or the torso below 0.18 m."""+ if up_z < self.spec.get("up_z_min", 0.0):+ return True+ if "joint_box" in self.spec:+ lo, hi = (np.tile(b, 4) for b in self.spec["joint_box"])+ q = self.data.qpos[7:]+ if np.any(q < lo) or np.any(q > hi):+ return True+ if "torso_min_z" in self.spec and self.data.xpos[self._root][2] < self.spec["torso_min_z"]:+ return True+ return False++ def push_force(self, t: int) -> np.ndarray:+ """barkour/joystick.py's kick at control step t: 0.5 sin(pi i / dur) * torso mass * v / (dur * 0.02 s) along+ the kick's direction, i = t - start (zero outside a kick)."""+ f = np.zeros(3)+ for k in self.kicks:+ i = t - int(k["start_step"])+ dur = int(k["duration_steps"])+ if 0 <= i < dur:+ u = 0.5 * np.sin(np.pi * i / dur)+ f[:2] += u * self._root_mass * k["velocity_mps"] / (dur * CONTROL_DT) * np.asarray(k["direction_xy"])+ return f++ def check(self) -> dict[str, Any]:+ """Success so far, judged on the steps executed (the grader judges the whole trajectory)."""+ L = np.array(self.log).reshape(-1, 5)+ out: dict[str, Any] = {"steps": self.steps, "horizon": self.horizon, "time_s": round(self.steps * self.control_dt, 2)}+ if self.kind == "joystick":+ segs = []+ for i, s in enumerate(self.inst["commands"]):+ a = int(s["start_step"]) + SETTLE_STEPS+ b = min(int(self.inst["commands"][i + 1]["start_step"]) if i + 1 < len(self.inst["commands"]) else self.horizon,+ self.steps)+ if b > a:+ segs.append({"segment": i, "lin_err": round(float(L[a:b, 0].mean()), 4),+ "yaw_err": round(float(L[a:b, 1].mean()), 4)})+ if self.gait:+ G = np.asarray(self.gait_log)+ for g in segs:+ s0 = self.inst["commands"][g["segment"]]+ a = int(s0["start_step"]) + SETTLE_STEPS+ nxt = self.inst["commands"][g["segment"] + 1]["start_step"] if g["segment"] + 1 < len(self.inst["commands"]) else self.horizon+ g["gait_err"] = round(float(G[a:min(int(nxt), self.steps)].mean()), 4)+ ok_track = all(g["lin_err"] <= LIN_TOL and g["yaw_err"] <= YAW_TOL and g.get("gait_err", 0.0) <= GAIT_TOL+ for g in segs)+ out.update(success=bool(self.steps == self.horizon and self.fell_at is None and ok_track),+ fell_at=self.fell_at, tracking_ok=bool(ok_track), segments=segs,+ worst_lin_err=max([g["lin_err"] for g in segs], default=None),+ worst_yaw_err=max([g["yaw_err"] for g in segs], default=None),+ **({"worst_gait_err": max([g["gait_err"] for g in segs], default=None)} if self.gait else {}))+ elif self.kind == "stand_on_two":+ P = np.array(self.pose_log, dtype=float).reshape(-1, 2)+ n = POSE_HOLD_STEPS+ held = (len(P) >= n and self.fell_at is None and bool(np.all(P[-n:, 0] <= self.spec["fwd_tol_deg"]))+ and bool(np.all(L[-n:, 3] >= self.spec["min_imu_height"])) and not bool(P[-n:, 1].any()))+ out.update(success=bool(held), fell_at=self.fell_at,+ pose_angle_deg=round(float(P[-1, 0]), 2) if len(P) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ else:+ last = L[-HOLD_STEPS:]+ held = (len(last) == HOLD_STEPS and bool(np.all(last[:, 2] <= TILT_MAX_DEG))+ and bool(np.all(last[:, 3] >= self.spec["min_imu_height"])))+ out.update(success=bool(held), tilt_deg=round(float(L[-1, 2]), 2) if len(L) else None,+ imu_height=round(float(L[-1, 3]), 4) if len(L) else None,+ min_imu_height=self.spec["min_imu_height"])+ return out++ @property+ def done(self) -> bool:+ return self.steps >= self.horizon++ # ------------------------------------------------------------------------------------------------ reading+ def sensor(self, name: str) -> np.ndarray:+ a, n = self._sens[name]+ return self.data.sensordata[a:a + n].copy()++ def gravity(self) -> np.ndarray:+ """Gravity's direction in the IMU frame ([0, 0, -1] when level), as Playground's Go1 computes it."""+ return self.data.site_xmat[self._imu].reshape(3, 3).T @ np.array([0.0, 0.0, -1.0])++ def foot_contacts(self) -> np.ndarray:+ return np.array([self.sensor(f"{f}_floor_found")[0] > 0 for f in self.robot["feet"]], dtype=np.float64)++ def command_now(self) -> np.ndarray:+ if self.commands is None:+ return np.zeros(3)+ return self.commands[min(self.steps, self.horizon - 1)].copy()++ def state(self) -> dict[str, Any]:+ d = self.data+ return {"qpos": d.qpos.copy(), "qvel": d.qvel.copy(), "targets": self.targets.copy(),+ "local_linvel": self.sensor("local_linvel"), "gyro": self.sensor("gyro"), "gravity": self.gravity(),+ "accelerometer": self.sensor("accelerometer"), "imu_pos": d.site_xpos[self._imu].copy(),+ "imu_mat": d.site_xmat[self._imu].reshape(3, 3).copy(), "foot_contacts": self.foot_contacts(),+ "feet_pos": np.array([d.site_xpos[self.model.site(f).id] for f in self.robot["feet"]]),+ "command": self.command_now(), **self.check()}++ def state_sha(self) -> str:+ return hashlib.sha1(np.concatenate([self.data.qpos, self.data.qvel]).tobytes()).hexdigest()[:12]++ # ------------------------------------------------------------------------------------------------ trajectories+ def save_trajectory(self, actions, path: str | Path = "/app/output/trajectory.npz", meta: dict | None = None) -> None:+ Path(path).parent.mkdir(parents=True, exist_ok=True)+ np.savez(path, actions=np.asarray(actions, dtype=np.float64), env=self.env, seed=self.inst.get("seed"),+ action_layout=f"12 joint position targets (rad) per control step (1/50 s): {', '.join(self.joint_names)}",+ meta=json.dumps(meta or {}))++ def replay(self, actions) -> dict[str, Any]:+ A = np.asarray(actions, dtype=np.float64)+ if A.ndim != 2 or A.shape[1] != N:+ raise ValueError(f"actions must be (T, {N}), got {A.shape}")+ if len(A) > self.horizon:+ raise ValueError(f"trajectory longer than the {self.horizon}-step episode")+ self.reset()+ self._trace = None+ for row in A:+ self.step(row)+ r = self.check()+ _slog("replay", n_actions=int(len(A)), success=r["success"])+ return {**r, "state_sha": self.state_sha()}++ # ------------------------------------------------------------------------------------------------ pictures+ def render(self, camera: str = "track", size: tuple[int, int] = (320, 240)) -> np.ndarray:+ if self._renderer is None or self._renderer.width != size[0] or self._renderer.height != size[1]:+ self._renderer = self.mj.Renderer(self.model, size[1], size[0])+ self._renderer.update_scene(self.data, camera=camera)+ return self._renderer.render().copy()++ def render_grid(self, size=(320, 240)) -> np.ndarray:+ """The robot's first two cameras side by side (Go1, Spot: `track` and `side`)."""+ return np.concatenate([self.render(c, size) for c in self.cameras[:2]], axis=1)++ def render_video(self, actions, path: str | Path, every: int | None = None, fps: int = 25) -> dict[str, Any]:+ """Replay `actions` from t = 0 and write an mp4 of at most ~150 frames (CPU rendering takes ~0.2 s a view)."""+ import imageio.v2 as imageio+ A = np.asarray(actions, dtype=np.float64)[:self.horizon]+ every = every or max(2, -(-len(A) // 150))+ fps = max(5, min(fps, round(1 / (every * self.control_dt))))+ self.reset()+ self._trace = None+ frames = [self.render_grid()]+ for i, row in enumerate(A):+ self.step(row)+ if (i + 1) % every == 0:+ frames.append(self.render_grid())+ path = Path(path)+ path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), frames[-1])+ return {**self.check(), "n_frames": len(frames), "video": str(path)}++ def _trace_dump(self) -> None:+ tr = self._trace+ self._trace = None+ if not tr or not TRACE_DIR:+ return+ try:+ os.makedirs(TRACE_DIR, exist_ok=True)+ ents = [e for e in os.scandir(TRACE_DIR) if e.name.endswith(".npz")]+ if len(ents) >= TRACE_MAX_FILES or sum(e.stat().st_size for e in ents) >= TRACE_MAX_BYTES:+ return+ np.savez_compressed(os.path.join(TRACE_DIR, f"{os.getpid()}_{self.resets:05d}.npz"), actions=np.stack(tr),+ success=self.check()["success"], t_end=time.time())+ except Exception:+ pass+++def main(argv: list[str]) -> int:+ """CLI: `replay --instance I --traj T [--out J] [--video V]` (one fresh-process replay, the grader's), or `info I`."""+ import argparse+ ap = argparse.ArgumentParser(prog="rcb_quadruped.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ r = sub.add_parser("replay")+ r.add_argument("--instance", default="/app/instance.json")+ r.add_argument("--traj", default="/app/output/trajectory.npz")+ r.add_argument("--out")+ r.add_argument("--video")+ i = sub.add_parser("info")+ i.add_argument("instance", nargs="?", default="/app/instance.json")+ a = ap.parse_args(argv)+ if a.cmd == "info":+ s = Session(a.instance)+ print(json.dumps({"env": s.env, "seed": s.inst.get("seed"), "state_sha": s.state_sha(), "horizon": s.horizon}))+ return 0+ os.environ["RCB_AGENT_TRACE_DIR"] = ""+ s = Session(a.instance, check_hash=False)+ out: dict[str, Any] = {"instance_ok": bool(s.instance_ok)}+ try:+ A = np.asarray(np.load(a.traj, allow_pickle=False)["actions"], dtype=np.float64)+ out.update(s.replay(A), n_actions=int(len(A)))+ except Exception as exc: # a malformed trajectory is the agent's 0, reported as such+ out.update(success=False, bad_trajectory=1, error=repr(exc)[:300])+ if a.video and not out.get("bad_trajectory"):+ try:+ s.render_video(A, a.video)+ out["video"] = True+ except Exception as exc:+ out["video"] = False+ out["video_error"] = repr(exc)[:300]+ if a.out:+ Path(a.out).write_text(json.dumps(out))+ print(json.dumps(out))+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/run.sh b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/run.shnew file mode 100755index 0000000000..49d4d045d4--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/run.sh@@ -0,0 +1,22 @@+#!/bin/sh+# eai-standard/2.2 sidecar entrypoint: PID 1 of the `sim` container, shared by every 2.2 service+# (scripts/eai_standard/run.sh, copied unchanged into each standard task's environment/sim/).+# - The service crashed (a non-zero exit: an exception, a signal, the startup watchdog): exit with its code, so compose+# restarts the container (`restart: on-failure:6`) and the service resumes the same episode from its journal+# (rcb_limited.Episode). The container keeps its /data (or /out) across the restart.+# - The service exited cleanly (0: it dumped its episode on the collect hook's SIGUSR1 and released the simulator): keep+# the container up for the collect hook's fresh-process replays. If the service were PID 1 itself, that exit would+# stop the container and kill the hook with it (Harbor reports exit 137).+# - Everything the service prints also goes to $RCB_DATA/server.log (an artifact: Harbor keeps no sidecar output, and a+# simulator that dies while it loads leaves no other trace).+DATA="${RCB_DATA:-/data}"+mkdir -p "$DATA"+rm -f "$DATA/.service_rc"+{ python -u "${RCB_SERVER:-/srv/server.py}" 2>&1; echo "$?" > "$DATA/.service_rc"; } | tee -a "$DATA/server.log"+rc="$(cat "$DATA/.service_rc" 2>/dev/null)"; rc="${rc:-1}"+if [ "$rc" != 0 ]; then+ echo "[sim] service exited ($rc): leaving, so compose restarts the container (the service resumes the episode if one began)" | tee -a "$DATA/server.log"+ exit "$rc"+fi+echo "[sim] service exited (0); holding the container open for the collect hook" | tee -a "$DATA/server.log"+while true; do sleep 3600; donediff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/server.py b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/server.pynew file mode 100644index 0000000000..b0c774b183--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/environment/sim/server.py@@ -0,0 +1,478 @@+"""eai-standard/2.2 sim service for MuJoCo Playground's quadruped tasks (docs/STANDARD_MODE_2_2.md): the adapter of the+shared layer rcb_limited.py; the simulator is rcb_quadruped.Session (plain MuJoCo on the CPU).+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to+/data/episode.jsonl.++The episode is the frozen instance's: one control step = 1/50 s. A joystick episode ends after the whole command schedule+(the horizon), when the robot meets Playground's termination rule (it falls over: a failure), when the agent submits+`done`, or when its time is over; success = the task's check on the steps executed. A getup episode ends the moment the+check holds (success), after the horizon, on `done` or on timeout.++Crash recovery (rcb_limited.Episode, resume class `exact`: MuJoCo on the CPU repeats bit for bit in a fresh process):+every executed row is journaled; after a crash the service rebuilds the episode and replays the journal. When the+episode ends the service writes /data/trajectory.npz + /data/episode.json; the collect hook (finalize.sh) makes it exit+and replays the trajectory in two fresh processes."""++import math+import os+import sys+import threading+import time+import traceback++import numpy as np++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import rcb_limited as L # noqa: E402++DATA = os.environ.get("RCB_DATA", "/data")+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.json"))+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "3600"))+MAX_CHUNK_S = float(os.environ.get("RCB_MAX_CHUNK_S", "10"))+MAX_WATCH_S = float(os.environ.get("RCB_MAX_WATCH_S", "30"))+CAM_W, CAM_H = 320, 240+LOCK = threading.Lock()+PID_FILE = os.path.join(DATA, "server.pid")+E = {"ready": False, "step": 0, "calls": 0, "done": False, "reason": None, "success": False, "t0": time.time(), "error": None}++os.environ["RCB_SESSION_LOG"] = ""+os.environ["RCB_AGENT_TRACE_DIR"] = ""+import rcb_quadruped as Q # noqa: E402 (first: it picks the rendering backend before mujoco loads)+import mujoco # noqa: E402++EP = L.Episode(DATA, dim=Q.N, resume="exact")+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()+S = Q.Session(INSTANCE)+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz+DT = S.control_dt # one control step of simulated time (Barkour: 10 ms, as Playground steps it)+CTRL_HZ = 1.0 / DT+SUBSTEPS = S.substeps+M = S.model+CAMS = list(S.cameras)+FEET = S.robot["feet"]+LIMITS = np.stack([S.lower, S.upper], axis=1)+GROUPS = [+ ("joint_pos", S.joint_names, "measured joint positions (rad), in the action's order"),+ ("joint_vel", [f"{j}_vel" for j in S.joint_names], "measured joint velocities (rad/s)"),+ ("joint_effort", [f"{j}_effort" for j in S.joint_names], "actuator torques of those joints (N m)"),+ ("gripper_opening", [], "none (no gripper)"),+ ("tcp_pose", [], "none (no gripper)"),+ ("imu_gyro", ["gyro_x", "gyro_y", "gyro_z"], "angular velocity of the trunk, IMU frame (rad/s)"),+ ("imu_accelerometer", ["acc_x", "acc_y", "acc_z"], "specific force at the IMU, IMU frame (m/s^2; +9.81 up at rest)"),+ ("imu_gravity", ["gravity_x", "gravity_y", "gravity_z"], "unit vector of gravity's direction in the IMU frame "+ "([0, 0, -1] when the trunk is level)"),+ ("imu_linvel", ["linvel_x", "linvel_y", "linvel_z"], "linear velocity of the trunk at the IMU, IMU frame (m/s; the "+ "IMU's velocimeter, what a state estimator gives)"),+ ("foot_contact", [f"{f}_contact" for f in FEET], "1 when the foot touches the ground, else 0"),+]+PROPRIO_LAYOUT = [n for _, names, _ in GROUPS for n in names]+PROPRIO_GROUPS, _i = {}, 0+for _g, _names, _meaning in GROUPS:+ PROPRIO_GROUPS[_g] = [_i, len(_names), _meaning]+ _i += len(_names)+++# ------------------------------------------------------------------------------------------------- cameras+def _intrinsic(cam: str) -> list:+ fovy = math.radians(float(M.cam_fovy[M.camera(cam).id]))+ f = 0.5 * CAM_H / math.tan(fovy / 2)+ return [[f, 0.0, CAM_W / 2], [0.0, f, CAM_H / 2], [0.0, 0.0, 1.0]]+++def camera_info(cam: str) -> dict:+ """World -> camera (OpenCV axes) and camera -> world (OpenGL axes) at the current state."""+ i = M.camera(cam).id+ R_gl = S.data.cam_xmat[i].reshape(3, 3) # camera axes (OpenGL: x right, y up, z back) in the world+ p = S.data.cam_xpos[i].copy()+ R_cv = R_gl @ np.diag([1.0, -1.0, -1.0])+ ext = np.zeros((3, 4))+ ext[:, :3] = R_cv.T+ ext[:, 3] = -R_cv.T @ p+ c2w = np.eye(4)+ c2w[:3, :3] = R_gl+ c2w[:3, 3] = p+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": ext.tolist(), "cam2world_gl": c2w.tolist(),+ "image_size": [CAM_W, CAM_H]}+++# ------------------------------------------------------------------------------------------------- kinematics+KD = mujoco.MjData(M) # kinematics only: the trunk at the origin, level; never stepped+_FOOT = {f: M.site(f).id for f in FEET}+_LEG_DOF = {f: [6 + 3 * k + j for j in range(3)] for k, f in enumerate(FEET)} # actuator order = leg order = FEET+++def _fk_kd(q) -> None:+ KD.qpos[:] = 0.0+ KD.qpos[3] = 1.0+ KD.qpos[7:] = q+ mujoco.mj_kinematics(M, KD)+++def _foot_pose(f: str) -> list:+ quat = np.zeros(4)+ mujoco.mju_mat2Quat(quat, KD.site_xmat[_FOOT[f]])+ return [*KD.site_xpos[_FOOT[f]].tolist(), *quat.tolist()]+++def do_kinematics(req: dict) -> dict:+ """Feet in the trunk frame (the trunk body's origin and axes; x forward, y left, z up). IK solves positions only, one+ leg (3 joints) per foot target, damped least squares within the joint ranges; a foot's orientation is ignored."""+ if req["op"] == "fk":+ _fk_kd(np.asarray(req["q"]))+ return L.fk_response({f: _foot_pose(f) for f in req["links"]}, "trunk")+ q = np.array(req["seed"] if req["seed"] is not None else S.data.qpos[7:], dtype=np.float64)+ errors = {}+ jac = np.zeros((3, M.nv))+ for f, pose in req["targets"].items():+ tgt = np.asarray(pose[:3])+ idx = _LEG_DOF[f]+ for _ in range(req["max_iters"]):+ _fk_kd(q)+ err = tgt - KD.site_xpos[_FOOT[f]]+ if np.linalg.norm(err) < req["tol_pos_m"]:+ break+ mujoco.mj_jacSite(M, KD, jac, None, _FOOT[f])+ J = jac[:, idx]+ dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(3), err)+ q[[i - 6 for i in idx]] = np.clip(q[[i - 6 for i in idx]] + dq, S.lower[[i - 6 for i in idx]],+ S.upper[[i - 6 for i in idx]])+ _fk_kd(q)+ errors[f] = (float(np.linalg.norm(tgt - KD.site_xpos[_FOOT[f]])), 0.0)+ ok = all(e[0] <= req["tol_pos_m"] for e in errors.values())+ return L.ik_response(q, ok, errors, "trunk", note="feet: position only (a foot is a sphere; its orientation is ignored)")+++# ------------------------------------------------------------------------------------------------- spec+def schedule_text() -> list:+ if S.commands is None:+ return []+ return [{"from_s": round(int(c["start_step"]) * DT, 2), "vx_mps": round(c["vx"], 4), "vy_mps": round(c["vy"], 4),+ "wz_radps": round(c["wz"], 4)} for c in S.inst["commands"]]+++TASK_EPISODE = {+ "joystick": f"one episode, no reset: it ends after {S.horizon} control steps (the {S.horizon * DT:g} s command "+ f"schedule), when the robot meets its termination rule ({S.spec.get('term_text')}: a failure), when you "+ "submit `done`, or when your time is over",+ "getup": f"one episode, no reset: it ends the moment the robot has stood upright for {Q.HOLD_STEPS} control steps in a "+ f"row (success), after {S.horizon} control steps, when you submit `done`, or when your time is over",+ "stand_on_two": f"one episode, no reset: it ends the moment the pose has been held for {Q.POSE_HOLD_STEPS} control steps "+ "in a row (success), when the robot meets the termination rule (a failure: its trunk's up axis below "+ f"-0.25, or {'a leg' if S.spec.get('hind_leg_contact') else 'a front leg'}'s thigh, calf or hip on the "+ f"floor), after {S.horizon} control steps, when you "+ "submit `done`, or when your time is over",+}[S.kind]+_ctl = {"type": "joint position actuators (PD)", "kp_nm_per_rad": float(M.actuator_gainprm[0, 0]),+ "kd_nms_per_rad": float(M.dof_damping[6] - M.actuator_biasprm[0, 2])}+SPEC = {+ "protocol": L.PROTOCOL,+ "protocol_compat": list(L.COMPAT),+ "simulator": "MuJoCo 3.3.7 (MuJoCo Playground's scene, plain MuJoCo on the CPU)",+ "robot": S.robot["name"],+ "task_text": S.inst["text"],+ "control_hz": CTRL_HZ,+ "physics_substeps": SUBSTEPS,+ "max_chunk_s": MAX_CHUNK_S,+ "max_watch_s": MAX_WATCH_S,+ "cameras": {c: {"rgb": True, "depth": True, "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),+ **({"mounted": "follows the robot", "mount": {"type": "link", "link": S.robot["root"], "note":+ "follows the robot's centre of mass at a fixed offset; it does not turn with the robot"}}+ if int(M.cam_mode[M.camera(c).id]) != 0 else+ {"mounted": "on the robot's head", "mount": {"type": "link", "link": M.body(M.cam_bodyid[M.camera(c).id]).name+ or S.robot["root"], "note": "fixed to the robot: moves and turns with it"}})}+ for c in CAMS},+ "default_cameras": ["track"],+ "action_types": {+ "joint_position": {+ "dim": Q.N,+ "layout": S.joint_names,+ "limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "units": "rad",+ "semantics": "absolute targets of the 12 joint position actuators, one per control step (1/50 s); rows `dt` "+ "apart (a multiple of the control period, at most 0.5 s), `hold` or `linear` between rows; values "+ "outside the limits are clipped and reported",+ },+ "done": {"dim": 0, "layout": [], "semantics": 'ends the episode now, in the current state (no physics); r.submit("done", [])'},+ "not_yet": ["joint_velocity", "joint_torque", "joint_delta"],+ },+ "proprio_layout": PROPRIO_LAYOUT,+ "proprio_groups": PROPRIO_GROUPS,+ "static": {},+ "world": {"frame": "z up; the robot starts where the episode puts it (no world coordinates are given)", "up": "+z",+ "units": {"length": "m", "angle": "rad", "time": "s"}, "quaternion_order": "wxyz",+ "camera_axes": "intrinsic_cv / extrinsic_cv: OpenCV camera axes (x right, y down, z forward); cam2world_gl: OpenGL axes"},+ "budget": {"reset": 0, "steps": None, "wall_clock_s": WALL_CLOCK_S},+ "max_control_steps": S.horizon,+ "episode": TASK_EPISODE,+ "command_schedule": schedule_text(),+ **({"gait": {k: S.gait[k] for k in ("name", "frequency_hz", "foot_height_m", "phase0", "phase_dt")} | {+ "feet": FEET, "rule": "foot i's target height at control step t is get_rz(wrap(phase0[i] + t * phase_dt)) with "+ "Playground's gait.get_rz (a cubic Bezier from 0 up to foot_height_m over the first half of the phase, then "+ "down); phases in rad, wrapped to [-pi, pi)"}} if S.gait else {}),+ "robot_spec": {"name": S.robot["name"], "joints": S.joint_names, "joint_limits": dict(zip(S.joint_names, LIMITS.tolist())),+ "joint_order": S.robot["joint_text"], "home_pose": dict(zip(S.joint_names, S.home.tolist())),+ "feet": FEET, "controller": _ctl},+ "kinematics": {"endpoint": "/kinematics", "joint_names": S.joint_names, "frame": "trunk", "quaternion_order": "wxyz",+ "links": FEET, "tcp_frames": [], "ee_frames": FEET, "ik_targets": FEET,+ "ik": {"tol_pos_m": 0.002, "tol_rot_rad": 3.2, "max_iters": 100},+ "note": "poses of the feet in the trunk frame (x forward, y left, z up, metres) for joint positions q; "+ "ik: one leg per foot, positions only"},+ "depth": {"modes": list(L.DEPTH_MODES), "default": "none", "kind": "z-depth", "unit": "m", "invalid": 0,+ "max_m": L.DEPTH_MAX_M, "frames_encoding": "uint16 mm, zlib", "noise": L.DEPTH_NOISE},+}+L.check_spec(SPEC) # a spec that misses a 2.2 field or names a forbidden one never starts the episode+EP.scene_built()++_RENDER = {}+++def _renderer():+ if "r" not in _RENDER:+ _RENDER["r"] = mujoco.Renderer(M, CAM_H, CAM_W)+ return _RENDER["r"]+++def ctrl_steps() -> int:+ return S.steps+++def proprio_row() -> np.ndarray:+ d = S.data+ return np.concatenate([d.qpos[7:], d.qvel[6:], d.actuator_force, S.sensor("gyro"), S.sensor("accelerometer"), S.gravity(),+ S.sensor("local_linvel"), S.foot_contacts()]).astype(np.float32)+++def grab(cams, want_depth: bool):+ r = _renderer()+ rgb, dep = {}, {}+ for c in cams:+ r.update_scene(S.data, camera=c)+ rgb[c] = r.render().copy()+ if want_depth:+ r.enable_depth_rendering()+ r.update_scene(S.data, camera=c)+ dep[c] = r.render().astype(np.float32).copy()+ r.disable_depth_rendering()+ return rgb, dep+++def extrinsics(cams) -> dict:+ return {c: np.asarray(camera_info(c)["extrinsic_cv"], dtype=np.float64) for c in cams}+++def write_final() -> None:+ if L.final_verdict(DATA): # finalize.sh's verdict, or a give-up after crashes: never overwritten+ return+ L._write_json(os.path.join(DATA, "final.json"), {**summary(), "finalized": False, "live_sha": E.get("live_sha")})+++def summary() -> dict:+ n = int(E.get("episode_control_steps") or ctrl_steps())+ chk = E.get("check") or {}+ return {"success": bool(E["success"]), "steps": E["step"], "calls": E["calls"], "control_steps": n,+ "physics_steps": n * SUBSTEPS, "elapsed_s": round((E.get("t_end") or time.time()) - E["t0"], 1),+ "reason": E["reason"], "done": E["done"], "env": S.env, "protocol": L.PROTOCOL, "n_actions": len(ROWS),+ "fell_at": chk.get("fell_at"), "worst_lin_err": chk.get("worst_lin_err"), "worst_yaw_err": chk.get("worst_yaw_err"),+ "tilt_deg": chk.get("tilt_deg"), "imu_height": chk.get("imu_height"), "pose_angle_deg": chk.get("pose_angle_deg"),+ **EP.final_fields()}+++def finish(reason: str) -> None:+ """The episode is over: the task's check on the steps executed, then the record for the collect hook."""+ if E["done"]:+ return+ E["done"] = True+ E["reason"] = reason+ E["t_end"] = time.time()+ E["episode_control_steps"] = ctrl_steps()+ try:+ chk = S.check()+ E["check"] = {k: v for k, v in chk.items() if k != "segments"}+ E["success"] = bool(chk["success"])+ except Exception: # noqa: BLE001+ traceback.print_exc()+ EP.log({"ev": "end", "reason": reason, "step": E["step"], "control_steps": ctrl_steps(), "success": bool(E["success"])})+ dump()+++def dump() -> None:+ if E.get("dumped"):+ return+ E["dumped"] = True+ E["live_sha"] = S.state_sha()+ np.savez(os.path.join(DATA, "trajectory.npz"), actions=np.asarray(ROWS, dtype=np.float64).reshape(-1, Q.N),+ env=S.env, action_layout=",".join(S.joint_names))+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})+ write_final()+++def after_step() -> None:+ if S.kind in ("joystick", "stand_on_two") and S.fell_at is not None:+ finish("fell")+ elif S.kind in ("getup", "stand_on_two") and S.check()["success"]:+ finish("success")+ elif S.done:+ finish("horizon")+++def ctrl_step(a, rec) -> bool:+ """One executed control step, journaled. True when the call must stop here."""+ S.step(a)+ ROWS.append(np.asarray(a, dtype=np.float64))+ stop = EP.journal(a)+ rec.tick()+ after_step()+ return E["done"] or stop+++def recorder(cams, fps: int, meta: dict) -> L.Recorder:+ return L.Recorder(cams, max(1, int(round(CTRL_HZ / max(1, fps)))), grab, proprio_row, extrinsics, ctrl_steps,+ depth=L.depth_mode(meta), clock_hz=CTRL_HZ)+++def video_fps(meta: dict) -> int:+ fps = meta.get("video_fps")+ if fps is None:+ return 10+ if isinstance(fps, bool) or not isinstance(fps, (int, float)) or not (1 <= fps <= 50):+ raise ValueError("video_fps must be in [1, 50]")+ return int(fps)+++def cameras_of(meta: dict) -> list:+ cams = meta.get("cameras") or ["track"]+ bad = [c for c in cams if c not in CAMS]+ if bad:+ raise ValueError(f"unknown cameras {bad}; cameras: {CAMS}")+ return list(cams)+++def meta_common(cams) -> dict:+ n = ctrl_steps()+ out = {"step": E["step"], "calls": E["calls"], "control_steps": n, "physics_steps": n * SUBSTEPS,+ "sim_time_s": round(n * DT, 3), "time_s": round(time.time() - E["t0"], 2),+ "time_left_s": max(0.0, round(WALL_CLOCK_S - (time.time() - E["t0"]), 1)),+ "proprio": {"layout": PROPRIO_LAYOUT, "now": proprio_row().tolist()}, "done": E["done"], "reason": E["reason"],+ "cameras": {c: camera_info(c) for c in cams}}+ if S.kind == "joystick":+ out["command_now"] = dict(zip(("vx_mps", "vy_mps", "wz_radps"), S.command_now().round(4).tolist()))+ return out+++def do_submit(meta: dict, A: np.ndarray):+ typ = meta.get("type")+ if typ == "done":+ rec = recorder(cameras_of(meta), 5, meta)+ rec.tick(force=True, last=True) # every response carries the last frames+ E["calls"] += 1+ finish("done")+ return {**meta_common(cameras_of(meta)), "chunk_id": E["calls"], "type": typ, "executed_rows": 0, "ok": True}, rec.parts("none", 5)+ if typ != "joint_position":+ raise ValueError(f"type must be joint_position or done (not yet: {SPEC['action_types']['not_yet']})")+ dt = float(meta.get("dt", DT))+ interp = meta.get("interpolate", "linear")+ video = meta.get("video", "mp4")+ cams, fps = cameras_of(meta), video_fps(meta)+ k = dt / DT+ if A.ndim != 2 or A.shape[1] != Q.N:+ raise ValueError(f"joint_position actions must be (T, {Q.N}), got {list(A.shape)}")+ if not np.all(np.isfinite(A)):+ raise ValueError("actions contain NaN/inf")+ if not (math.isfinite(dt) and dt <= 0.5 + 1e-9 and round(k) >= 1 and abs(k - round(k)) < 1e-6):+ raise ValueError(f"dt must be a whole multiple of the {DT:g} s control period and at most 0.5 s; got {dt}")+ if A.shape[0] * dt > MAX_CHUNK_S + 1e-9:+ raise ValueError(f"chunk longer than max_chunk_s={MAX_CHUNK_S}: {A.shape[0]} rows x {dt} s")+ if interp not in ("hold", "linear"):+ raise ValueError("interpolate must be hold|linear")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, clipped = recorder(cams, fps, meta), []+ E["calls"] += 1+ step0, before = E["step"], ctrl_steps()+ rec.tick(force=True)+ prev = S.targets.copy()+ for ri, row in enumerate(A):+ E["step"] += 1+ target = np.clip(row, LIMITS[:, 0], LIMITS[:, 1])+ for j in np.flatnonzero(target != row)[:20]:+ clipped.append({"row": ri, "index": int(j), "reason": f"{S.joint_names[j]} limit [{LIMITS[j, 0]:g}, {LIMITS[j, 1]:g}]"})+ n = int(round(k))+ stop = False+ for s in range(1, n + 1):+ a = target if interp == "hold" else prev + (target - prev) * (s / n)+ if ctrl_step(a, rec):+ stop = True+ break+ prev = target+ if stop:+ break+ rec.tick(force=True, last=True)+ out = {**meta_common(cams), "chunk_id": E["calls"], "type": typ, "executed_rows": E["step"] - step0,+ "control_steps_chunk": ctrl_steps() - before, "physics_steps_chunk": (ctrl_steps() - before) * SUBSTEPS,+ "clipped": clipped[:200], "n_clipped": len(clipped), "plan": [], "ok": True}+ EP.log({"ev": "submit", "call": E["calls"], "rows": E["step"] - step0, "dt": dt, "interpolate": interp, "cameras": cams,+ "control_steps": ctrl_steps() - before, "n_clipped": len(clipped), "note": (meta.get("note") or "")[:500],+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video, fps)+++def do_observe(meta: dict):+ cams, fps = cameras_of(meta), video_fps(meta)+ seconds = float(meta.get("seconds", 0))+ video = meta.get("video", "frames")+ if not math.isfinite(seconds) or seconds < 0 or seconds > MAX_WATCH_S:+ raise ValueError(f"seconds must be in [0, {MAX_WATCH_S}]")+ if video not in ("mp4", "frames", "both", "none"):+ raise ValueError("video must be mp4|frames|both|none")+ rec, before = recorder(cams, fps, meta), ctrl_steps()+ if seconds > 0 and not E["done"]:+ rec.tick(force=True)+ hold = S.targets.copy()+ for _ in range(int(round(seconds / DT))):+ if ctrl_step(hold, rec):+ break+ rec.tick(force=True, last=True)+ E["calls"] += 1+ out = {**meta_common(cams), "obs_id": E["calls"], "seconds": seconds, "control_steps_watch": ctrl_steps() - before,+ "physics_steps_watch": (ctrl_steps() - before) * SUBSTEPS, "ok": True}+ EP.log({"ev": "observe", "call": E["calls"], "seconds": seconds, "cameras": cams, "control_steps": ctrl_steps() - before,+ **({"stopped": EP.stop_reason} if EP.stopping else {})})+ return out, rec.parts(video if seconds > 0 else ("frames" if video == "mp4" else video), fps)+++def status() -> dict:+ return {"step": E["step"], "calls": E["calls"], "control_steps": ctrl_steps(), "done": E["done"], "reason": E["reason"],+ "elapsed_s": round(time.time() - E["t0"], 1)}+++def end_from_signal() -> None:+ """The collect hook's SIGUSR1: end the episode (the agent's time is over), dump it, exit so the replays can start."""+ with LOCK:+ E["exiting"] = True+ if not E["done"]:+ finish("timeout")+ EP.log({"ev": "exit", "reason": "collect hook: episode dumped"})+ if not os.path.exists(PID_FILE):+ open(PID_FILE, "w").write(str(os.getpid()))+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(0)+++def replay_row(row) -> None:+ """A journaled row during a resume."""+ S.step(row)+ ROWS.append(np.asarray(row, dtype=np.float64))+++EP.begin(state=E, step=replay_row, state_sha=S.state_sha, proprio=proprio_row, spec=SPEC, on_end=end_from_signal,+ start_event={"env": S.env, "seed": S.inst.get("seed"), "cameras": CAMS})+if E["done"]:+ dump() # resumed after the episode had ended: the record is rewritten from the replay+E["ready"] = True+write_final()+open(PID_FILE, "w").write(str(os.getpid()))+print(f"{L.PROTOCOL} MuJoCo Playground quadruped sim ready ({S.env}; startup {EP.n_startups}, resumes {EP.resumes})", flush=True)+L.serve(L.Service(spec=SPEC, lock=LOCK, state=E, submit=do_submit, observe=do_observe, kinematics=do_kinematics, status=status,+ on_submit_error=lambda exc: finish("error"), log=EP.log, episode=EP, state_sha=S.state_sha,+ proprio=proprio_row), port=int(os.environ.get("RCB_PORT", "8000")))diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/instruction.md b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/instruction.mdnew file mode 100644index 0000000000..01fba03fdc--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/instruction.md@@ -0,0 +1,59 @@+# MuJoCo Playground · SpotJoystickGaitTracking — STANDARD MODE (robot as a service, eai-standard/2.2)++**Task:** Make Boston Dynamics Spot follow the joystick command schedule for the whole 20 s episode with the commanded gait (the feet's swing pattern, frequency and height) without falling over.++You control the Boston Dynamics Spot quadruped — **as if it were real hardware** — in one episode of MuJoCo Playground's+`SpotJoystickGaitTracking` environment (plain MuJoCo 3.3.7 with Playground's scene, commit 4057c14). The simulator runs in a service you+cannot open. You get one client and one episode.++## The episode+The robot starts standing still at Playground's `home` pose (this environment's reset does not move it). The ground is flat.+For 20 s (1000 control steps) it is given this command schedule, drawn by Playground's command process (a new draw every 201 control steps, zero with probability 0.1). A command is a velocity in the robot's own frame: vx forward, vy to the left (the trunk's planar velocity), and the yaw rate:++| from (s) | vx (m/s) | vy (m/s) | yaw rate (rad/s) |+|---:|---:|---:|---:|+| 0.00 | +0.994 | +0.371 | +0.447 |+| 4.02 | +0.924 | -0.362 | -0.327 |+| 8.04 | -0.939 | +0.092 | +0.450 |+| 12.06 | -0.960 | -0.295 | +0.569 |+| 16.08 | +0.866 | +0.185 | -0.297 |++The feet must also follow a **pace** gait at 3.66 Hz with a swing height of 0.129 m: foot i's target height at control step t is Playground's `gait.get_rz(wrap(phase0[i] + t * phase_dt), foot_height)` (a cubic Bezier up over the first half of the phase, then down), with phase0 = [0.0, 3.1416, 0.0, 3.1416] (feet FL, FR, HL, HR) and phase_dt = 0.4597 rad.++The same schedule is `spec["command_schedule"]`; every response's `meta["command_now"]` is the current command. The gait is `spec["gait"]`.++## Rules (real-robot rules)+- **No reset.** One episode. You see four cameras that follow the robot (RGB, depth if you ask) and the robot's own+ sensors: joint positions, velocities and torques, the IMU (gyro, accelerometer, gravity's direction, the trunk's+ velocity), foot contacts. No world positions, no success check.+- **The episode ends** after 1000 control steps, the whole schedule (`spec["max_control_steps"]`, counted by `meta["control_steps"]`), when the robot meets its termination rule (the trunk tilted by more than about 32 deg (the z component of the IMU frame's z axis below 0.85): a failure), when you submit `done`, or when your time is up (before the end of the schedule, both are failures).+- **Success** is judged on the whole schedule: no termination, and in every command segment, after its first 25 control steps, a mean |v_xy - cmd_xy| of at most 0.2 m/s (`imu_linvel`) and a mean |w_z - cmd_wz| of at most 0.3 rad/s (`imu_gyro`), and a mean RMS foot-height error to the gait's targets of at most 0.05 m.+- Your wall-clock budget is 3600 s from your start. Simulated time only advances with your commands (and+ `get_obs(seconds=...)`, which holds the current targets).+- Nothing to hand in: the service records the episode and grades it. Leave your script at `/app/output/gen.py`.+- **If the service crashes**, a call fails with a connection error: it restarts and resumes the SAME episode (never a+ reset) in the state after the last call it completed. `r.wait_ready()` waits for it; then check `r.status()`.+- Nothing is put into your context automatically: images come back as arrays in Python objects.++## Client (`/opt/tools/rcb_client.py`)+```python+from rcb_client import Robot+r = Robot() # connects (waits while the service starts)+spec = r.spec() # action types, limits, cameras, robot_spec (home pose, gains), kinematics, command_schedule, gait+obs = r.get_obs() # obs.last[cam] -> uint8 (240, 320, 3); obs.meta["proprio"] {"layout", "now"}+res = r.submit("joint_position", A, dt=0.02) # A: (T, 12) rows dt apart; res.proprio (one row per frame), res.meta+obs = r.get_obs(seconds=1.0, video="mp4") # hold the current targets and watch for 1 s (max 30)+r.fk(q); r.ik({"FL": [x, y, z, 1, 0, 0, 0]}, seed=q) # feet in the trunk frame <-> joints (no physics)+r.submit("done", []) # end the episode now+r.status() # calls, control steps, done, reason, elapsed time+```+Cameras: `track`, `side`, `back`, `top` (they follow the robot); `spec["cameras"]` gives each one's mounting and intrinsics, and every response carries its pose. Proprioception (`spec["proprio_groups"]`): `joint_pos`, `joint_vel`, `joint_effort` (12 each, action+order), `imu_gyro`, `imu_accelerometer`, `imu_gravity`, `imu_linvel` (3 each, IMU frame: x forward, y left, z up),+`foot_contact` (FL, FR, HL, HR).++### `joint_position` (12)+FL, FR, HL, HR legs, each hx (abduction), hy (hip pitch), kn (knee): absolute targets of the joint position actuators (rad; kp = 400 N m/rad, joint damping 10 N m s/rad, plus the actuators' own damping of 20 N m s/rad).+Rows are `dt` apart (a whole multiple of the 0.02 s control period, at most 0.5 s), `interpolate="linear"` (default) or+`"hold"` between rows; a chunk covers at most 10 s; values outside the limits+(`spec["action_types"]["joint_position"]["limits"]`) are clipped and listed in `res.meta["clipped"]`. Feedback control+means short chunks: each response tells you where the robot is now.diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/solution/oracle.npy b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/solution/oracle.npynew file mode 100644index 0000000000..565259883eBinary files /dev/null and b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/solution/oracle.npy differdiff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/solution/oracle_replay.py b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/solution/oracle_replay.pynew file mode 100644index 0000000000..b6a9824592--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/solution/oracle_replay.py@@ -0,0 +1,42 @@+"""Oracle (standard mode): streams the reference rows (one per 1/50 s control step, `hold`) as `joint_position` chunks+through the client, the same interface an agent has. Uses no privileged information at run time; the service's recorded+trajectory is then exactly the privileged reference. If the service crashes it resumes the same episode+(spec["on_service_error"]): the oracle waits until it answers again and goes on from the control step it reports."""+import os+import sys+import time++import numpy as np+import requests++sys.path.insert(0, "/opt/tools")+from rcb_client import EpisodeOver, Robot # noqa: E402++Q = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle.npy")).astype(np.float64)+r = Robot()+spec = r.spec()+dt = 1.0 / float(spec["control_hz"])+per_chunk = max(1, int(spec.get("max_chunk_s", 10) / dt + 1e-9))+print("spec:", spec["protocol"], "rows:", len(Q), flush=True)+t0, i = time.time(), 0+while i < len(Q):+ chunk = Q[i:i + per_chunk]+ try:+ res = r.submit("joint_position", chunk, dt=dt, interpolate="hold", cameras=["track"], video="none", note=f"oracle rows {i}+")+ except EpisodeOver as e:+ print("episode over:", e)+ break+ except requests.exceptions.RequestException as e: # the service crashed: it restarts and resumes the same episode+ print("service unreachable:", repr(e)[:200], "- waiting for it to resume", flush=True)+ st = r.wait_ready()+ n = int(st["control_steps"])+ if not i <= n <= i + len(chunk):+ raise SystemExit(f"resumed at control step {n}: outside the chunk in flight (rows {i}..{i + len(chunk)})")+ i = n+ continue+ n = int(res.meta["control_steps"])+ print(f"rows {i}..{n}: clipped={res.meta['n_clipped']} done={res.meta['done']} reason={res.meta['reason']}", flush=True)+ if res.meta["done"] or n <= i:+ break+ i = n+print("status:", r.status(), "wall %.0fs" % (time.time() - t0))diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/solution/solve.sh b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/solution/solve.shnew file mode 100755index 0000000000..ecb1f6c954--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/solution/solve.sh@@ -0,0 +1,8 @@+#!/bin/bash+# Oracle (standard mode): streams the reference trajectory's joint targets (solution/oracle.npy, one row per control step)+# as `joint_position` chunks through the client. Uses no privileged information at run time (only the pre-recorded+# targets); the service's recorded trajectory is then exactly the privileged reference.+set -e+mkdir -p /app/output+cp /solution/oracle_replay.py /app/output/gen.py+python /solution/oracle_replay.pydiff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/task.toml b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/task.tomlnew file mode 100644index 0000000000..c9c88a6760--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/task.toml@@ -0,0 +1,54 @@+# Generated by scripts/mujoco-playground/generate.py -- edit the template or the instance, not this.+schema_version = "1.3"+artifacts = [+ { source = "/data/final.json", service = "sim" },+ { source = "/data/episode.jsonl", service = "sim" },+ { source = "/data/trajectory.npz", service = "sim" },+ { source = "/data/replay.mp4", service = "sim" },+ { source = "/data/server.log", service = "sim" }, # the service's own output (Harbor keeps none)+ { source = "/data/journal.f64", service = "sim" }, # crash recovery: every executed control step (float64 rows)+ { source = "/data/startups.jsonl", service = "sim" }, # crash recovery: one line per service start+ { source = "/data/replay1.log", service = "sim" }, # the collect hook's two fresh-process replays+ { source = "/data/replay2.log", service = "sim" },+ { source = "/data/replay3.log", service = "sim" }, # and its third, which renders replay.mp4+ "/app/output/",+]++[task]+name = "robot-coding-bench/mujoco_playground_spot_joystick_gait_tracking-standard"+description = "STANDARD MODE (robot as a service, eai-standard/2.2): MuJoCo Playground SpotJoystickGaitTracking (Boston Dynamics Spot) on the same frozen instance as mujoco_playground_spot_joystick_gait_tracking-privileged: Make Boston Dynamics Spot follow the joystick command schedule for the whole 20 s episode with the commanded gait (the feet's swing pattern, frequency and height) without falling over. The agent only gets a client: four cameras that follow the robot (RGB, optional depth), the robot's joints and IMU, joint position chunks at 50 Hz, the feet's kinematics; one episode, no reset, no world state; the sim service records the episode, replays it in fresh processes and grades it."+authors = [{ name = "Changhe Chen" }]+keywords = ["robotics", "mujoco", "mujoco-playground", "boston-dynamics-spot", "quadruped", "locomotion", "joystick", "code-as-policy", "trajectory", "standard-mode"]++[metadata]+author_name = "Changhe Chen"+author_org = "MLL Lab"+task_type = "trajectory"+simulator = "mujoco"+robot = "boston-dynamics-spot"+family = "mujoco_playground/SpotJoystickGaitTracking"+mode = "standard"+protocol = "eai-standard/2.2"+oracle = "full"+instance_seed = 0+expert_time_estimate_hours = 4.0++[verifier]+timeout_sec = 600.0+environment_mode = "separate"+network_mode = "no-network"++[[verifier.collect]]+service = "sim"+command = "sh /srv/finalize.sh" # end + dump + exit the service, replay twice in fresh processes, write final.json, video+timeout_sec = 1200++[agent]+timeout_sec = 3600.0+network_mode = "allowlist"+allowed_hosts = ["chatgpt.com", "*.chatgpt.com", "auth.openai.com", "api.openai.com", "*.openai.com", "api.anthropic.com", "*.anthropic.com", "openrouter.ai", "*.openai.azure.com", "*.cognitiveservices.azure.com"]++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 8192diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/tests/Dockerfile b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/tests/Dockerfilenew file mode 100644index 0000000000..26bc699ebe--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/tests/Dockerfile@@ -0,0 +1,5 @@+# Separate verifier sandbox: grades the sim service's own artifacts; needs nothing but python (the shared client base).+FROM docker.io/library/python:3.12.14-slim@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f+COPY test.sh /tests/test.sh+COPY grade.py /tests/grade.py+RUN chmod +x /tests/test.shdiff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/tests/grade.py b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/tests/grade.pynew file mode 100644index 0000000000..5b990bf458--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/tests/grade.py@@ -0,0 +1,64 @@+"""Standard-mode verifier (MuJoCo Playground quadrupeds): reads what the sim service (which the agent could not touch) wrote:+/data/final.json (live success, two fresh-process replays of the recorded trajectory, determinism, crash-recovery+fields), /data/trajectory.npz, /data/replay.mp4. success = live success AND replay success AND deterministic, the+replays having started in the instance's t = 0 state. Numeric-only reward.json."""++import json, os, shutil++LOG = "/logs/verifier"+os.makedirs(LOG, exist_ok=True)+++def write(ok, out):+ open(f"{LOG}/reward.txt", "w").write("1\n" if ok else "0\n")+ json.dump(out, open(f"{LOG}/reward.json", "w"))+ print(out)+++p = "/data/final.json"+if not os.path.exists(p):+ write(False, {"success": 0, "missing_log": 1, "grader_error": 0, "infra_error": 0})+ raise SystemExit+d = json.load(open(p))+for f in ("replay.mp4", "trajectory.npz", "episode.jsonl"):+ if os.path.exists(f"/data/{f}"):+ shutil.copy(f"/data/{f}", f"{LOG}/{f}")+ok = bool(d.get("success")) and bool(d.get("replay_success")) and bool(d.get("deterministic"))+ok = ok and not d.get("instance_mismatch")+num = lambda k: float(d.get(k) or 0) # noqa: E731+write(+ ok,+ {+ "success": int(ok),+ "live_success": int(bool(d.get("success"))),+ "replay_success": int(bool(d.get("replay_success"))),+ "deterministic": int(bool(d.get("deterministic"))),+ "live_matches_replay": int(bool(d.get("live_matches_replay"))),+ "finalized": int(bool(d.get("finalized"))),+ "n_actions": int(d.get("n_actions") or 0),+ "sim_steps": int(d.get("control_steps") or 0),+ "physics_steps": int(d.get("physics_steps") or 0),+ "steps": int(d.get("steps") or 0),+ "elapsed_s": float(d.get("elapsed_s") or 0),+ "video_rendered": int(bool(d.get("video"))),+ "fell": int(d.get("fell_at") is not None),+ "worst_lin_err": float(d["worst_lin_err"]) if d.get("worst_lin_err") is not None else -1.0,+ "worst_yaw_err": float(d["worst_yaw_err"]) if d.get("worst_yaw_err") is not None else -1.0,+ "end_tilt_deg": float(d["tilt_deg"]) if d.get("tilt_deg") is not None else -1.0,+ "end_imu_height": float(d["imu_height"]) if d.get("imu_height") is not None else -1.0,+ "end_pose_angle_deg": float(d["pose_angle_deg"]) if d.get("pose_angle_deg") is not None else -1.0,+ # a replay process gave no result, or the image no longer builds the frozen start: not the agent's 0+ "grader_error": int(bool(d.get("replay_failed") or d.get("instance_mismatch"))),+ "instance_mismatch": int(bool(d.get("instance_mismatch"))),+ # an infrastructure failure, not the agent's (PROTOCOL §2.6): a give-up after crashes between calls or a failed+ # resume (docs/STANDARD_MODE_2_2.md §13), the service not ending its episode for the collect hook, a replay+ # process that gave no result, replays that did not start in the instance's t = 0 state+ "infra_error": int(bool(d.get("infra_error"))),+ "gave_up": int(bool(d.get("gave_up"))),+ "sim_error": int(d.get("reason") == "error"),+ "sim_startups": int(d.get("sim_startups") or 0),+ "resumes": int(d.get("resumes") or 0),+ "resume_state_mismatch": int(d.get("resume_state_mismatch") or 0),+ "resume_max_joint_dev": num("resume_max_joint_dev"),+ },+)diff --git a/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/tests/test.sh b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/tests/test.shnew file mode 100755index 0000000000..bc608aa8b9--- /dev/null+++ b/tasks/mujoco_playground_spot_joystick_gait_tracking-standard/tests/test.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Verifier (separate sandbox): the sim sidecar's artifacts were uploaded to /data by Harbor.+# Harbor also mounts /logs/verifier into the agent's container: start from an empty directory, so nothing the agent+# left there (a planted reward, a symlink) can count. rm never follows symlinks.+rm -rf /logs/verifier/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)+mkdir -p /logs/verifier+python /tests/grade.py 2> /logs/verifier/grade.log