Skip to content

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.

Merge pull request #61 from JamesKrW/dev/chi-dexjoco-shared (+1 more)

Chi Gui20c0f655d982
diff --git a/README.md b/README.md
index 51890909dd..c76c13e02c 100644
--- a/README.md
+++ b/README.md
@@ -50,6 +50,7 @@ measures the same thing under real-robot constraints. The standard-mode wire pro
| RoboCasa (`robocasa-<task>-i00`) | robosuite · Franka Panda on an Omron mobile base | 29 | full (upstream demonstrations) |
| RoboCasa365 (`robocasa365-<task>-i00`) | robosuite · Franka Panda on an Omron mobile base | 50 | full (upstream demonstrations) |
| RoboCasa-GR1 (`robocasa-gr1-<task>-i00`) | robosuite · Fourier GR1 humanoid | 24 | full (upstream demonstrations) |
+| DexJoCo (`dexjoco-<family>-i00`) | MuJoCo 3.4 · Franka Panda + Allegro hand, one or two arms | 11 | full (upstream human demonstrations) |
| MyoSuite (`myosuite-<family>-i00`) | MyoSuite 2.12.2 (MuJoCo 3.6, CPU) · musculoskeletal hand, arm, torso and legs (MyoHand, MyoArm, MyoLegs, with prostheses in two tasks), muscle commands; MyoChallenge and MyoDex tasks | 22 | full on 3 (MyoSuite's NPG baselines), none on 19 (human review) |
Each task directory carries a README in one layout: a key table (benchmark, mode, twin, simulator and robot, family and
@@ -113,7 +114,7 @@ harbor view jobs
- **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, the three
- RoboCasa benchmarks and MuJoCo Playground's quadruped tasks restrict agent egress to model APIs by default, because their reference policies, demonstrations or
+ RoboCasa benchmarks, DexJoCo 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 is
off by default in batch runs (it runs at the model provider, past any allowlist).
diff --git a/ci_checks/check-tooling-identity.sh b/ci_checks/check-tooling-identity.sh
index 5f2e56395f..3dbabf2279 100755
--- a/ci_checks/check-tooling-identity.sh
+++ b/ci_checks/check-tooling-identity.sh
@@ -1,13 +1,13 @@
#!/usr/bin/env bash
# Shared-source rules (PROTOCOL §2.1, D9: copies of shared sources are byte-identical). Two parts:
-# 1. BEHAVIOR-1K, RoboLab, RoboWits, ManiGuard, MolmoSpaces and MyoSuite: within one benchmark, both modes, every copy of a shared file is byte-identical
+# 1. BEHAVIOR-1K, RoboLab, RoboWits, ManiGuard, MolmoSpaces, MyoSuite and DexJoCo: within one benchmark, both modes, every copy of a shared file is byte-identical
# (the generators copy them from the benchmark's template task unchanged):
# - the tooling module rcb_<sim>.py wherever it sits (privileged environment/ and tests/, standard environment/sim/);
# - the standard agent side environment/rcb_client.py + rcb1.py and the sim service environment/sim/ (server.py,
# finalize.sh, run.sh, rcb1.py);
# - the graders, tests/grade.py (one version per mode).
# A change to one of them is rolled out to every task of the benchmark at once. Same approach as check-robopaint-tooling.sh.
-# 2. The eai-standard/2.2 layer (every task whose metadata.protocol is 2.2: BEHAVIOR, RoboLab, RoboWits, RoboPaint, MolmoSpaces, MyoSuite): the
+# 2. The eai-standard/2.2 layer (every task whose metadata.protocol is 2.2: BEHAVIOR, RoboLab, RoboWits, RoboPaint, MolmoSpaces, MyoSuite, DexJoCo): the
# agent's client environment/rcb_client.py + rcb1.py and the service's environment/sim/rcb_limited.py + rcb1.py +
# run.sh are byte-identical to their source in scripts/eai_standard/ (docs/STANDARD_MODE_2_2.md), and the sidecar is
# set up for crash recovery: `command: sh /srv/run.sh` (run.sh exits non-zero when the service crashes) and
@@ -19,7 +19,8 @@ python3 - "${1:-$root/tasks}" "$root/scripts/eai_standard" <<'PY'
import collections, hashlib, os, re, sys, tomllib
tasks, src = sys.argv[1], sys.argv[2]
MODULE = {"behavior": "rcb_behavior.py", "robolab": "rcb_robolab.py", "robowits": "rcb_robowits.py", "maniguard": "rcb_maniguard.py",
- "molmospaces": "rcb_molmospaces.py", "myosuite": "rcb_myosuite.py"}
+ "molmospaces": "rcb_molmospaces.py", "myosuite": "rcb_myosuite.py",
+ "dexjoco": "rcb_dexjoco.py"}
SHARED = {"environment/rcb_client.py", "environment/rcb1.py", "environment/sim/server.py", "environment/sim/finalize.sh",
"environment/sim/run.sh", "environment/sim/rcb1.py", "environment/sim/rcb_limited.py", "tests/grade.py"}
LAYER = {"environment/rcb_client.py": "rcb_client.py", "environment/rcb1.py": "rcb1.py", "environment/sim/rcb_limited.py": "rcb_limited.py",
@@ -85,6 +86,6 @@ if bad:
if len(bad) > 60:
print(f" ... {len(bad) - 60} more")
sys.exit(1)
-print("ok shared sources: " + ("; ".join(f"{b} {dirs[b]} task dirs, {len(seen[b])} shared files" for b in sorted(seen)) or "no BEHAVIOR / RoboLab / RoboWits / ManiGuard / MolmoSpaces / MyoSuite tasks")
+print("ok shared sources: " + ("; ".join(f"{b} {dirs[b]} task dirs, {len(seen[b])} shared files" for b in sorted(seen)) or "no BEHAVIOR / RoboLab / RoboWits / ManiGuard / MolmoSpaces / MyoSuite / DexJoCo tasks")
+ f"; the eai-standard/2.2 layer in {n_layer} task dirs")
PY
diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md
index b0bc74642e..3814e81413 100644
--- a/docs/PROTOCOL.md
+++ b/docs/PROTOCOL.md
@@ -176,7 +176,7 @@ Harbor builds the task images locally from the task directory on every run; only
| Reference solutions only under `solution/` (mounted for the oracle agent only) | MUST | [current] |
| A solution, or a pointer to one, anywhere the agent can reach (task image, base image, tooling, docs in the container) | MUST NOT | [current] |
| Upstream experts scrubbed from images (e.g. cap-x `oracle_code`, RoboTwin `play_once`) | MUST | [current] |
-| Agent egress allowlisted in `task.toml` when a solution is publicly downloadable | SHOULD | [current] for DexToolBench, KinDER, HumanoidBench, MetaWorld+, RoboPaint, VLABench, RoboCasa, RoboCasa365, RoboCasa-GR1, MolmoSpaces and MyoSuite; RoboTwin, MuJoCo Playground, robosuite, RoboWits, RoboLab and BEHAVIOR-1K are open by default and switched per run with `scripts/set_agent_egress.py` (allowlist contents under review, §7) |
+| Agent egress allowlisted in `task.toml` when a solution is publicly downloadable | SHOULD | [current] for DexToolBench, KinDER, HumanoidBench, MetaWorld+, RoboPaint, VLABench, RoboCasa, RoboCasa365, RoboCasa-GR1, MolmoSpaces, MyoSuite and DexJoCo; RoboTwin, MuJoCo Playground, robosuite, RoboWits, RoboLab and BEHAVIOR-1K are open by default and switched per run with `scripts/set_agent_egress.py` (allowlist contents under review, §7) |
| `nop` scores 0 | MUST | [current] |
| `oracle = "full"`: the oracle scores 1 | MUST | [current] |
| `oracle = "partial"` or `"none"`: `oracle_evidence` and **human review** | MUST | [new] |
@@ -230,7 +230,7 @@ section lists what is required.
| rcb-limited/2.0 | 2026-09-24 | no reset; `/submit` action chunks, `/observe`; binary RCB1 responses |
| rcb-limited/2.1 | 2026-09-27 | 82-column proprioception, optional depth noise; crash recovery added 2026-09-29 (no version bump) |
| **eai-standard/2.1** | 2026-09-30 | rename only; identical to rcb-limited/2.1 including crash recovery. **Current.** |
-| eai-standard/2.2 | 2026-10-01 | additive extension (§6, [`STANDARD_MODE_2_2.md`](STANDARD_MODE_2_2.md)) with crash recovery; served by BEHAVIOR-1K, RoboLab, RoboWits, RoboPaint, MolmoSpaces and MyoSuite |
+| eai-standard/2.2 | 2026-10-01 | additive extension (§6, [`STANDARD_MODE_2_2.md`](STANDARD_MODE_2_2.md)) with crash recovery; served by BEHAVIOR-1K, RoboLab, RoboWits, RoboPaint, MolmoSpaces, MyoSuite and DexJoCo |
Services report `eai-standard/2.1` or `eai-standard/2.2`; the shipped clients accept the former `rcb-limited/2.x` spelling as well.
diff --git a/docs/STANDARD_MODE_2_2.md b/docs/STANDARD_MODE_2_2.md
index 9584b51940..db1814bfba 100644
--- a/docs/STANDARD_MODE_2_2.md
+++ b/docs/STANDARD_MODE_2_2.md
@@ -5,8 +5,8 @@
> says otherwise, every 2.2 addition is a MAY capability, and a request written for 2.0 or 2.1 gets the same answer as
> 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`), and MuJoCo Playground's
+**Who serves it.** The standard twins of eight benchmarks: BEHAVIOR-1K, RoboLab, RoboWits, RoboPaint, ManiGuard, MolmoSpaces,
+MyoSuite and DexJoCo ([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 six
diff --git a/docs/TAXONOMY.md b/docs/TAXONOMY.md
index 992cf6c3e5..5961f42dcb 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, 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) · `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) |
+| `protocol` | standard mode only: `eai-standard/2.1` · `eai-standard/2.2` (BEHAVIOR-1K, RoboLab, RoboWits, RoboPaint, ManiGuard, MolmoSpaces, MyoSuite, DexJoCo, 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) · `dexjoco` (DexJoCo: MuJoCo 3.4 + its gymnasium envs) — 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) · `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) · `franka-allegro` (Franka Panda with a 16-DoF Allegro hand; DexJoCo) · `franka-allegro-bimanual` (two of them side by side; DexJoCo) |
| `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) |
@@ -34,7 +34,7 @@ Benchmark-specific fields (MAY, PROTOCOL §2.3):
- `<base>-privileged` and `<base>-standard`, the two modes of one frozen instance. `<base>` is
`<simulator>-<family-with-dashes>-i<NN>`, or the benchmark's own task name: `robotwin_2_0_<robotwin_task>`,
`dextoolbench_<category>_<object>_<task>`, `mujoco_playground_<env>`, `kinder-<family>-i<NN>`,
- `humanoidbench-<category>-<family>-i<NN>`, `myosuite-<family>-i<NN>`.
+ `humanoidbench-<category>-<family>-i<NN>`, `myosuite-<family>-i<NN>`, `dexjoco-<family-with-dashes>-i<NN>`.
- RoboPaint: `<base>` is `robopaint-<family>-<target>-i<NN>`; Chinese targets by pinyin (the codepoint appended on a
collision, e.g. `robopaint-kaishu-shu-66f8-i00`); `[metadata].family = "robopaint_<family>_<target>"`.
- RoboPaint-strict: `<base>` is `robopaint-strict-<family>-<target>-i<NN>` (RoboPaint's pair with process rules);
diff --git a/docs/benchmarks/dexjoco.md b/docs/benchmarks/dexjoco.md
new file mode 100644
index 0000000000..bce38ec4cb
--- /dev/null
+++ b/docs/benchmarks/dexjoco.md
@@ -0,0 +1,97 @@
+# DexJoCo
+
+Dexterous manipulation with a 16-DoF Allegro hand on a Franka Panda arm (or two of them), from DexJoCo
+([brave-eai/dexjoco](https://github.com/brave-eai/dexjoco), MIT): its 11 tasks, each on one frozen scene instance taken
+from a public human demonstration, in both modes (`scripts/dexjoco/`).
+
+| | |
+|---|---|
+| upstream | DexJoCo @ `8d23b0f` (MIT); human demonstrations: Hugging Face dataset `DexJoCo/DexJoCo-Datasets-Raw` (public) |
+| simulator | `dexjoco`: DexJoCo's gymnasium envs on MuJoCo 3.4.0, CPU physics (bit-exact replay in a fresh process), OSMesa rendering; no GPU |
+| robots | `franka-allegro` (6 tasks), `franka-allegro-bimanual` (5 tasks, two arms side by side) |
+| score | binary: DexJoCo's own success check (its episode ends at the first success or task failure); `water_plant` adds an aiming condition (below) |
+| tasks | 11 families × 2 modes: `tasks/dexjoco-<family>-i00-privileged` and `-standard` (`eai-standard/2.2`) |
+| image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` (`images/dexjoco/`: DexJoCo @ 8d23b0f and its pinned dependency closure; no demonstrations, no policies) |
+| oracle | full, both modes: the demonstration's own actions |
+| agent time budget | 5400 s for every task (D8: dexterous control of 16 hand joints per arm through a thin interface; the model runs we made used most of it) |
+| egress | allowlisted to the model APIs in both modes: the reference demonstrations are public (PROTOCOL §2.7) |
+
+## Tasks
+
+| family | robot | asks | oracle rows (50 Hz) |
+|---|---|---|---|
+| water_plant | single | spray the plant: the trigger held while the nozzle is near the plant and aimed at it, 30 steps | 307 |
+| click_mouse | single | put the mouse on the pad and click, then keep it there 10 steps | 560 |
+| hammer_nail | single | drive the nail at least 4 cm deep with counted strikes | 202 |
+| pick_bucket | single | put the boxed food into the bucket and lift the bucket 15 cm | 580 |
+| pinch_tongs | single | three pinches with the tongs held 10 cm up, then 30 steps | 375 |
+| fold_glasses | single | fold both temples and put the glasses into the case, 50 steps | 612 |
+| bimanual_hanoi | bimanual | the three-disk tower moved to post C, 20 steps; an illegal stack fails | 1085 |
+| bimanual_microwave_cook | bimanual | hot dog in, door closed, start pressed | 815 |
+| bimanual_unlock_ipad | bimanual | enter 1-2-3 with a fingertip, unlocked 10 steps; a wrong digit fails | 392 |
+| bimanual_assembly | bimanual | peg into the tray's socket, touching the bottom 30 steps | 586 |
+| bimanual_photograph | bimanual | camera held 0.4 m in front of the logo, axis within 10 deg, shutter pressed | 260 |
+
+## Task definition
+- **Instance.** The task's env after DexJoCo's reset, with the initial object poses and table height of one human
+ demonstration restored by DexJoCo's own state restorer (demo `state[0]`). DexJoCo's reset samples poses from the
+ global RNG and its restorers edit the MuJoCo model (table height, fixed bodies), so the instance is a snapshot, not a
+ seed: `instance.npz` holds the full physics state (`mjSTATE_INTEGRATION`), mocap targets, controls, every numeric
+ `MjModel` array a task can change, and the env's Python-side task state (counters, flags). Its hash is checked
+ whenever a task rebuilds it (privileged verifier, standard service, every replay).
+- **Action.** DexJoCo's own row per control step (50 Hz, 10 physics substeps of 2 ms): per arm the tcp target pose
+ (xyz, quaternion wxyz, world frame), which DexJoCo's operational-space controller tracks, and 16 Allegro joint targets.
+ Single arm 23 values, bimanual 46 (right first; the left hand's fingers in DexJoCo's mirrored order).
+- **Episode.** As in DexJoCo's evaluation: it ends at the first success or task failure. DexJoCo's episode cap, its
+ real-time pacing, its per-step camera rendering and hanoi's wall-clock auto-reset are lifted (`rcb_dexjoco.py`):
+ the wall clock is the only budget.
+- **water_plant.** Upstream's zone + trigger test passes with the bottle lying on the table and spraying away from the
+ plant (two Opus 5.5 runs did exactly that). The task also requires the spray direction (the bottle's local +z) within
+ 45 deg of the nozzle-to-plant line, held with the rest for 30 steps; the demonstration sprays 33 deg off.
+
+## Privileged mode
+`rcb_dexjoco.Session` on the frozen instance: unlimited exact resets, live object poses (`s.objects()`), DexJoCo's state
+dict, thin primitives (tcp-target moves, hand-joint interpolation, hold), rendering, recording and self-replay. The
+deliverable is `/app/output/trajectory.npz`; the verifier replays it twice in a fresh process from its own copy of the
+instance: success = both replays succeed ∧ same final-state hash ∧ the instance rebuilt exactly.
+
+## Standard mode (`eai-standard/2.2`)
+The 2.2 adapter `scripts/dexjoco/shared/standard/server.py` on the shared layer (`scripts/eai_standard/`, copied
+unchanged), resume class `exact`:
+- **actions:** `ee_pose` (DexJoCo's own row) and `joint_position` (per arm 7 arm + 16 hand joint targets; the arm part
+ becomes a tcp target by forward kinematics, the same controller tracks it). The service journals and records the
+ executed DexJoCo row, so the recorded trajectory replays in the privileged tooling unchanged.
+- **observations:** every camera of the scene (static `front`, `back`, `left`, `right`, `top0`; the hand cameras on each
+ hand's mount) at 640 x 480 with calibration (static pose or mount link), optional z-depth from the same renderer;
+ proprioception `joint_pos`, `joint_vel`, `joint_effort` (7 + 16 per arm), `tcp_pose`, plus `tcp_target` and
+ `hand_target` (the targets being tracked); no gripper-opening column (a dexterous hand).
+- **kinematics:** stateless FK of the arm links, the hand mount and the tcp; IK of each tcp over its arm's 7 joints
+ (damped least squares within the joint ranges).
+- **robot_spec:** joints with the simulator's limits (arm torque limits; hand position actuators unlimited in effort),
+ the hand drives' gains, the tcp definition (DexJoCo's `attachment_site`, the flange), the arm bases.
+- **evidence and grading:** the collect hook (`finalize.sh`) ends the service, replays the recorded trajectory in two
+ fresh processes and renders `replay.mp4` in a third; success = live ∧ both replays ∧ deterministic.
+- `ci_checks/check-limited-protocol.py` passes against a live service of a single-arm and a bimanual task (velocity limits are null:
+ WARN only). Crash recovery: the service killed between calls and inside a call resumes the same episode
+ (`resumes = 2`, exact hash) and the oracle still ends in success with `live_matches_replay`.
+
+## World-frame information (D7)
+Privileged mode gives world coordinates (object poses through the tooling, the table height and the arm bases in the
+instruction). Standard mode gives the robot's own pose only: each arm's base pose in `robot_spec`, the tcp in
+proprioception, the cameras' calibration; no table height, no object or workspace coordinates in `/spec` or the texts.
+The goals state their thresholds as relative distances (e.g. "within 0.20 m of the plant").
+
+## Reference solutions
+The demonstration's own actions (`scripts/dexjoco/instances/<family>/oracle_trajectory.npz`, built by
+`make_instances.py` in the image), replayed until the episode ends in success. The standard client sends float32, so
+the rows are rounded to float32 for both modes; every family still succeeds, `bimanual_hanoi` after holding its last row
+8 more steps (the rounded rows end its 20-step hold count short). Standard mode streams the same rows through the client
+as `ee_pose` chunks; the recorded trajectory is then exactly the privileged reference.
+
+## Regenerating
+```bash
+python3 scripts/dexjoco/get_demo.py water_plant 1 /tmp/demos # only to rebuild an instance from its demo
+docker run --rm --user $(id -u):$(id -g) -e HOME=/tmp -v $PWD:/repo -w /repo ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2 \
+ python scripts/dexjoco/make_instances.py --all # check the instances and oracles, refresh facts.json
+python3 scripts/dexjoco/generate.py && python3 scripts/dexjoco/generate.py --check
+```
diff --git a/images/dexjoco/Dockerfile b/images/dexjoco/Dockerfile
new file mode 100644
index 0000000000..d85964e8a9
--- /dev/null
+++ b/images/dexjoco/Dockerfile
@@ -0,0 +1,21 @@
+# eai-dexjoco: DexJoCo (brave-eai/dexjoco @ 8d23b0f, MIT) on MuJoCo 3.4.0, Franka Panda + 16-DoF Allegro hand (one or two
+# arms), 11 tasks. Infrastructure only: the upstream package and its dependencies, pinned (requirements.txt = the closure
+# that rcb-dexjoco:0.1.1 resolved, frozen with `pip freeze`); no benchmark code, no demonstrations, no policies.
+# Physics and rendering both run on the CPU (MuJoCo + OSMesa), so the image needs no GPU.
+# Build from the repo root: scripts/build_images.sh (tag = images/dexjoco/VERSION). docs/benchmarks/dexjoco.md.
+FROM python@sha256:e41613d42d4891e4930f79523f93f81bbc7632584ec65e36ab055f41a800b41e
+ARG DEXJOCO_COMMIT=8d23b0fab23b17a58c4b55f3942e17013aaf8267
+RUN apt-get update && apt-get install -y --no-install-recommends git libosmesa6 libgl1 libglfw3 libegl1 ffmpeg && \
+ rm -rf /var/lib/apt/lists/*
+# Clone, check out and prune in ONE layer: nothing removed here survives in an earlier layer of the published image.
+# Removed: the git history, the openpi examples and assets (policy configs and norm stats), the teleoperation stack and
+# the docs' pictures. DexJoCo's human demonstrations are not in the repository (they are on Hugging Face).
+RUN git clone https://github.com/brave-eai/dexjoco.git /opt/dexjoco && cd /opt/dexjoco && \
+ git checkout ${DEXJOCO_COMMIT} && rm -rf .git openpi/examples openpi/assets docs/pics teleoperation
+COPY images/dexjoco/requirements.txt /tmp/requirements.txt
+RUN pip install --no-cache-dir -r /tmp/requirements.txt && \
+ pip install --no-cache-dir --no-deps -e /opt/dexjoco/dexjoco /opt/dexjoco/openpi/packages/openpi-client && \
+ pip check
+ENV MUJOCO_GL=osmesa PYOPENGL_PLATFORM=osmesa PYTHONUNBUFFERED=1 DEXJOCO_ROOT=/opt/dexjoco
+RUN python -c "from dexjoco.tasks.mappings import CONFIG_MAPPING; print(sorted(CONFIG_MAPPING))"
+WORKDIR /app
diff --git a/images/dexjoco/VERSION b/images/dexjoco/VERSION
new file mode 100644
index 0000000000..d917d3e26a
--- /dev/null
+++ b/images/dexjoco/VERSION
@@ -0,0 +1 @@
+0.1.2
diff --git a/images/dexjoco/requirements.txt b/images/dexjoco/requirements.txt
new file mode 100644
index 0000000000..94deb92dfe
--- /dev/null
+++ b/images/dexjoco/requirements.txt
@@ -0,0 +1,46 @@
+# eai-dexjoco pip pins: the closure rcb-dexjoco:0.1.1 resolved for DexJoCo @ 8d23b0f (dexjoco + openpi-client and their
+# dependencies), frozen with `pip freeze` on 2026-10-06. dexjoco and openpi-client themselves are installed --no-deps
+# from the clone. A change here is a new image version (frozen-instance hashes depend on mujoco and numpy).
+absl-py==2.5.0
+asciitree==0.3.3
+attrs==26.1.0
+av==18.1.0
+click==8.5.0
+cloudpickle==3.1.2
+Deprecated==1.3.1
+dm-tree==0.1.10
+dm_robotics-transformations==0.9.0
+docstring_parser==0.18.0
+etils==1.14.0
+Farama-Notifications==0.0.6
+fasteners==0.20
+fsspec==2026.9.0
+glfw==2.10.2
+gymnasium==1.0.0
+ImageIO==2.37.4
+imageio-ffmpeg==0.6.0
+jax==0.7.1
+jaxlib==0.7.1
+ml_dtypes==0.5.4
+msgpack==1.2.2
+mujoco==3.4.0
+numcodecs==0.15.1
+numpy==1.26.4
+opencv-python==4.11.0.86
+opt_einsum==3.4.0
+packaging==26.3
+pillow==12.3.0
+psutil==7.2.2
+PyOpenGL==3.1.10
+PyYAML==6.0.3
+scipy==1.17.1
+svgwrite==1.4.3
+tqdm==4.70.1
+Tree==0.2.4
+typeguard==4.6.0
+typing_extensions==4.16.0
+tyro==1.0.16
+websockets==17.1
+wrapt==2.5.0
+zarr==2.18.7
+zipp==4.1.0
diff --git a/scripts/dexjoco/generate.py b/scripts/dexjoco/generate.py
new file mode 100644
index 0000000000..0c85105bd7
--- /dev/null
+++ b/scripts/dexjoco/generate.py
@@ -0,0 +1,699 @@
+#!/usr/bin/env python3
+"""Generate the DexJoCo tasks: tasks/dexjoco-<family>-i00-privileged and -standard for the 11 DexJoCo families.
+
+ python3 scripts/dexjoco/generate.py # (re)write all 22 task directories
+ python3 scripts/dexjoco/generate.py --check # exit 1 if tasks/ differs from what this would write
+
+Standard library only (plus scripts/task_conventions.py, which every generator ends with). Inputs:
+ scripts/dexjoco/instances/<family>/{instance.npz, oracle_trajectory.npz, facts.json} (make_instances.py, in the image)
+ scripts/dexjoco/shared/ the tooling rcb_dexjoco.py, the privileged grader, the standard adapter and its hooks
+ scripts/eai_standard/ the eai-standard/2.2 layer (client, service layer, run.sh, client image and pins)
+The texts are the templates below. docs/benchmarks/dexjoco.md describes the benchmark.
+"""
+from __future__ import annotations
+
+import filecmp
+import json
+import shutil
+import stat
+import sys
+import tempfile
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+ROOT = HERE.parent.parent
+SHARED = HERE / "shared"
+LAYER = ROOT / "scripts" / "eai_standard"
+sys.path.insert(0, str(ROOT / "scripts"))
+from task_conventions import normalize # noqa: E402
+
+IMAGE = "ghcr.io/mll-lab-nu/eai-dexjoco:" + (ROOT / "images" / "dexjoco" / "VERSION").read_text().strip()
+CLIENT_ENV = dict(l.split("=", 1) for l in (LAYER / "client.env").read_text().splitlines() if "=" in l and not l.startswith("#"))
+CLIENT_IMAGE = CLIENT_ENV["CLIENT_IMAGE"].strip()
+AGENT_TIMEOUT = 5400 # 1.5 h for the whole benchmark (PROTOCOL D8): dexterous control of a 16-DoF hand per arm
+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"]
+
+# Per family: the goal in words (the standard twin never sees the code, so it is complete), what the scene holds, the
+# extra rule robot_coding_bench adds, the static camera the texts name first, the difficulty and the expert time.
+FAMILIES: dict[str, dict] = {
+ "water_plant": dict(
+ goal=("Pick up the spray bottle, point its nozzle at the potted plant and squeeze the trigger. Success: the "
+ "trigger is held pulled (trigger joint > 0.34 rad; it counts as released again below 0.25 rad) while the "
+ "nozzle reference point is within 0.20 m of the plant horizontally and within +-0.20 m of the plant's "
+ "height AND the spray points at the plant, all three for 30 consecutive control steps (0.6 s). The spray "
+ "leaves the spray head horizontally forward: perpendicular to the bottle's long axis, on the side the "
+ "trigger faces (the bottle's local +z; its long axis, bottom to head, is local +y). It points at the "
+ "plant when that direction is within 45 degrees of the line from the nozzle to the plant, e.g. with the "
+ "bottle held upright and its trigger side facing the plant. "
+ "Pulling the trigger while the nozzle is outside the zone ends the episode as a failure."),
+ rcb_rule=("robot_coding_bench adds the aiming condition to DexJoCo's check: upstream's zone + trigger test alone "
+ "passes with the bottle lying on the table and spraying away from the plant. The episode ends in "
+ "success only when `_compute_success`'s zone + trigger condition and the aim below hold together for "
+ "30 consecutive steps (`status()['info']` reports `aim_deg` and `rcb_success_count`); DexJoCo's own "
+ "`succeed` flag alone no longer ends it."),
+ scene=("The spray bottle stands on the table to the robot's right-front, the potted plant further along +y. The "
+ "trigger is a hinge on the bottle's neck that the index and middle fingers can pull back."),
+ difficulty="medium", hours=1.5),
+ "click_mouse": dict(
+ goal=("Put the computer mouse on the magenta mousepad and click its button. Success: the mouse is on the pad "
+ "(its centre within the pad's 0.15 m radius horizontally and within 0.05 m of the pad's height), the "
+ "button has been pressed while the mouse was on the pad (button joint more than 0.001 rad past its rest "
+ "angle), which turns the monitor blue, and the mouse then stays on the pad for 10 consecutive control "
+ "steps. A click while the mouse is off the pad does nothing."),
+ scene=("The mouse lies on the table in front of the monitor; the round magenta mousepad is next to it at lower y. "
+ "The button is a hinge on the mouse's front half."),
+ difficulty="medium", hours=1.5),
+ "hammer_nail": dict(
+ goal=("Pick up the hammer and drive the nail into the wooden block by striking its head. A strike counts only if "
+ "the hammer face was moving down faster than 0.02 m/s just before it touched the nail; each counted "
+ "strike drives the nail 8 mm x min(3, speed / 0.02) deeper (at most 7.26 cm). Success: the nail is at "
+ "least 4 cm deep."),
+ scene=("The hammer lies on the table at the robot's right (low y); the nail stands upright in a wooden block in "
+ "front of the robot. The nail is not a free body: it only moves down when struck."),
+ difficulty="hard", hours=2.0),
+ "bimanual_hanoi": dict(
+ goal=("Tower of Hanoi with three disks on three vertical posts in a row along y: the small disk is on post A "
+ "(y > 0, the left arm's side), the medium disk on post B (middle), the large disk on post C (y < 0). Build "
+ "the full tower on post C: large at the bottom, then medium, then small, posts A and B empty, every disk "
+ "at rest and seated on the post (horizontally within 4 cm of it, at its stacking height within 1.2 cm), "
+ "held for 20 consecutive control steps. A larger disk resting on a smaller one, or a disk resting on the "
+ "table, for 10 consecutive steps ends the episode as a failure."),
+ scene=("Two arms with a hand each stand side by side facing the table (right arm at y < 0, left arm at y > 0); the "
+ "wooden Hanoi base with its three posts is in front of them. Each disk has a hole and slides over a post."),
+ difficulty="medium", hours=2.0),
+ "pick_bucket": dict(
+ goal=("Put the boxed food into the bucket, then lift the bucket. Success: the boxed food's centre is inside the "
+ "bounding box of the bucket's eight reference corners AND the bucket's bottom is at least 0.15 m above "
+ "where it started, at the same control step."),
+ scene=("The bucket stands on the table with a hinged handle over it; the boxed food lies next to it. The handle "
+ "swings on a hinge (`bucket_handle`)."),
+ difficulty="medium", hours=2.0),
+ "pinch_tongs": dict(
+ goal=("Pick up the tongs and open and close them three times while holding them up. A pinch counts each time the "
+ "tongs' hinge goes from open (>= 0.1 rad) to closed (<= -0.07 rad). Success: at least three pinches counted "
+ "and the tongs at least 0.10 m above the table, held for 30 consecutive control steps."),
+ scene="The kitchen tongs lie on the table in front of the robot; their two arms are joined by a hinge (`tongs_hinge`).",
+ difficulty="medium", hours=2.0),
+ "fold_glasses": dict(
+ goal=("Fold both temples of the glasses and put the glasses into the open case. Success: both temple hinges past "
+ "1.1 rad AND the glasses' centre inside the case (within 0.145 m of the case centre in x and y, between "
+ "0.045 m below and 0.0275 m above it), held for 50 consecutive control steps."),
+ scene="Open glasses lie on the table; the open case is next to them. Each temple is a hinge (`temple_0`, `temple_1`).",
+ difficulty="hard", hours=2.5),
+ "bimanual_microwave_cook": dict(
+ goal=("Open the microwave door, put the hot dog inside, close the door and press the start button. Success, at one "
+ "control step: the hot dog is inside the cavity (1 cm margin), the door hinge is within 0.01 rad of closed, "
+ "and the start button is in contact with something."),
+ scene=("The microwave stands on the table with its door closed; the hot dog lies in front of it. The door has a "
+ "handle and a hinge (`door_hinge`); the start and stop buttons are on the front panel."),
+ difficulty="hard", hours=3.0),
+ "bimanual_unlock_ipad": dict(
+ goal=("Pick up the iPad and enter the passcode 1-2-3 on its screen. A digit is pressed when a FINGERTIP touches its "
+ "button; pressing any other digit than the next one of 1-2-3 ends the episode as a failure. Success: the "
+ "screen is unlocked (1, 2, 3 in order) and stays unlocked for 10 consecutive control steps."),
+ scene="The iPad rests on a stand on the table, screen facing the robots; its keypad shows the digits.",
+ difficulty="hard", hours=2.5),
+ "bimanual_assembly": dict(
+ goal=("Hold the tray with one hand and insert the round peg into its socket with the other. Success: the peg "
+ "touches the socket's bottom for 30 consecutive control steps."),
+ scene="The tray with a round socket and the 8 mm round peg lie on the table in front of the robots.",
+ difficulty="hard", hours=2.5),
+ "bimanual_photograph": dict(
+ goal=("Hold the camera with the left hand in front of the logo and press its shutter with the right hand. Success, at "
+ "one control step: the camera's view point is inside the target region (0.16 m radius, +-0.10 m height, "
+ "0.40 m in front of the logo along -x, i.e. about 0.3 m above the table), the camera's viewing axis is "
+ "within 10 degrees of world +x, and the shutter button is touched by something other than the camera."),
+ scene="The camera lies on the table between the robots; the logo disk stands at the far side of the table.",
+ difficulty="hard", hours=2.5),
+}
+
+
+def dash(fam: str) -> str:
+ return fam.replace("_", "-")
+
+
+def facts(fam: str) -> dict:
+ return json.loads((HERE / "instances" / fam / "facts.json").read_text())
+
+
+def write(path: Path, text: str, executable: bool = False) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text)
+ mode = 0o755 if executable else 0o644
+ path.chmod(mode)
+
+
+def copy(src: Path, dst: Path) -> None:
+ dst.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(src, dst)
+ dst.chmod(0o755 if src.suffix == ".sh" else 0o644)
+
+
+def robot_words(fam: str) -> str:
+ return ("two Franka Panda arms, each with a 16-DoF Allegro hand" if fam.startswith("bimanual_")
+ else "a Franka Panda arm with a 16-DoF Allegro hand")
+
+
+def robot_id(fam: str) -> str:
+ return "franka-allegro-bimanual" if fam.startswith("bimanual_") else "franka-allegro"
+
+
+# ------------------------------------------------------------------------------------------------- privileged mode
+def priv_instruction(fam: str, F: dict) -> str:
+ f = FAMILIES[fam]
+ bim = fam.startswith("bimanual_")
+ adim = 46 if bim else 23
+ arm = '"right"'
+ objs = ", ".join(f"`{k}`" for k in F["objects"])
+ cam0 = "front" if "front" in F["cameras"] else F["cameras"][0]
+ extra = ""
+ if f.get("rcb_rule"):
+ extra = f"\n\n{f['rcb_rule']}\n```python\nWATER_AIM_MAX_DEG = {F['water_aim_max_deg']}\n\n{F['rcb_src']}\n```"
+ frame = (f"The table top is at z = {F['table_top_z']:.3f}. " if F["table_top_z"] is not None else "")
+ frame += "Arm base (`link0`): " + ", ".join(f"{n} {v}" for n, v in F["arm_bases"].items()) + "."
+ if bim:
+ frame += " The right arm works at y < 0, the left arm at y > 0."
+ return f"""# DexJoCo · {fam} — frozen instance
+
+You control {robot_words(fam)} (DexJoCo on MuJoCo 3.4) via Python. **Task:** {f["goal"]}
+
+{f["scene"]} `s.objects()` gives the live poses of the task objects ({objs}). DexJoCo's success code (from
+`/opt/dexjoco/{F["success_path"]}`; `step()` ends the episode on success or on a task failure):
+```python
+{F["success_src"]}
+```{extra}
+
+This is a *fixed scene instance*: object poses, the table height and the robot's start pose never change between
+resets. You may reset and retry as many times as you want. Your deliverable is **one replayable trajectory**, not a
+general policy.
+
+## Deliverable
+Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
+open-loop from the same initial state in a fresh process and scored 1 if its episode ends in success, else 0. Also
+leave the script that produced it at `/app/output/gen.py`. You have {AGENT_TIMEOUT // 60} minutes of wall clock: save a
+first trajectory early, improve it, and do not stop before the task is solved.
+
+## Tooling (already installed; run `python` from any directory)
+```python
+from rcb_dexjoco import Session
+s = Session("{fam}", instance="/app/instance.npz") # ~1 s: builds the env and loads the frozen state
+s.reset() # back to the frozen initial state (as often as you like; an exact snapshot restore)
+s.objects() # live task objects: name -> pos, quat_wxyz (bodies) / pos (sites) / qpos (joints)
+s.state() # DexJoCo's state dict: tcp_pose, gripper_pose (hand joints), INITIAL object poses, table height
+p = s.primitives() # thin wrappers of the low-level action; each has a docstring: help(p["move_ee"])
+p["move_ee"]({arm}, pos, quat_wxyz) # straight-line + slerp motion of an arm's tcp target, then settle
+p["set_hand"]({arm}, q16) # interpolate the 16 Allegro joint targets
+p["hold"](10); p["set_targets"](row, steps) # keep every target / send one raw action row
+p["get_ee_pose"]({arm}); p["get_ee_target"]({arm}); p["get_hand"]({arm}); p["get_body_pose"](name)
+s.render_frame("{cam0}") # RGB uint8 (480, 640, 3); cameras: {F["cameras"]}; s.render_grid()
+s.step(action) # one control step ({adim} values, below) = 1/50 s; returns False once the episode is over
+s.record_start(); ...; actions = s.record_stop() # (T, {adim}) actions, one row per control step
+s.status() # {{'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}}
+s.replay(actions) # resets, replays open-loop until the episode ends, returns status -> self-check
+s.save_trajectory(actions, "/app/output/trajectory.npz")
+s.render_video(actions, "/app/output/check.mp4", cameras=["{cam0}"]) # replays from the frozen state into a video
+```
+The primitives are deliberately thin (tcp target moves, hand joint targets, hold): grasping, pressing, striking and
+every other skill are yours to build from them. `s.bodies()` lists every MuJoCo body for `p["get_body_pose"]`.
+
+CLI equivalent of the grader:
+`python /opt/tools/rcb_dexjoco.py replay --task {fam} --instance /app/instance.npz --traj /app/output/trajectory.npz`
+
+## Conventions
+- World frame, metres; z up; the robot{"s" if bim else ""} stand{"" if bim else "s"} at low x and reach{"" if bim else "es"} towards +x. {frame} Quaternions are **WXYZ**.
+- Action ({adim}): {"per arm, right first: " if bim else ""}tcp target position (3), tcp target orientation (4, wxyz), 16 Allegro
+ joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+ target and stops where contact blocks it); the hand joints are position-controlled. `s.hold_action()` is the no-op.
+ At the start the tcp target is {F["tcp0"]}.
+- Allegro joint order{" (right hand)" if bim else ""}: index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger =
+ spread, 1-3 = flexion from the knuckle out; thumb 12 = opposition).{" The LEFT hand's 16 values are mirrored: ring 0-3, middle 4-7, index 8-11, thumb 12-15." if bim else ""}
+ Target ranges (rad, same for every finger slot, thumb last): low {F["hand_lo"]}, high {F["hand_hi"]}; the simulator clamps
+ targets to them.
+- Control runs at 50 Hz (10 physics substeps of 2 ms). DexJoCo's own episode cap and real-time pacing are lifted: there
+ is no step budget, your wall-clock time is the limit (~{F["steps_per_s"]} control steps/s here). An episode ends at the
+ first success or task failure; `s.step` then refuses further actions until `s.reset()`.
+"""
+
+
+def priv_readme(fam: str, F: dict) -> str:
+ f = FAMILIES[fam]
+ return f"""# dexjoco-{dash(fam)}-i00-privileged
+
+## Task
+DexJoCo `{fam}` ({robot_words(fam)}): {f["goal"]}
+Privileged mode: the agent works in the simulator's container with live object poses, unlimited resets and thin motion
+primitives, and hands in one trajectory replayed open-loop from the frozen instance.
+
+## Difficulty
+First-pass rating: {f["difficulty"]}. Dexterous manipulation with {"two 16-DoF hands on two arms (46 action values per control step)" if fam.startswith("bimanual_") else "a 16-DoF hand on a 7-DoF arm (23 action values per control step)"};
+the primitives only move tcp and hand-joint targets, so grasping, pressing and every other skill is the agent's. The
+reference (the human teleoperator's demonstration) takes {F["oracle_rows"]} control steps ({F["oracle_rows"] / 50:.1f} s at 50 Hz).
+
+## Reference solution
+`solution/oracle_trajectory.npz` = the human demonstration's own actions, rounded to float32 (the standard client's
+precision; the rounded rows still succeed) and replayed from the frozen instance until the episode ends in success
+({F["oracle_rows"]} rows). The demonstration is public (DexJoCo-Datasets-Raw on Hugging Face), so agent egress is
+limited to the model APIs.
+
+## Verification
+Open-loop replay of `/app/output/trajectory.npz` from `tests/instance.npz`, twice in a fresh process in the verifier's own
+sandbox (no network); pass iff both episodes end in success, their final-state hashes agree and the rebuilt instance
+matches its recorded hash (`tests/grade.py`); plus `/logs/verifier/replay.mp4`. Oracle: success after {F["oracle_rows"]} control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `{F["demo"]}` (DexJoCo-Datasets-Raw), restored with DexJoCo's own state restorer; instance sha `{F["instance_sha"]}` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Tooling notes
+DexJoCo's reset samples object poses from the global RNG and its state restorer edits the MuJoCo model (table height,
+fixed bodies), so `instance.npz` stores the full physics state (`mjSTATE_INTEGRATION`), the mocap targets, the controls,
+every numeric model array a task can change, and the env's Python-side task state. Its per-step camera rendering,
+real-time sleep, episode cap and hanoi's wall-clock auto-reset are disabled in the tooling (`rcb_dexjoco.py`).
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py` from `scripts/dexjoco/instances/{fam}/` (`make_instances.py`).
+"""
+
+
+def priv_toml(fam: str) -> str:
+ f = FAMILIES[fam]
+ return f"""# Generated by scripts/dexjoco/generate.py -- edit the generator or the instance, not this.
+schema_version = "1.3"
+artifacts = ["/app/output/"]
+
+[task]
+name = "robot-coding-bench/dexjoco-{dash(fam)}-i00-privileged"
+description = "DexJoCo {fam} ({robot_words(fam)}, MuJoCo): produce one replayable trajectory. {f["goal"].split(". ")[0]}. Frozen scene instance (the initial state of a DexJoCo human demonstration)."
+authors = [{{ name = "Chi Gui" }}]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "code-as-policy", "trajectory", "{fam}"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "{robot_id(fam)}"
+family = "{fam}"
+mode = "privileged"
+oracle = "full"
+expert_time_estimate_hours = {f["hours"]}
+
+[verifier]
+timeout_sec = 1800.0
+environment_mode = "separate" # the verifier runs in its own sandbox (tests/Dockerfile); the agent container is gone by then
+network_mode = "no-network"
+
+[agent]
+timeout_sec = {float(AGENT_TIMEOUT)}
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+allowed_hosts = {json.dumps(ALLOWED_HOSTS)}
+
+[environment]
+build_timeout_sec = 1800.0
+cpus = 4
+memory_mb = 8192
+
+[verifier.environment]
+build_timeout_sec = 1800.0
+"""
+
+
+PRIV_ENV_DOCKERFILE = f"""# Base image = DexJoCo on MuJoCo 3.4.0 (images/dexjoco/). Everything task-specific is copied here. CPU only.
+FROM {IMAGE}
+COPY instance.npz /app/instance.npz
+COPY rcb_dexjoco.py /opt/tools/rcb_dexjoco.py
+ENV PYTHONPATH=/opt/tools
+RUN mkdir -p /app/output
+WORKDIR /app
+"""
+
+PRIV_TESTS_DOCKERFILE = f"""# Separate verifier sandbox (PROTOCOL §2.6): the same simulator image with the verifier's own copies of the tooling and
+# the frozen instance baked in. Nothing the agent did in its container reaches this one: Harbor uploads only the declared
+# artifacts (/app/output/), so a patched success check in the agent container cannot count.
+FROM {IMAGE}
+COPY grade.py instance.npz rcb_dexjoco.py test.sh /tests/
+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
+ENV PYTHONPATH=/tests
+WORKDIR /tests
+"""
+
+
+def priv_test_sh(fam: str) -> str:
+ return f"""#!/bin/bash
+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in a fresh process.
+# 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/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)
+mkdir -p /logs/verifier
+python /tests/grade.py --family {fam} --instance /tests/instance.npz --traj /app/output/trajectory.npz --repeat 2 \\
+ 2> /logs/verifier/grade.log
+"""
+
+
+PRIV_SOLVE = """#!/bin/bash
+# Reference solution: the human demonstration's actions (float32), replayed through the task tooling until success.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_trajectory.npz /app/output/trajectory.npz
+cp /solution/gen.py /app/output/gen.py
+"""
+
+PRIV_ORACLE_GEN = """# How solution/oracle_trajectory.npz was made (scripts/dexjoco/make_instances.py): the DexJoCo human demonstration's
+# own actions (replay.zarr data/action), rounded to float32, replayed from the frozen instance with Session.replay until
+# the episode ended in success (holding the last row a few steps where the rounded rows ended short of a hold count),
+# truncated there and saved with Session.save_trajectory.
+"""
+
+
+# ------------------------------------------------------------------------------------------------- standard mode
+def task_text(fam: str) -> str:
+ f = FAMILIES[fam]
+ return f"{f['goal']}\n\n{f['scene']}\n"
+
+
+def std_instruction(fam: str, F: dict) -> str:
+ f = FAMILIES[fam]
+ bim = fam.startswith("bimanual_")
+ dim = 46 if bim else 23
+ hand_cams = [c for c in F["cameras"] if c.startswith("handcam")]
+ static = [c for c in F["cameras"] if not c.startswith("handcam")]
+ cam0 = "front" if "front" in static else static[0]
+ tcp = "`tcp_right`, `tcp_left`" if bim else "`tcp`"
+ return f"""# DexJoCo · {fam} — STANDARD MODE (robot as a service, eai-standard/2.2)
+
+You control {robot_words(fam)}, **as if it were real hardware**: the simulator runs in a service you cannot open. You get
+one client and one episode. **Task:** {f["goal"]}
+
+{f["scene"]}
+
+## Rules (real-robot rules)
+- **No reset.** The episode starts when the service comes up and ends on success, on a task failure (see the task), when
+ your time is up, or on a simulator error. Knocked-over objects stay knocked over.
+- **No privileged state.** You see what the cameras see (RGB, and depth on request, with each camera's calibration) plus
+ the robot's own proprioception (joints, tcp poses, the current targets). No object poses, no success check:
+ `meta["done"]` / `meta["reason"]` tell you when the episode is over and why.
+- Steps are unlimited; your wall-clock budget ({AGENT_TIMEOUT // 60} minutes) is the limit (`meta["time_left_s"]`). Actions and
+ simulated time are reported as cost. Do not stop before the task is solved.
+- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
+ `/app/output/gen.py` for the record (save it early, update it as you go).
+- **Nothing is put into your context automatically.** Images and videos come back as arrays/bytes in a Python object;
+ what you look at and where you store it is your code's decision.
+
+## Client (`/opt/tools/rcb_client.py`, protocol `eai-standard/2.2`)
+```python
+from rcb_client import Robot
+r = Robot() # connects (waits while the service starts)
+spec = r.spec() # action types, cameras (+ calibration), proprio layout, robot_spec, kinematics, budget
+obs = r.get_obs() # current frames of spec["default_cameras"]: obs.last[cam] -> uint8 (480, 640, 3)
+obs = r.get_obs(cameras=["{cam0}"{', "' + hand_cams[0] + '"' if hand_cams else ""}], depth=True) # + obs.last_depth[cam] -> float32 (480, 640) z-depth (m)
+obs.meta["proprio"] # {{"layout": [...], "now": [...]}}; obs.group("tcp_pose", now=True)
+obs.meta["cameras"] # per camera intrinsic_cv / extrinsic_cv / cam2world_gl for these frames
+obs = r.get_obs(seconds=2.0, video="mp4") # hold the current targets and watch for 2 s (max 30): obs.video[cam] = mp4 bytes
+
+res = r.submit("ee_pose", rows, dt=0.1) # rows: (T, {dim}) targets dt seconds apart, executed at 50 Hz with interpolation
+res = r.submit("joint_position", q_rows, dt=0.1) # (T, {dim}) joint targets instead (see below)
+res.meta["done"], res.meta["reason"], res.meta["clipped"], res.meta["control_steps_chunk"]
+res.video["{cam0}"]; res.last["{cam0}"]; res.proprio # mp4 of the chunk, last frame, float32 (N, P) proprio per frame
+res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, proprio.npy, ...
+r.fk(q); r.ik({{"{"tcp_right" if bim else "tcp"}": pose}}, seed=q) # kinematics of the robot (stateless: no physics, no time)
+r.status() # calls, control steps, done, reason, elapsed time
+```
+Cameras: {", ".join(f"`{c}`" for c in static)} (static), {", ".join(f"`{c}`" for c in hand_cams)} (on the hand mount{"s" if bim else ""}; they move,
+so use the calibration that comes with each response; `spec["cameras"][cam]["mount"]` gives the static pose or the mount
+link). Resolution 640x480. Rendering runs on the CPU: ask only for the cameras you need; `video="none"` makes a chunk
+fastest. If a call fails with a connection error the service may have crashed: it resumes the same episode;
+`r.wait_ready()`, then check `r.status()` (`spec["on_service_error"]`).
+
+### Action type `ee_pose` ({dim}) — DexJoCo's own action
+{"Per arm, right first: " if bim else ""}tcp target position (3, metres, world frame), tcp target orientation (4, quaternion wxyz), 16
+Allegro joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+target and stops where contact blocks it); the hand joints are position-controlled. Rows are `dt` apart (a whole multiple
+of 1/50 s, at most 0.5 s); between rows positions and joints move linearly and orientations by slerp
+(`interpolate="linear"`) or jump (`"hold"`); a chunk may cover at most 10 s. Hand targets outside the ranges
+(`spec["action_types"]["ee_pose"]["hand_limits"]`) are clamped by the simulator and listed in `meta["clipped"]`. Build
+the next row from the `tcp_target` and `hand_target` proprio groups to move smoothly.
+
+### Action type `joint_position` ({dim})
+{"Per arm, right first: " if bim else ""}7 Panda joint targets, then the 16 Allegro joint targets (rad). The service turns the arm's targets
+into a tcp target by forward kinematics and the same controller tracks it: the tcp reaches FK(q), but the measured arm
+joints may differ from q in the arm's redundant direction (the controller's null space pulls towards a home posture).
+Out-of-limit values are clipped and reported.
+
+## Conventions
+- World frame, metres, z up; the robot{"s" if bim else ""} stand{"" if bim else "s"} at low x and reach{"" if bim else "es"} towards +x{" (right arm at y < 0, left arm at y > 0)" if bim else ""}; each
+ arm's base pose is in `spec["robot_spec"]["base"]`. No other world coordinates are given (D7: the cameras are
+ calibrated, depth is available). Quaternions are **WXYZ**.
+- The tcp ({tcp}) is the hand's mounting flange (`spec["robot_spec"]["tcp"]`), not the fingertips. Allegro joint
+ order{" (right hand)" if bim else ""}: index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger = spread, 1-3 = flexion
+ from the knuckle out; thumb 12 = opposition).{" The LEFT hand's 16 values are mirrored: ring 0-3, middle 4-7, index 8-11, thumb 12-15 (the joint names in `spec[\"proprio_layout\"]` say which)." if bim else ""}
+- Control runs at 50 Hz (10 physics substeps of 2 ms). There is no step budget: your wall-clock time is the limit.
+"""
+
+
+def std_readme(fam: str, F: dict) -> str:
+ f = FAMILIES[fam]
+ return f"""# dexjoco-{dash(fam)}-i00-standard
+
+## Task
+DexJoCo `{fam}` ({robot_words(fam)}) on the same frozen instance as `dexjoco-{dash(fam)}-i00-privileged`: {f["goal"]}
+Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with the robot's own
+sensors, calibrated cameras (RGB, optional depth) and the robot's kinematics.
+
+## Difficulty
+Same instance and success check as `dexjoco-{dash(fam)}-i00-privileged`. In standard mode the agent loses resets, the
+simulator and the object poses: it sees camera images and proprioception, acts in chunks of tcp-target + hand-joint rows
+(or joint targets), and gets one episode, so it has to close the loop on what the cameras show and recover from its own
+mistakes without starting over.
+
+## Reference solution
+`solution/oracle_stream.py` streams the privileged reference's rows (`solution/oracle_trajectory.npz`, {F["oracle_rows"]} rows, float32-exact)
+through the client as `ee_pose` 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 {F["oracle_rows"]} 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 {F["oracle_rows"]} control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `{F["demo"]}` (DexJoCo-Datasets-Raw); instance sha `{F["instance_sha"]}` |
+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); action types `ee_pose` and `joint_position`; cameras {", ".join(f"`{c}`" for c in F["cameras"])} (640 x 480); `/kinematics` for the arm links, the hand mount and the tcp; crash recovery class `exact` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py`, as its privileged twin.
+"""
+
+
+def std_toml(fam: str) -> str:
+ f = FAMILIES[fam]
+ return f"""# Generated by scripts/dexjoco/generate.py -- edit the generator 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/dexjoco-{dash(fam)}-i00-standard"
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): DexJoCo {fam} ({robot_words(fam)}) on the same frozen instance as dexjoco-{dash(fam)}-i00-privileged. {f["goal"].split(". ")[0]}. The agent only gets a client: calibrated cameras (RGB, optional depth), the robot's joints and tcp poses, tcp-target + hand-joint chunks at 50 Hz, the robot's kinematics; one episode, no reset, no object state; the sim service records the episode, replays it in fresh processes and grades it."
+authors = [{{ name = "Chi Gui" }}]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "standard-mode", "robot-as-a-service", "{fam}"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "{robot_id(fam)}"
+family = "{fam}"
+mode = "standard"
+protocol = "eai-standard/2.2"
+oracle = "full"
+expert_time_estimate_hours = {f["hours"]}
+
+[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 = 3600
+
+[agent]
+timeout_sec = {float(AGENT_TIMEOUT)}
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+allowed_hosts = {json.dumps(ALLOWED_HOSTS)}
+
+[environment]
+build_timeout_sec = 1800.0
+cpus = 4
+memory_mb = 8192
+"""
+
+
+def std_compose(fam: str) -> str:
+ return 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 OSMesa rendering; 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_TASK: {fam}
+ RCB_INSTANCE: /srv/instance.npz
+ RCB_TOOL: /srv/rcb_dexjoco.py
+ RCB_DATA: /data
+ RCB_WALL_CLOCK_S: "{AGENT_TIMEOUT}"
+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in a few seconds
+ PYTHONPATH: /srv
+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction log
+"""
+
+
+STD_ENV_DOCKERFILE = f"""# Standard mode: the agent container has NO simulator and no DexJoCo 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_TEST_SH = """#!/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
+"""
+
+STD_SOLVE = """#!/bin/bash
+# Oracle (standard mode): streams the reference trajectory's rows (solution/oracle_trajectory.npz, one row per control
+# step) as `ee_pose` chunks through the client. Uses no privileged information at run time (only the pre-recorded rows);
+# the service's recorded trajectory is then exactly the privileged reference.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_stream.py /app/output/gen.py
+python /solution/oracle_stream.py
+"""
+
+
+# ------------------------------------------------------------------------------------------------- rendering
+def render(root: Path) -> list[Path]:
+ out = []
+ for fam in FAMILIES:
+ F = facts(fam)
+ inst = HERE / "instances" / fam
+ # privileged
+ t = root / f"dexjoco-{dash(fam)}-i00-privileged"
+ if t.exists():
+ shutil.rmtree(t)
+ write(t / "task.toml", priv_toml(fam))
+ write(t / "instruction.md", priv_instruction(fam, F))
+ write(t / "README.md", priv_readme(fam, F))
+ write(t / "environment" / "Dockerfile", PRIV_ENV_DOCKERFILE)
+ write(t / "tests" / "Dockerfile", PRIV_TESTS_DOCKERFILE)
+ write(t / "tests" / "test.sh", priv_test_sh(fam), executable=True)
+ write(t / "solution" / "solve.sh", PRIV_SOLVE, executable=True)
+ write(t / "solution" / "gen.py", PRIV_ORACLE_GEN)
+ for sub in ("environment", "tests"):
+ copy(inst / "instance.npz", t / sub / "instance.npz")
+ copy(SHARED / "rcb_dexjoco.py", t / sub / "rcb_dexjoco.py")
+ copy(SHARED / "grade.py", t / "tests" / "grade.py")
+ copy(inst / "oracle_trajectory.npz", t / "solution" / "oracle_trajectory.npz")
+ out.append(t)
+ # standard
+ t = root / f"dexjoco-{dash(fam)}-i00-standard"
+ if t.exists():
+ shutil.rmtree(t)
+ write(t / "task.toml", std_toml(fam))
+ write(t / "instruction.md", std_instruction(fam, F))
+ write(t / "README.md", std_readme(fam, F))
+ write(t / "environment" / "Dockerfile", STD_ENV_DOCKERFILE)
+ write(t / "environment" / "docker-compose.yaml", std_compose(fam))
+ copy(LAYER / CLIENT_ENV.get("CLIENT_REQUIREMENTS", "client-requirements.txt").strip(), t / "environment" / "client-requirements.txt")
+ for f in ("rcb_client.py", "rcb1.py"):
+ copy(LAYER / f, t / "environment" / f)
+ sim = t / "environment" / "sim"
+ for f in ("rcb_limited.py", "rcb1.py", "run.sh"):
+ copy(LAYER / f, sim / f)
+ for f in ("server.py", "finalize.sh"):
+ copy(SHARED / "standard" / f, sim / f)
+ copy(SHARED / "rcb_dexjoco.py", sim / "rcb_dexjoco.py")
+ copy(inst / "instance.npz", sim / "instance.npz")
+ write(sim / "task_text.txt", task_text(fam))
+ write(t / "tests" / "Dockerfile", STD_TESTS_DOCKERFILE)
+ write(t / "tests" / "test.sh", STD_TEST_SH, executable=True)
+ copy(SHARED / "standard" / "grade.py", t / "tests" / "grade.py")
+ write(t / "solution" / "solve.sh", STD_SOLVE, executable=True)
+ copy(SHARED / "standard" / "oracle_stream.py", t / "solution" / "oracle_stream.py")
+ copy(inst / "oracle_trajectory.npz", t / "solution" / "oracle_trajectory.npz")
+ out.append(t)
+ for t in out:
+ normalize(t)
+ return out
+
+
+def tree(d: Path) -> dict:
+ # contents and the executable bit (git keeps only that; the rest of the mode follows the checkout's umask)
+ return {str(p.relative_to(d)): (p.read_bytes(), bool(p.stat().st_mode & 0o100)) for p in sorted(d.rglob("*")) if p.is_file()}
+
+
+def main() -> int:
+ if "--check" in sys.argv[1:]:
+ with tempfile.TemporaryDirectory() as td:
+ got = render(Path(td))
+ bad = [t.name for t in got if tree(t) != (tree(ROOT / "tasks" / t.name) if (ROOT / "tasks" / t.name).is_dir() else {})]
+ extra = sorted(p.name for p in (ROOT / "tasks").glob("dexjoco-*") if p.name not in {t.name for t in got})
+ for n in bad:
+ print(f"FAIL tasks/{n}: differs from the generator's output (run scripts/dexjoco/generate.py)")
+ for n in extra:
+ print(f"FAIL tasks/{n}: not written by the generator")
+ print(f"checked {len(got)} DexJoCo task dirs: {len(bad) + len(extra)} difference(s)")
+ return 1 if bad or extra else 0
+ got = render(ROOT / "tasks")
+ print(f"wrote {len(got)} task dirs")
+ return 0
+
+
+if __name__ == "__main__":
+ filecmp.clear_cache()
+ sys.exit(main())
diff --git a/scripts/dexjoco/get_demo.py b/scripts/dexjoco/get_demo.py
new file mode 100644
index 0000000000..c5797b5065
--- /dev/null
+++ b/scripts/dexjoco/get_demo.py
@@ -0,0 +1,14 @@
+"""Download only replay.zarr of the first N demos of a DexJoCo task from the public HF raw dataset."""
+import json, os, sys, urllib.request
+task, n, out = sys.argv[1], int(sys.argv[2]), sys.argv[3]
+API = "https://huggingface.co/api/datasets/DexJoCo/DexJoCo-Datasets-Raw/tree/main/"
+RAW = "https://huggingface.co/datasets/DexJoCo/DexJoCo-Datasets-Raw/resolve/main/"
+demos = sorted(x["path"] for x in json.load(urllib.request.urlopen(API + f"dexjoco_raw_datasets/{task}")) if x["type"] == "directory")
+for d in demos[:n]:
+ files = json.load(urllib.request.urlopen(API + d + "?recursive=true"))
+ for f in files:
+ if f["type"] == "file" and "/replay.zarr/" in f["path"]:
+ dst = os.path.join(out, task, f["path"].split(f"{task}/", 1)[1])
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
+ urllib.request.urlretrieve(RAW + f["path"], dst)
+ print("got", d.rsplit("/", 1)[1])
diff --git a/scripts/dexjoco/instances/bimanual_assembly/facts.json b/scripts/dexjoco/instances/bimanual_assembly/facts.json
new file mode 100644
index 0000000000..a7e19de5ab
--- /dev/null
+++ b/scripts/dexjoco/instances/bimanual_assembly/facts.json
@@ -0,0 +1,74 @@
+{
+ "family": "bimanual_assembly",
+ "demo": "assembly_demo_10_2026-03-19_17-36-54_867270",
+ "instance_sha": "e39abc9b3d77cd72",
+ "objects": [
+ "peg",
+ "peg_tip",
+ "tray",
+ "socket",
+ "table_top"
+ ],
+ "cameras": [
+ "back",
+ "handcam_rgb_right",
+ "handcam_rgb_left"
+ ],
+ "tcp0": "right [-0.443, -0.4, 1.517] / [0.0, -1.0, 0.0, -0.0025], left [-0.443, 0.4, 1.517] / [0.0, -1.0, 0.0, -0.0025]",
+ "table_top_z": 0.956,
+ "arm_bases": {
+ "link0_right": [
+ -0.75,
+ -0.4,
+ 0.924
+ ],
+ "link0_left": [
+ -0.75,
+ 0.4,
+ 0.924
+ ]
+ },
+ "hand_lo": [
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ 0.26,
+ -0.1,
+ -0.19,
+ -0.16
+ ],
+ "hand_hi": [
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 1.4,
+ 1.16,
+ 1.64,
+ 1.72
+ ],
+ "oracle_rows": 586,
+ "oracle_state_sha": "f5a74b67a4e1dfd7",
+ "steps_per_s": 230,
+ "success_src": "def _compute_success(self) -> bool:\n success, _, _ = self._compute_success_metrics()\n return bool(success)\n\ndef _compute_success_metrics(self) -> Tuple[bool, bool, int]:\n contact_count = 0\n for i in range(int(self._data.ncon)):\n c = self._data.contact[i]\n g1 = int(c.geom1)\n g2 = int(c.geom2)\n if (\n (g1 == self._peg_geom_id and g2 == self._socket_bottom_geom_id)\n or (g2 == self._peg_geom_id and g1 == self._socket_bottom_geom_id)\n ):\n contact_count += 1\n bottom_contact = contact_count > 0\n triggered = bottom_contact\n\n if triggered:\n if not getattr(self, \"_success_started\", False):\n self._success_started = True\n self._success_counter = 1\n else:\n self._success_counter += 1\n else:\n self._success_started = False\n self._success_counter = 0\n # print(f\"Triggered: {triggered}\")\n if getattr(self, \"_success_counter\", 0) >= 30:\n return True\n\n return False\n # return bool(bottom_contact), bool(bottom_contact), int(contact_count)",
+ "success_path": "dexjoco/dexjoco/sim/envs/panda_bimanual_assembly_env.py",
+ "rcb_src": "",
+ "water_aim_max_deg": 45.0
+}
diff --git a/scripts/dexjoco/instances/bimanual_assembly/instance.npz b/scripts/dexjoco/instances/bimanual_assembly/instance.npz
new file mode 100644
index 0000000000..d8c094224d
Binary files /dev/null and b/scripts/dexjoco/instances/bimanual_assembly/instance.npz differ
diff --git a/scripts/dexjoco/instances/bimanual_assembly/oracle_trajectory.npz b/scripts/dexjoco/instances/bimanual_assembly/oracle_trajectory.npz
new file mode 100644
index 0000000000..1e77b98bbf
Binary files /dev/null and b/scripts/dexjoco/instances/bimanual_assembly/oracle_trajectory.npz differ
diff --git a/scripts/dexjoco/instances/bimanual_hanoi/facts.json b/scripts/dexjoco/instances/bimanual_hanoi/facts.json
new file mode 100644
index 0000000000..ee4e47febf
--- /dev/null
+++ b/scripts/dexjoco/instances/bimanual_hanoi/facts.json
@@ -0,0 +1,79 @@
+{
+ "family": "bimanual_hanoi",
+ "demo": "hanoi_demo_10_2026-03-13_15-45-06_925668",
+ "instance_sha": "93165d7fd0c8813c",
+ "objects": [
+ "disk_small",
+ "disk_medium",
+ "disk_large",
+ "post_a",
+ "post_b",
+ "post_c"
+ ],
+ "cameras": [
+ "front",
+ "back",
+ "left",
+ "right",
+ "top0",
+ "handcam_rgb_right",
+ "handcam_rgb_left"
+ ],
+ "tcp0": "right [-0.443, -0.4, 1.517] / [0.0, -1.0, 0.0, -0.0025], left [-0.443, 0.4, 1.517] / [0.0, -1.0, 0.0, -0.0025]",
+ "table_top_z": 0.942,
+ "arm_bases": {
+ "link0_right": [
+ -0.75,
+ -0.4,
+ 0.924
+ ],
+ "link0_left": [
+ -0.75,
+ 0.4,
+ 0.924
+ ]
+ },
+ "hand_lo": [
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ 0.26,
+ -0.1,
+ -0.19,
+ -0.16
+ ],
+ "hand_hi": [
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 1.4,
+ 1.16,
+ 1.64,
+ 1.72
+ ],
+ "oracle_rows": 1085,
+ "oracle_state_sha": "1a9ae74984155266",
+ "steps_per_s": 140,
+ "success_src": "def _compute_success_metrics(self) -> Tuple[bool, Dict[str, Any]]:\n state = self._reconstruct_tower_state()\n towers = state[\"towers\"]\n disk_assignment = state[\"disk_assignment\"]\n disk_positions = state[\"disk_positions\"]\n disk_static = state[\"disk_static\"]\n post_positions = state[\"post_positions\"]\n base_top_z = state[\"base_top_z\"]\n\n tower_state = self._tower_state_repr(towers)\n all_disks_static = all(bool(v) for v in disk_static.values())\n\n illegal_candidate = False\n illegal_reason = \"\"\n\n for post_name, disks in towers.items():\n ranks = [self._disk_size_rank[disk] for disk in disks]\n if any(ranks[i] < ranks[i + 1] for i in range(len(ranks) - 1)):\n if all(disk_static[disk] for disk in disks):\n xy_error, height_error = self._tower_geometry_errors(\n disks, post_name, disk_positions, post_positions, base_top_z\n )\n if (\n xy_error <= self._post_assignment_tol\n and height_error <= self._placement_height_tol\n ):\n illegal_candidate = True\n illegal_reason = f\"illegal_stack_{post_name}\"\n break\n\n if not illegal_candidate and all_disks_static:\n on_table = [disk for disk, assign in disk_assignment.items() if assign == \"table\"]\n if on_table:\n illegal_candidate = True\n illegal_reason = \"disk_on_table\"\n\n if illegal_candidate:\n if illegal_reason == self._illegal_trigger_reason:\n self._illegal_trigger_count += 1\n else:\n self._illegal_trigger_reason = illegal_reason\n self._illegal_trigger_count = 1\n else:\n self._illegal_trigger_reason = \"\"\n self._illegal_trigger_count = 0\n\n illegal_state = self._illegal_trigger_count >= self._illegal_trigger_target\n\n xy_error_max = 0.0\n height_error_max = 0.0\n target_stack = [\"hanoi_disk_large\", \"hanoi_disk_medium\", \"hanoi_disk_small\"]\n\n if towers[\"C\"] == target_stack and len(towers[\"A\"]) == 0 and len(towers[\"B\"]) == 0:\n xy_error_max, height_error_max = self._tower_geometry_errors(\n target_stack, \"C\", disk_positions, post_positions, base_top_z\n )\n geom_success = (\n xy_error_max <= self._post_assignment_tol\n and height_error_max <= self._placement_height_tol\n and all_disks_static\n )\n else:\n geom_success = False\n\n if geom_success and not illegal_state:\n self._success_trigger_count += 1\n else:\n self._success_trigger_count = 0\n\n success = self._success_trigger_count >= self._success_trigger_target\n\n return bool(success), {\n \"tower_state\": tower_state,\n \"disk_assignment\": dict(disk_assignment),\n \"all_disks_static\": bool(all_disks_static),\n \"illegal_state\": bool(illegal_state),\n \"illegal_reason\": illegal_reason,\n \"xy_error_max\": float(xy_error_max),\n \"height_error_max\": float(height_error_max),\n }\n\ndef _compute_success(self) -> bool:\n success, _ = self._compute_success_metrics()\n return bool(success)",
+ "success_path": "dexjoco/dexjoco/sim/envs/panda_bimanual_hanoi_env.py",
+ "rcb_src": "",
+ "water_aim_max_deg": 45.0
+}
diff --git a/scripts/dexjoco/instances/bimanual_hanoi/instance.npz b/scripts/dexjoco/instances/bimanual_hanoi/instance.npz
new file mode 100644
index 0000000000..0f1065cea8
Binary files /dev/null and b/scripts/dexjoco/instances/bimanual_hanoi/instance.npz differ
diff --git a/scripts/dexjoco/instances/bimanual_hanoi/oracle_trajectory.npz b/scripts/dexjoco/instances/bimanual_hanoi/oracle_trajectory.npz
new file mode 100644
index 0000000000..7195531771
Binary files /dev/null and b/scripts/dexjoco/instances/bimanual_hanoi/oracle_trajectory.npz differ
diff --git a/scripts/dexjoco/instances/bimanual_microwave_cook/facts.json b/scripts/dexjoco/instances/bimanual_microwave_cook/facts.json
new file mode 100644
index 0000000000..bab98c8131
--- /dev/null
+++ b/scripts/dexjoco/instances/bimanual_microwave_cook/facts.json
@@ -0,0 +1,76 @@
+{
+ "family": "bimanual_microwave_cook",
+ "demo": "microwave_cook_demo_10_2026-02-09_11-56-09_655851",
+ "instance_sha": "6c16f3cfa1c737c7",
+ "objects": [
+ "hot_dog",
+ "microwave",
+ "door_hinge",
+ "door_handle",
+ "start_button",
+ "stop_button",
+ "table_top"
+ ],
+ "cameras": [
+ "back",
+ "handcam_rgb_right",
+ "handcam_rgb_left"
+ ],
+ "tcp0": "right [-0.443, -0.4, 1.517] / [0.0, 1.0, 0.0, 0.0], left [-0.443, 0.4, 1.517] / [0.0, 1.0, 0.0, 0.0]",
+ "table_top_z": 0.943,
+ "arm_bases": {
+ "link0_right": [
+ -0.75,
+ -0.4,
+ 0.924
+ ],
+ "link0_left": [
+ -0.75,
+ 0.4,
+ 0.924
+ ]
+ },
+ "hand_lo": [
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ 0.26,
+ -0.1,
+ -0.19,
+ -0.16
+ ],
+ "hand_hi": [
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 1.4,
+ 1.16,
+ 1.64,
+ 1.72
+ ],
+ "oracle_rows": 815,
+ "oracle_state_sha": "6f9ad37acc38b448",
+ "steps_per_s": 190,
+ "success_src": "def _compute_success(self):\n # ---- door must be closed ----\n micro_qpos = float(self._data.joint(\"microjoint\").qpos)\n microwave_closed = abs(micro_qpos) < 1e-2\n\n # ---- hot_dog must be inside interior bbox ----\n inside = self.hot_dog_inside_microwave(margin=0.01)\n\n contact = self._geom_in_contact(\"start_button\")\n\n # Debug helpers kept nearby for local inspection when needed.\n # print(\"microjoint qpos:\", micro_qpos)\n # print(\"hot_dog inside:\", inside)\n # print(\"start button pressed:\", contact)\n\n return inside and microwave_closed and contact\n\ndef hot_dog_inside_microwave(self, margin=0.0):\n # ---- hot_dog world position ----\n p_world = self._data.sensor(\"hot_dog_pos\").data\n\n # ---- transform to microwave local frame ----\n p_local = self.world_to_body(\"microwave_object\", p_world)\n\n # ---- read interior box sites (local frame) ----\n p0 = self._model.site(\"int_p0\").pos\n px = self._model.site(\"int_px\").pos\n py = self._model.site(\"int_py\").pos\n pz = self._model.site(\"int_pz\").pos\n\n inside_x = (p0[0] - margin) <= p_local[0] <= (px[0] + margin)\n inside_y = (p0[1] - margin) <= p_local[1] <= (py[1] + margin)\n inside_z = (p0[2] - margin) <= p_local[2] <= (pz[2] + margin)\n\n return inside_x and inside_y and inside_z",
+ "success_path": "dexjoco/dexjoco/sim/envs/panda_bimanual_microwave_cook_env.py",
+ "rcb_src": "",
+ "water_aim_max_deg": 45.0
+}
diff --git a/scripts/dexjoco/instances/bimanual_microwave_cook/instance.npz b/scripts/dexjoco/instances/bimanual_microwave_cook/instance.npz
new file mode 100644
index 0000000000..d07075df98
Binary files /dev/null and b/scripts/dexjoco/instances/bimanual_microwave_cook/instance.npz differ
diff --git a/scripts/dexjoco/instances/bimanual_microwave_cook/oracle_trajectory.npz b/scripts/dexjoco/instances/bimanual_microwave_cook/oracle_trajectory.npz
new file mode 100644
index 0000000000..896244501e
Binary files /dev/null and b/scripts/dexjoco/instances/bimanual_microwave_cook/oracle_trajectory.npz differ
diff --git a/scripts/dexjoco/instances/bimanual_photograph/facts.json b/scripts/dexjoco/instances/bimanual_photograph/facts.json
new file mode 100644
index 0000000000..a98639802d
--- /dev/null
+++ b/scripts/dexjoco/instances/bimanual_photograph/facts.json
@@ -0,0 +1,80 @@
+{
+ "family": "bimanual_photograph",
+ "demo": "photograph_demo_10_2026-03-16_14-31-13_305518",
+ "instance_sha": "b8b1dbe8dba6c733",
+ "objects": [
+ "camera",
+ "view_point",
+ "shutter",
+ "logo",
+ "target_region",
+ "table_top"
+ ],
+ "cameras": [
+ "front",
+ "back",
+ "left",
+ "right",
+ "top0",
+ "handcam_rgb_right",
+ "handcam_rgb_left",
+ "cam_pos_z"
+ ],
+ "tcp0": "right [-0.443, -0.4, 1.517] / [0.0, -1.0, 0.0, -0.0025], left [-0.443, 0.4, 1.517] / [0.0, -1.0, 0.0, -0.0025]",
+ "table_top_z": 0.93,
+ "arm_bases": {
+ "link0_right": [
+ -0.75,
+ -0.4,
+ 0.924
+ ],
+ "link0_left": [
+ -0.75,
+ 0.4,
+ 0.924
+ ]
+ },
+ "hand_lo": [
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ 0.26,
+ -0.1,
+ -0.19,
+ -0.16
+ ],
+ "hand_hi": [
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 1.4,
+ 1.16,
+ 1.64,
+ 1.72
+ ],
+ "oracle_rows": 260,
+ "oracle_state_sha": "b19e15ffe178c275",
+ "steps_per_s": 180,
+ "success_src": "def _compute_success(self) -> bool:\n success, _ = self._compute_success_metrics()\n return bool(success)\n\ndef _compute_success_metrics(self) -> Tuple[bool, Dict[str, Any]]:\n region_center = self._data.geom_xpos[self._target_region_geom_id].copy()\n region_rot = self._data.geom_xmat[self._target_region_geom_id].reshape(3, 3)\n view_pos = self._data.site_xpos[self._view_site_id].copy()\n delta_local = region_rot.T @ (view_pos - region_center)\n radial_dist = float(np.linalg.norm(delta_local[:2]))\n region_height_dist = float(abs(delta_local[2]))\n region_pass = radial_dist <= _TARGET_REGION_RADIUS and region_height_dist <= _TARGET_REGION_HALF_HEIGHT\n\n axis_z_world = self._data.geom_xmat[self._camera_axis_z_geom_id].reshape(3, 3)[:, 2].copy()\n axis_z_norm = float(np.linalg.norm(axis_z_world))\n if axis_z_norm < 1e-8:\n axis_z_world = np.array([0.0, 0.0, 1.0], dtype=np.float64)\n else:\n axis_z_world = axis_z_world / axis_z_norm\n\n cos_val = float(np.clip(np.dot(axis_z_world, _WORLD_POS_X), -1.0, 1.0))\n angle_deg = float(np.degrees(np.arccos(cos_val)))\n angle_pass = angle_deg <= _TARGET_ANGLE_DEG\n\n shutter_pressed = False\n shutter_contact_count = 0\n ncon = int(self._data.ncon)\n for i in range(ncon):\n c = self._data.contact[i]\n g1 = int(c.geom1)\n g2 = int(c.geom2)\n if g1 == self._shutter_geom_id:\n if g2 not in self._camera_geom_ids:\n shutter_pressed = True\n shutter_contact_count += 1\n elif g2 == self._shutter_geom_id:\n if g1 not in self._camera_geom_ids:\n shutter_pressed = True\n shutter_contact_count += 1\n\n success = region_pass and angle_pass and shutter_pressed\n return bool(success), {\n \"region_pass\": bool(region_pass),\n \"angle_pass\": bool(angle_pass),\n \"shutter_pressed\": bool(shutter_pressed),\n \"radial_dist\": radial_dist,\n \"region_height_dist\": region_height_dist,\n \"view_angle_deg\": angle_deg,\n \"shutter_contact_count\": int(shutter_contact_count),\n }",
+ "success_path": "dexjoco/dexjoco/sim/envs/panda_bimanual_photograph_env.py",
+ "rcb_src": "",
+ "water_aim_max_deg": 45.0
+}
diff --git a/scripts/dexjoco/instances/bimanual_photograph/instance.npz b/scripts/dexjoco/instances/bimanual_photograph/instance.npz
new file mode 100644
index 0000000000..6e5ca5b70e
Binary files /dev/null and b/scripts/dexjoco/instances/bimanual_photograph/instance.npz differ
diff --git a/scripts/dexjoco/instances/bimanual_photograph/oracle_trajectory.npz b/scripts/dexjoco/instances/bimanual_photograph/oracle_trajectory.npz
new file mode 100644
index 0000000000..7468c2f0df
Binary files /dev/null and b/scripts/dexjoco/instances/bimanual_photograph/oracle_trajectory.npz differ
diff --git a/scripts/dexjoco/instances/bimanual_unlock_ipad/facts.json b/scripts/dexjoco/instances/bimanual_unlock_ipad/facts.json
new file mode 100644
index 0000000000..b56c34a48d
--- /dev/null
+++ b/scripts/dexjoco/instances/bimanual_unlock_ipad/facts.json
@@ -0,0 +1,73 @@
+{
+ "family": "bimanual_unlock_ipad",
+ "demo": "ipad_unlock_demo_10_2026-03-22_13-59-49_595064",
+ "instance_sha": "d38c827ac3bb030e",
+ "objects": [
+ "ipad",
+ "ipad_screen",
+ "stand",
+ "table_top"
+ ],
+ "cameras": [
+ "back",
+ "handcam_rgb_right",
+ "handcam_rgb_left"
+ ],
+ "tcp0": "right [-0.443, -0.4, 1.517] / [0.0, 1.0, 0.0, 0.0], left [-0.443, 0.4, 1.517] / [0.0, 1.0, 0.0, 0.0]",
+ "table_top_z": 0.97,
+ "arm_bases": {
+ "link0_right": [
+ -0.75,
+ -0.4,
+ 0.924
+ ],
+ "link0_left": [
+ -0.75,
+ 0.4,
+ 0.924
+ ]
+ },
+ "hand_lo": [
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ 0.26,
+ -0.1,
+ -0.19,
+ -0.16
+ ],
+ "hand_hi": [
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 1.4,
+ 1.16,
+ 1.64,
+ 1.72
+ ],
+ "oracle_rows": 392,
+ "oracle_state_sha": "89ebcd76f8b8a1dd",
+ "steps_per_s": 190,
+ "success_src": "def _compute_success(self):\n if self._unlock_failed:\n return False\n\n if self._screen_unlocked:\n self._success_trigger_count += 1\n else:\n self._success_trigger_count = 0\n\n return self._success_trigger_count >= self._success_trigger_target\n\n # if self._screen_geom_id >= 0 and self._mat_screen_unlocked_id >= 0:\n # return int(self._model.geom_matid[self._screen_geom_id]) == self._mat_screen_unlocked_id\n # return False",
+ "success_path": "dexjoco/dexjoco/sim/envs/panda_bimanual_unlock_ipad_env.py",
+ "rcb_src": "",
+ "water_aim_max_deg": 45.0
+}
diff --git a/scripts/dexjoco/instances/bimanual_unlock_ipad/instance.npz b/scripts/dexjoco/instances/bimanual_unlock_ipad/instance.npz
new file mode 100644
index 0000000000..8bc4e3d0c4
Binary files /dev/null and b/scripts/dexjoco/instances/bimanual_unlock_ipad/instance.npz differ
diff --git a/scripts/dexjoco/instances/bimanual_unlock_ipad/oracle_trajectory.npz b/scripts/dexjoco/instances/bimanual_unlock_ipad/oracle_trajectory.npz
new file mode 100644
index 0000000000..f860a6ee35
Binary files /dev/null and b/scripts/dexjoco/instances/bimanual_unlock_ipad/oracle_trajectory.npz differ
diff --git a/scripts/dexjoco/instances/click_mouse/facts.json b/scripts/dexjoco/instances/click_mouse/facts.json
new file mode 100644
index 0000000000..e2d2d912ae
--- /dev/null
+++ b/scripts/dexjoco/instances/click_mouse/facts.json
@@ -0,0 +1,72 @@
+{
+ "family": "click_mouse",
+ "demo": "monitor_mousepad_demo_10_2026-03-10_20-07-29_950914",
+ "instance_sha": "ad73bedaf42257f0",
+ "objects": [
+ "mouse",
+ "mouse_button",
+ "mousepad",
+ "monitor",
+ "table_top"
+ ],
+ "cameras": [
+ "front",
+ "back",
+ "left",
+ "right",
+ "top0",
+ "handcam_rgb"
+ ],
+ "tcp0": "[-0.443, -0.0, 1.517] / [0.0, 1.0, 0.0, 0.0]",
+ "table_top_z": 0.927,
+ "arm_bases": {
+ "link0": [
+ -0.75,
+ 0.0,
+ 0.924
+ ]
+ },
+ "hand_lo": [
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ 0.26,
+ -0.1,
+ -0.19,
+ -0.16
+ ],
+ "hand_hi": [
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 1.4,
+ 1.16,
+ 1.64,
+ 1.72
+ ],
+ "oracle_rows": 560,
+ "oracle_state_sha": "59efacab09e064e0",
+ "steps_per_s": 330,
+ "success_src": "def _compute_success(self) -> bool:\n # print(\"mouse_in_mousepad\", self._mouse_in_mousepad())\n trigger_active = self._mouse_in_mousepad() and self._display_blue\n\n if trigger_active:\n self._success_trigger_count += 1\n else:\n self._success_trigger_count = 0\n\n return self._success_trigger_count >= self._success_trigger_target\n\ndef _mouse_in_mousepad(self) -> bool:\n try:\n mouse_pos = self._data.sensor(\"mouse_pos\").data\n except Exception:\n return False\n if self._mousepad_geom_id < 0 or self._mousepad_radius is None:\n return False\n pad_center = self._data.geom_xpos[self._mousepad_geom_id]\n dx, dy, dz = mouse_pos - pad_center\n in_xy = (dx * dx + dy * dy) <= (self._mousepad_radius * self._mousepad_radius)\n in_z = abs(dz) <= _MOUSEPAD_Z_TOL\n return in_xy and in_z\n\ndef _detect_click(self) -> bool:\n try:\n joint0 = float(self._data.sensor(\"mouse_joint0_pos\").data)\n except Exception:\n return False\n return (joint0 - self._mouse_joint0_init) > _CLICK_THRESHOLD",
+ "success_path": "dexjoco/dexjoco/sim/envs/panda_click_mouse_env.py",
+ "rcb_src": "",
+ "water_aim_max_deg": 45.0
+}
diff --git a/scripts/dexjoco/instances/click_mouse/instance.npz b/scripts/dexjoco/instances/click_mouse/instance.npz
new file mode 100644
index 0000000000..274a4b7352
Binary files /dev/null and b/scripts/dexjoco/instances/click_mouse/instance.npz differ
diff --git a/scripts/dexjoco/instances/click_mouse/oracle_trajectory.npz b/scripts/dexjoco/instances/click_mouse/oracle_trajectory.npz
new file mode 100644
index 0000000000..57a35f5ca6
Binary files /dev/null and b/scripts/dexjoco/instances/click_mouse/oracle_trajectory.npz differ
diff --git a/scripts/dexjoco/instances/fold_glasses/facts.json b/scripts/dexjoco/instances/fold_glasses/facts.json
new file mode 100644
index 0000000000..b71749f6e9
--- /dev/null
+++ b/scripts/dexjoco/instances/fold_glasses/facts.json
@@ -0,0 +1,72 @@
+{
+ "family": "fold_glasses",
+ "demo": "glass_fold_demo_10_2026-03-11_20-33-55_671576",
+ "instance_sha": "35849caecf4a0f6d",
+ "objects": [
+ "glasses",
+ "temple_0",
+ "temple_1",
+ "case",
+ "table_top"
+ ],
+ "cameras": [
+ "front",
+ "back",
+ "left",
+ "right",
+ "top0",
+ "handcam_rgb"
+ ],
+ "tcp0": "[-0.443, -0.0, 1.517] / [0.0, 1.0, 0.0, 0.0]",
+ "table_top_z": 0.962,
+ "arm_bases": {
+ "link0": [
+ -0.75,
+ 0.0,
+ 0.924
+ ]
+ },
+ "hand_lo": [
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ 0.26,
+ -0.1,
+ -0.19,
+ -0.16
+ ],
+ "hand_hi": [
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 1.4,
+ 1.16,
+ 1.64,
+ 1.72
+ ],
+ "oracle_rows": 612,
+ "oracle_state_sha": "fd58ca0b45a0ef3e",
+ "steps_per_s": 380,
+ "success_src": "def _compute_success(self):\n # Read the glass position in world coordinates\n glass_pos_world = np.array(self._data.sensor(\"glass_pos\").data, dtype=np.float64)\n\n glass_body_id = self._model.body(\"glass\").id\n glass_pos_world_2 = np.array(self._model.body_pos[glass_body_id], dtype=np.float64)\n # print(\"Debug: glass_pos_world (sensor):\", glass_pos_world)\n glass_quat_world = np.array(self._data.sensor(\"glass_quat\").data, dtype=np.float64)\n # print(\"Debug: glass_quat_world (sensor):\", glass_quat_world)\n\n # Read the world position of the open_box (assuming no rotation)\n box_pos_world = None\n body_id = self._model.body(\"open_box\").id\n box_pos_world = np.array(self._model.body_pos[body_id], dtype=np.float64)\n\n # Transform from world coordinates to box-local coordinates\n glass_local = glass_pos_world - box_pos_world\n\n # Inner cavity bounds of the box (derived from the XML, assuming `size` is half-extent)\n x_half = 0.145 # = 0.1475 - 0.0025\n y_half = 0.145\n z_min = -0.045\n z_max = 0.0475\n inside_x = (-x_half <= glass_local[0] <= x_half)\n inside_y = (-y_half <= glass_local[1] <= y_half)\n inside_z = (z_min <= glass_local[2] <= z_max - 0.02)\n\n # Original joint angle conditions\n glass_joint_0_pos = self._data.sensor(\"glass_joint_0_pos\").data\n glass_joint_1_pos = self._data.sensor(\"glass_joint_1_pos\").data\n j0 = float(glass_joint_0_pos[0])\n j1 = float(glass_joint_1_pos[0])\n\n if j0 > 1.1 and j1 > 1.1:\n pass\n # print(\"-----Glass folded!-----\")\n trigger_active = (\n (j0 > 1.1)\n and (j1 > 1.1)\n and inside_x\n and inside_y\n and inside_z\n )\n\n if trigger_active:\n # Increment counter if the condition is met\n self._success_trigger_count += 1\n else:\n # Reset counter if the condition is not met\n self._success_trigger_count = 0\n\n # Return success if the condition has been met 10 times consecutively\n return self._success_trigger_count >= self._success_trigger_target",
+ "success_path": "dexjoco/dexjoco/sim/envs/panda_fold_glasses_env.py",
+ "rcb_src": "",
+ "water_aim_max_deg": 45.0
+}
diff --git a/scripts/dexjoco/instances/fold_glasses/instance.npz b/scripts/dexjoco/instances/fold_glasses/instance.npz
new file mode 100644
index 0000000000..ac1baebfb1
Binary files /dev/null and b/scripts/dexjoco/instances/fold_glasses/instance.npz differ
diff --git a/scripts/dexjoco/instances/fold_glasses/oracle_trajectory.npz b/scripts/dexjoco/instances/fold_glasses/oracle_trajectory.npz
new file mode 100644
index 0000000000..721e4675b4
Binary files /dev/null and b/scripts/dexjoco/instances/fold_glasses/oracle_trajectory.npz differ
diff --git a/scripts/dexjoco/instances/hammer_nail/facts.json b/scripts/dexjoco/instances/hammer_nail/facts.json
new file mode 100644
index 0000000000..06bef49bad
--- /dev/null
+++ b/scripts/dexjoco/instances/hammer_nail/facts.json
@@ -0,0 +1,72 @@
+{
+ "family": "hammer_nail",
+ "demo": "hammer_nail_demo_10_2026-02-05_19-18-55_029010",
+ "instance_sha": "095c53d8e9a1cae0",
+ "objects": [
+ "hammer",
+ "nail",
+ "nail_top",
+ "wood_top",
+ "table_top"
+ ],
+ "cameras": [
+ "front",
+ "back",
+ "left",
+ "right",
+ "top0",
+ "handcam_rgb"
+ ],
+ "tcp0": "[-0.059, 0.008, 1.096] / [1.0, 0.0, 0.0, 0.0]",
+ "table_top_z": 0.936,
+ "arm_bases": {
+ "link0": [
+ -0.75,
+ 0.0,
+ 0.924
+ ]
+ },
+ "hand_lo": [
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ 0.26,
+ -0.1,
+ -0.19,
+ -0.16
+ ],
+ "hand_hi": [
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 1.4,
+ 1.16,
+ 1.64,
+ 1.72
+ ],
+ "oracle_rows": 202,
+ "oracle_state_sha": "8c86453dc2ab732f",
+ "steps_per_s": 400,
+ "success_src": "def _compute_success(self):\n return float(self._nail_depth) >= self._success_depth\n\ndef _apply_hammer_nail_interaction(self) -> bool:\n if not self._hammer_geom_ids or not self._nail_geom_ids:\n return False\n\n hammer_set = set(self._hammer_geom_ids)\n nail_set = set(self._nail_geom_ids)\n hit = False\n ncon = int(self._data.ncon)\n for i in range(ncon):\n c = self._data.contact[i]\n g1 = int(c.geom1)\n g2 = int(c.geom2)\n if (g1 in hammer_set and g2 in nail_set) or (\n g2 in hammer_set and g1 in nail_set\n ):\n hit = True\n break\n\n if not hit:\n return False\n\n preimpact_vz = min(self._vz_buf) if self._vz_buf else 0.0\n if preimpact_vz >= -self._impact_vel_threshold:\n return True\n\n depth = float(self._nail_depth)\n max_depth = float(self._nail_max_depth)\n scale = min(3.0, abs(preimpact_vz) / max(self._impact_vel_threshold, 1e-6))\n delta = self._impact_insert_step * scale\n new_depth = min(max_depth, depth + delta)\n if new_depth > depth:\n self._nail_depth = new_depth\n new_pos = self._nail_init_pos.copy()\n new_pos[2] = self._nail_init_pos[2] - new_depth\n self._data.mocap_pos[self._nail_mocap_id] = new_pos\n self._data.mocap_quat[self._nail_mocap_id] = self._nail_init_quat\n mujoco.mj_forward(self._model, self._data)\n\n return True",
+ "success_path": "dexjoco/dexjoco/sim/envs/panda_hammer_nail_env.py",
+ "rcb_src": "",
+ "water_aim_max_deg": 45.0
+}
diff --git a/scripts/dexjoco/instances/hammer_nail/instance.npz b/scripts/dexjoco/instances/hammer_nail/instance.npz
new file mode 100644
index 0000000000..443d63038d
Binary files /dev/null and b/scripts/dexjoco/instances/hammer_nail/instance.npz differ
diff --git a/scripts/dexjoco/instances/hammer_nail/oracle_trajectory.npz b/scripts/dexjoco/instances/hammer_nail/oracle_trajectory.npz
new file mode 100644
index 0000000000..9608c88267
Binary files /dev/null and b/scripts/dexjoco/instances/hammer_nail/oracle_trajectory.npz differ
diff --git a/scripts/dexjoco/instances/pick_bucket/facts.json b/scripts/dexjoco/instances/pick_bucket/facts.json
new file mode 100644
index 0000000000..c6e46b4c4e
--- /dev/null
+++ b/scripts/dexjoco/instances/pick_bucket/facts.json
@@ -0,0 +1,71 @@
+{
+ "family": "pick_bucket",
+ "demo": "bucket_pick_demo_10_2026-03-10_18-19-00_120725",
+ "instance_sha": "1cb042bf6d46ad45",
+ "objects": [
+ "bucket",
+ "bucket_handle",
+ "boxed_food",
+ "table_top"
+ ],
+ "cameras": [
+ "front",
+ "back",
+ "left",
+ "right",
+ "top0",
+ "handcam_rgb"
+ ],
+ "tcp0": "[-0.443, -0.0, 1.517] / [0.0, 1.0, 0.0, 0.0]",
+ "table_top_z": 0.946,
+ "arm_bases": {
+ "link0": [
+ -0.75,
+ 0.0,
+ 0.924
+ ]
+ },
+ "hand_lo": [
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ 0.26,
+ -0.1,
+ -0.19,
+ -0.16
+ ],
+ "hand_hi": [
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 1.4,
+ 1.16,
+ 1.64,
+ 1.72
+ ],
+ "oracle_rows": 580,
+ "oracle_state_sha": "f39c51709bbec3cc",
+ "steps_per_s": 350,
+ "success_src": "def _compute_success(self):\n box_pos = np.array(self._data.sensor(\"boxed_food_0_pos\").data, dtype=float)\n site_ids = [self.model.site(f\"bucket_ref_{i}\").id for i in range(8)]\n corners = np.array(self._data.site_xpos[site_ids], dtype=float) # (8,3)\n mins = corners.min(axis=0)\n maxs = corners.max(axis=0)\n inside = np.all(box_pos >= mins) and np.all(box_pos <= maxs)\n bottom_z = self._data.site_xpos[self._bucket_bottom_site_ids, 2]\n lifted = np.all(bottom_z - self._bucket_bottom_z0 >= 0.15)\n success = inside and lifted\n\n return success",
+ "success_path": "dexjoco/dexjoco/sim/envs/panda_pick_bucket_env.py",
+ "rcb_src": "",
+ "water_aim_max_deg": 45.0
+}
diff --git a/scripts/dexjoco/instances/pick_bucket/instance.npz b/scripts/dexjoco/instances/pick_bucket/instance.npz
new file mode 100644
index 0000000000..473da0693d
Binary files /dev/null and b/scripts/dexjoco/instances/pick_bucket/instance.npz differ
diff --git a/scripts/dexjoco/instances/pick_bucket/oracle_trajectory.npz b/scripts/dexjoco/instances/pick_bucket/oracle_trajectory.npz
new file mode 100644
index 0000000000..8e5a6a7641
Binary files /dev/null and b/scripts/dexjoco/instances/pick_bucket/oracle_trajectory.npz differ
diff --git a/scripts/dexjoco/instances/pinch_tongs/facts.json b/scripts/dexjoco/instances/pinch_tongs/facts.json
new file mode 100644
index 0000000000..39d3cb434e
--- /dev/null
+++ b/scripts/dexjoco/instances/pinch_tongs/facts.json
@@ -0,0 +1,70 @@
+{
+ "family": "pinch_tongs",
+ "demo": "table_tongs_demo_10_2026-03-12_16-30-04_442884",
+ "instance_sha": "ad2cfca40d427e20",
+ "objects": [
+ "tongs",
+ "tongs_hinge",
+ "table_top"
+ ],
+ "cameras": [
+ "front",
+ "back",
+ "left",
+ "right",
+ "top0",
+ "handcam_rgb"
+ ],
+ "tcp0": "[-0.443, -0.0, 1.517] / [0.0, 1.0, 0.0, 0.0]",
+ "table_top_z": 0.97,
+ "arm_bases": {
+ "link0": [
+ -0.75,
+ 0.0,
+ 0.924
+ ]
+ },
+ "hand_lo": [
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ 0.26,
+ -0.1,
+ -0.19,
+ -0.16
+ ],
+ "hand_hi": [
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 1.4,
+ 1.16,
+ 1.64,
+ 1.72
+ ],
+ "oracle_rows": 375,
+ "oracle_state_sha": "8c3b4bcc37576642",
+ "steps_per_s": 390,
+ "success_src": "def _compute_success(self) -> bool:\n try:\n tongs_pos = self._data.sensor(\"tongs_pos\").data\n except Exception:\n return False\n\n lifted = tongs_pos[2] >= self._lift_z\n triggered = lifted and self._pinch_count >= _REQUIRED_PINCHES\n\n if triggered:\n if not getattr(self, \"_success_started\", False):\n self._success_started = True\n self._success_counter = 1\n else:\n self._success_counter += 1\n else:\n self._success_started = False\n self._success_counter = 0\n\n # print(f\"Triggered: {triggered}\")\n if getattr(self, \"_success_counter\", 0) >= 30:\n return True\n\n return False\n\ndef _update_pinch_count(self) -> None:\n try:\n joint_pos = float(self._data.sensor(\"tongs_joint_0_pos\").data)\n except Exception:\n return\n\n if joint_pos <= _TONGS_CLOSE_THRESHOLD and self._pinch_in_progress:\n self._pinch_in_progress = False\n self._pinch_count += 1\n elif joint_pos >= _TONGS_OPEN_THRESHOLD and not self._pinch_in_progress:\n self._pinch_in_progress = True\n\n # print(f\"Pinch count: {self._pinch_count}, Joint pos: {joint_pos:.3f}\")",
+ "success_path": "dexjoco/dexjoco/sim/envs/panda_pinch_tongs_env.py",
+ "rcb_src": "",
+ "water_aim_max_deg": 45.0
+}
diff --git a/scripts/dexjoco/instances/pinch_tongs/instance.npz b/scripts/dexjoco/instances/pinch_tongs/instance.npz
new file mode 100644
index 0000000000..fb46289594
Binary files /dev/null and b/scripts/dexjoco/instances/pinch_tongs/instance.npz differ
diff --git a/scripts/dexjoco/instances/pinch_tongs/oracle_trajectory.npz b/scripts/dexjoco/instances/pinch_tongs/oracle_trajectory.npz
new file mode 100644
index 0000000000..8710cc5bde
Binary files /dev/null and b/scripts/dexjoco/instances/pinch_tongs/oracle_trajectory.npz differ
diff --git a/scripts/dexjoco/instances/water_plant/facts.json b/scripts/dexjoco/instances/water_plant/facts.json
new file mode 100644
index 0000000000..765fb252cc
--- /dev/null
+++ b/scripts/dexjoco/instances/water_plant/facts.json
@@ -0,0 +1,72 @@
+{
+ "family": "water_plant",
+ "demo": "water_plant_demo_10_2026-02-05_19-50-27_886249",
+ "instance_sha": "04f14553ced4b0ed",
+ "objects": [
+ "spray_bottle",
+ "spray_trigger",
+ "spray_nozzle",
+ "plant",
+ "table_top"
+ ],
+ "cameras": [
+ "front",
+ "back",
+ "left",
+ "right",
+ "top0",
+ "handcam_rgb"
+ ],
+ "tcp0": "[-0.443, -0.0, 1.517] / [0.0, -1.0, 0.0, -0.0025]",
+ "table_top_z": 0.964,
+ "arm_bases": {
+ "link0": [
+ -0.75,
+ 0.0,
+ 0.924
+ ]
+ },
+ "hand_lo": [
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ -0.47,
+ -0.2,
+ -0.17,
+ -0.23,
+ 0.26,
+ -0.1,
+ -0.19,
+ -0.16
+ ],
+ "hand_hi": [
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 0.47,
+ 1.61,
+ 1.71,
+ 1.62,
+ 1.4,
+ 1.16,
+ 1.64,
+ 1.72
+ ],
+ "oracle_rows": 307,
+ "oracle_state_sha": "a4342b4b85a7241c",
+ "steps_per_s": 390,
+ "success_src": "def _compute_success(self):\n site_id = self._model.site(\"ref_point\").id\n p_world = self._data.site_xpos[site_id]\n obj_world_pos = self._data.body(\"plant\").xpos\n\n R = 0.2\n HALF_H = 0.2\n dx, dy, dz = p_world - obj_world_pos\n inside = (dx * dx + dy * dy <= R * R) and (-HALF_H <= dz <= HALF_H)\n\n failed_trigger_outside = (not inside) and self._trigger_pulled\n\n if inside and self._trigger_pulled:\n self._success_counter += 1\n else:\n self._success_counter = 0\n\n success = self._success_counter >= _SUCCESS_STEPS_REQUIRED\n return success, failed_trigger_outside",
+ "success_path": "dexjoco/dexjoco/sim/envs/panda_water_plant_env.py",
+ "rcb_src": "def water_aim_deg(model, data) -> float:\n \"\"\"Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray\n direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long\n axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces.\"\"\"\n spray = data.body(\"link_2\").xmat.reshape(3, 3)[:, 2]\n to_plant = data.body(\"plant\").xpos - data.site(\"ref_point\").xpos\n c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))\n return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))",
+ "water_aim_max_deg": 45.0
+}
diff --git a/scripts/dexjoco/instances/water_plant/instance.npz b/scripts/dexjoco/instances/water_plant/instance.npz
new file mode 100644
index 0000000000..c71cd35bcb
Binary files /dev/null and b/scripts/dexjoco/instances/water_plant/instance.npz differ
diff --git a/scripts/dexjoco/instances/water_plant/oracle_trajectory.npz b/scripts/dexjoco/instances/water_plant/oracle_trajectory.npz
new file mode 100644
index 0000000000..f1a414a0c2
Binary files /dev/null and b/scripts/dexjoco/instances/water_plant/oracle_trajectory.npz differ
diff --git a/scripts/dexjoco/make_instances.py b/scripts/dexjoco/make_instances.py
new file mode 100644
index 0000000000..aa77266809
--- /dev/null
+++ b/scripts/dexjoco/make_instances.py
@@ -0,0 +1,146 @@
+"""Build the frozen DexJoCo instances and their reference trajectories, and record the facts the task texts quote.
+
+Runs INSIDE the base image (DexJoCo + MuJoCo); writes scripts/dexjoco/instances/<family>/:
+ instance.npz the frozen scene (rcb_dexjoco.Session.save_instance)
+ oracle_trajectory.npz the human demonstration's own actions, truncated where its episode ends in success
+ facts.json what generate.py needs from the simulator (cameras, start targets, hand limits, the upstream
+ success code, the arm bases, the table height, the oracle's length and margin)
+
+ # 1. the demos (public Hugging Face dataset DexJoCo/DexJoCo-Datasets-Raw, replay.zarr only, ~120 KB each)
+ python3 scripts/dexjoco/get_demo.py water_plant 1 /tmp/demos
+ # 2. in the image, from the repo root
+ docker run --rm --user $(id -u):$(id -g) -e HOME=/tmp -v $PWD:/repo -v /tmp/demos:/demos -w /repo \
+ ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2 python scripts/dexjoco/make_instances.py water_plant \
+ --demo /demos/water_plant/<demo>/replay.zarr
+ # without --demo: keep the committed instance and oracle, check them and refresh facts.json only
+ docker run ... python scripts/dexjoco/make_instances.py --all
+
+Instance = the task's env after reset with the initial object poses and table height of the demonstration restored
+(DexJoCo's own state restorer, demo state[0]). The reference = the demonstration's actions replayed through the tooling
+until its episode ends in success; a demo that does not succeed from its own initial state is refused. The rows are
+float32-exact (the standard-mode client sends float32), checked here.
+"""
+from __future__ import annotations
+
+import argparse
+import inspect
+import json
+import os
+import sys
+import textwrap
+import time
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+sys.path.insert(0, str(HERE / "shared"))
+os.environ["RCB_SESSION_LOG"] = ""
+import numpy as np # noqa: E402
+import rcb_dexjoco as R # noqa: E402
+
+R.SESSION_LOG = ""
+# family -> (the upstream methods that decide success, the demonstration used for the instance)
+FAMILIES = {
+ "water_plant": (["_compute_success"], "water_plant_demo_10_2026-02-05_19-50-27_886249"),
+ "click_mouse": (["_compute_success", "_mouse_in_mousepad", "_detect_click"], "monitor_mousepad_demo_10_2026-03-10_20-07-29_950914"),
+ "hammer_nail": (["_compute_success", "_apply_hammer_nail_interaction"], "hammer_nail_demo_10_2026-02-05_19-18-55_029010"),
+ "bimanual_hanoi": (["_compute_success_metrics", "_compute_success"], "hanoi_demo_10_2026-03-13_15-45-06_925668"),
+ "pick_bucket": (["_compute_success"], "bucket_pick_demo_10_2026-03-10_18-19-00_120725"),
+ "pinch_tongs": (["_compute_success", "_update_pinch_count"], "table_tongs_demo_10_2026-03-12_16-30-04_442884"),
+ "fold_glasses": (["_compute_success"], "glass_fold_demo_10_2026-03-11_20-33-55_671576"),
+ "bimanual_microwave_cook": (["_compute_success", "hot_dog_inside_microwave"], "microwave_cook_demo_10_2026-02-09_11-56-09_655851"),
+ "bimanual_unlock_ipad": (["_compute_success"], "ipad_unlock_demo_10_2026-03-22_13-59-49_595064"),
+ "bimanual_assembly": (["_compute_success", "_compute_success_metrics"], "assembly_demo_10_2026-03-19_17-36-54_867270"),
+ "bimanual_photograph": (["_compute_success", "_compute_success_metrics"], "photograph_demo_10_2026-03-16_14-31-13_305518"),
+}
+RCB_CODE = {"water_plant": ["water_aim_deg"]} # robot_coding_bench's tightened checks, quoted in the instruction
+
+
+def success_source(s: R.Session, fam: str) -> tuple[str, str]:
+ cls = type(s.base)
+ src = "\n".join(textwrap.dedent(inspect.getsource(getattr(cls, m))) for m in FAMILIES[fam][0])
+ return src.rstrip(), str(Path(inspect.getsourcefile(cls)).relative_to("/opt/dexjoco"))
+
+
+def build_from_demo(fam: str, demo: str, out: Path) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = R.Session(fam)
+ root = zarr.open(demo, mode="r")
+ s.base.reset()
+ restore_initial_state(s.env, fam, s.cfg, np.asarray(root["data"]["state"][0]).ravel())
+ s._snapshot = s.snapshot(); s._episode_reset()
+ s.save_instance(out / "instance.npz", {"source": "DexJoCo-Datasets-Raw demo initial state (dexjoco.tasks.state_restorers)",
+ "demo": FAMILIES[fam][1], "dexjoco": "8d23b0f"})
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = R.Session(fam, instance=out / "instance.npz")
+ st = s2.replay(A)
+ if not st["success"]:
+ raise SystemExit(f"{fam}: the demo does not succeed from its own initial state: {st}")
+ s2.save_trajectory(A[:st["replayed_rows"]], out / "oracle_trajectory.npz", {"source": "demo actions", "demo": FAMILIES[fam][1]})
+ # facts() rounds the rows to float32 (and checks they still succeed) if they are not float32-exact
+
+
+def facts(fam: str, out: Path) -> dict:
+ inst = out / "instance.npz"
+ A = np.asarray(np.load(out / "oracle_trajectory.npz")["actions"], dtype=np.float64)
+ s = R.Session(fam, instance=inst)
+ if not np.array_equal(A.astype(np.float32).astype(np.float64), A):
+ # the standard client sends float32: round the demo's rows to float32 (both modes use the same reference), keep
+ # them only if they still succeed (holding the last row up to 5 s more if the episode has not ended), truncated
+ # where the episode ends
+ A = A.astype(np.float32).astype(np.float64); n_demo = len(A)
+ st = s.replay(A)
+ if not st["done"]: # the rounded rows end a few steps short of the hold count: hold the last row
+ A = np.concatenate([A, np.repeat(A[-1:], 250, axis=0)])
+ st = s.replay(A)
+ if not st["success"]:
+ raise SystemExit(f"{fam}: the demo rows rounded to float32 do not succeed: {st}")
+ A = A[:st["replayed_rows"]]
+ meta = json.loads(str(np.load(out / "oracle_trajectory.npz")["meta"]))
+ s.save_trajectory(A, out / "oracle_trajectory.npz", {**meta, "float32": True, "demo_rows": int(n_demo)})
+ print(f"{fam}: oracle rows rounded to float32 ({len(A)} rows)", flush=True)
+ if not s.instance_exact:
+ raise SystemExit(f"{fam}: this image does not rebuild the instance (state sha {s.state_sha()} != {s.instance_sha})")
+ t0 = time.time(); st = s.replay(A); dt = time.time() - t0
+ if not st["success"] or st["replayed_rows"] != len(A):
+ raise SystemExit(f"{fam}: the oracle does not end in success on its last row: {st}")
+ st2 = R.Session(fam, instance=inst).replay(A)
+ assert st2["state_sha"] == st["state_sha"], (st, st2)
+ bim = s.bimanual
+ s.reset()
+ tgt = s.hold_action()
+ fmt = lambda v, n: [round(float(x), n) for x in v] # noqa: E731
+ tcp0 = (f"right {fmt(tgt[:3], 3)} / {fmt(tgt[3:7], 4)}, left {fmt(tgt[23:26], 3)} / {fmt(tgt[26:30], 4)}" if bim
+ else f"{fmt(tgt[:3], 3)} / {fmt(tgt[3:7], 4)}")
+ try:
+ table_z = round(float(s.data.site("table_top").xpos[2]), 3)
+ except KeyError:
+ table_z = None
+ bases = {n: fmt(s.body_pose(n)[0], 3) for n in s.bodies() if n.startswith("link0")}
+ src, path = success_source(s, fam)
+ rcb_src = "\n".join(textwrap.dedent(inspect.getsource(getattr(R, n))) for n in RCB_CODE.get(fam, [])).rstrip()
+ return {"family": fam, "demo": FAMILIES[fam][1], "instance_sha": s.instance_sha, "objects": list(s.objects()),
+ "cameras": s.cameras(), "tcp0": tcp0, "table_top_z": table_z, "arm_bases": bases,
+ "hand_lo": fmt(s.hand_limits()[:, 0], 2), "hand_hi": fmt(s.hand_limits()[:, 1], 2),
+ "oracle_rows": int(len(A)), "oracle_state_sha": st["state_sha"],
+ "steps_per_s": int(round(len(A) / max(dt, 1e-6), -1)),
+ "success_src": src, "success_path": path, "rcb_src": rcb_src, "water_aim_max_deg": R.WATER_AIM_MAX_DEG}
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("families", nargs="*"); ap.add_argument("--all", action="store_true"); ap.add_argument("--demo")
+ a = ap.parse_args()
+ fams = sorted(FAMILIES) if a.all else a.families
+ for fam in fams:
+ out = HERE / "instances" / fam
+ out.mkdir(parents=True, exist_ok=True)
+ if a.demo:
+ build_from_demo(fam, a.demo, out)
+ f = facts(fam, out)
+ (out / "facts.json").write_text(json.dumps(f, indent=1) + "\n")
+ print(json.dumps({k: f[k] for k in ("family", "oracle_rows", "instance_sha", "oracle_state_sha", "steps_per_s")}), flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/dexjoco/shared/grade.py b/scripts/dexjoco/shared/grade.py
new file mode 100644
index 0000000000..ad916e8bb9
--- /dev/null
+++ b/scripts/dexjoco/shared/grade.py
@@ -0,0 +1,109 @@
+"""Verifier entry point for the privileged DexJoCo tasks: replay /app/output/trajectory.npz from the frozen instance and
+write Harbor rewards.
+
+ python /tests/grade.py --family water_plant --instance /tests/instance.npz --traj /app/output/trajectory.npz
+
+Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only; Harbor rejects strings), a replay video
+/logs/verifier/replay.mp4 (front camera + wrist camera) and replay.last.png. Replays `--repeat` times in this fresh
+process; success requires every replay to end its episode in success (DexJoCo's own rule: the episode ends at the first
+success or task failure) AND all final-state hashes to agree (MuJoCo on the CPU is bit-deterministic), and the frozen
+instance rebuilt here from tests/instance.npz must match its recorded hash.
+"""
+from __future__ import annotations
+import argparse, json, os, sys, time, traceback
+import numpy as np
+
+LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")
+
+
+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 self_reported_cost() -> dict:
+ # From the tooling's append-only log in the agent's container: SELF-REPORTED accounting, never evidence.
+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_records": 0, "agent_replays": 0,
+ "agent_cost_self_reported": 1}
+ try:
+ with open("/app/output/rcb_session_log.jsonl") 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 == "session_end": cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)
+ elif ev == "record": cost["agent_records"] += 1
+ elif ev == "replay": cost["agent_replays"] += 1
+ except Exception: # noqa: BLE001 — one bad line must not sink the verdict
+ continue
+ except Exception: # noqa: BLE001
+ pass
+ return cost
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--family", required=True); ap.add_argument("--instance", required=True)
+ ap.add_argument("--traj", default="/app/output/trajectory.npz"); ap.add_argument("--repeat", type=int, default=2)
+ ap.add_argument("--no-video", action="store_true")
+ a = ap.parse_args()
+ cost = self_reported_cost()
+ os.environ["RCB_SESSION_LOG"] = "" # the verifier's own sessions are not the agent's cost
+ if not os.path.isfile(a.traj):
+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost}); return 0
+ s = None
+ try:
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the verifier's own copy of the tooling
+ import rcb_dexjoco
+ rcb_dexjoco.SESSION_LOG = ""
+ from rcb_dexjoco import Session, MAX_STEPS
+ d = np.load(a.traj, allow_pickle=False)
+ if str(d["task"]) != a.family:
+ write(False, {"success": 0, "wrong_family": 1, "grader_error": 0, **cost}); return 0
+ acts = np.asarray(d["actions"], dtype=np.float64)
+ s = Session(a.family, instance=a.instance)
+ if (acts.ndim != 2 or acts.shape[1] != s.action_dim or acts.shape[0] > MAX_STEPS
+ or not np.all(np.isfinite(acts))):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0,
+ "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0, **cost}); return 0
+ t0 = time.time()
+ outs = []
+ for _ in range(a.repeat):
+ try:
+ outs.append(s.replay(acts))
+ except (ValueError, rcb_dexjoco.PrimitiveError):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0, "n_actions": int(len(acts)), **cost}); return 0
+ all_success = all(o["success"] for o in outs)
+ deterministic = len({o["state_sha"] for o in outs}) == 1
+ instance_ok = bool(s.instance_exact)
+ ok = all_success and deterministic and instance_ok
+ out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
+ "instance_ok": int(instance_ok), "n_actions": int(len(acts)), "sim_steps": int(outs[0]["steps"]),
+ "task_failure": int(bool(outs[0]["reason"]) and not outs[0]["success"]),
+ "replay_wall_s": round(time.time() - t0, 1), "grader_error": 0, "video_rendered": 0, **cost}
+ if not a.no_video: # human-viewable replay (never affects the verdict)
+ try:
+ n = int(outs[0]["replayed_rows"])
+ s.render_video(acts[:n], os.path.join(LOG_DIR, "replay.mp4"), cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ import imageio.v2 as imageio
+ imageio.imwrite(os.path.join(LOG_DIR, "replay.last.png"), s.render_frame(s.default_camera(), (480, 640)))
+ out["video_rendered"] = int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4")))
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(ok, out)
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(False, {"success": 0, "grader_error": 1, **cost})
+ finally:
+ if s is not None:
+ s.close()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/dexjoco/shared/rcb_dexjoco.py b/scripts/dexjoco/shared/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/scripts/dexjoco/shared/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/dexjoco/shared/standard/finalize.sh b/scripts/dexjoco/shared/standard/finalize.sh
new file mode 100644
index 0000000000..e0cf248720
--- /dev/null
+++ b/scripts/dexjoco/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_dexjoco.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:?}"; TASK="${RCB_TASK:?}"
+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 --task "$TASK" --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --repeat 1 \
+ --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"))
+PY
diff --git a/scripts/dexjoco/shared/standard/grade.py b/scripts/dexjoco/shared/standard/grade.py
new file mode 100644
index 0000000000..003b933315
--- /dev/null
+++ b/scripts/dexjoco/shared/standard/grade.py
@@ -0,0 +1,60 @@
+"""Standard-mode verifier (DexJoCo): 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 frozen 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"))),
+ "task_failure": int(bool(d.get("task_failure"))),
+ "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),
+ "calls": int(d.get("calls") or 0),
+ "elapsed_s": float(d.get("elapsed_s") or 0),
+ "video_rendered": int(bool(d.get("video"))),
+ # 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 frozen 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/dexjoco/shared/standard/oracle_stream.py b/scripts/dexjoco/shared/standard/oracle_stream.py
new file mode 100644
index 0000000000..19877300c1
--- /dev/null
+++ b/scripts/dexjoco/shared/standard/oracle_stream.py
@@ -0,0 +1,43 @@
+"""Oracle (standard mode): streams the reference rows (the human demonstration's own actions, one per 1/50 s control step,
+float32-exact) as `ee_pose` 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
+
+A = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle_trajectory.npz"))["actions"].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(A), flush=True)
+t0, i = time.time(), 0
+while i < len(A):
+ chunk = A[i:i + per_chunk]
+ try:
+ res = r.submit("ee_pose", chunk, dt=dt, interpolate="hold", 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/dexjoco/shared/standard/server.py b/scripts/dexjoco/shared/standard/server.py
new file mode 100644
index 0000000000..ca5b61fc5c
--- /dev/null
+++ b/scripts/dexjoco/shared/standard/server.py
@@ -0,0 +1,625 @@
+"""eai-standard/2.2 sim service for DexJoCo (docs/STANDARD_MODE_2_2.md): the adapter of the shared layer rcb_limited.py;
+the simulator is rcb_dexjoco.Session (DexJoCo on MuJoCo 3.4, CPU physics, OSMesa rendering).
+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to
+/data/episode.jsonl.
+
+The robot is a Franka Panda with a 16-DoF Allegro hand, or two of them side by side (right arm first). One control step
+= 1/50 s (10 physics substeps of 2 ms). Two action types:
+ ee_pose DexJoCo's own row, per arm: the tcp target pose (xyz m, quaternion wxyz, world frame) that its
+ operational-space controller tracks + 16 Allegro joint targets (rad);
+ joint_position per arm: 7 arm joint targets + 16 Allegro joint targets; the arm's targets are turned into a tcp target
+ by forward kinematics (the controller tracks the tcp pose, not the joints).
+Either way, the executed (journaled, recorded) row is DexJoCo's own row, so the recorded trajectory replays in the
+privileged tooling unchanged. As in DexJoCo's evaluation the episode ends at the first success or task failure;
+otherwise when the agent's time is over (the collect hook's SIGUSR1).
+
+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 instance 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")
+TASK = os.environ.get("RCB_TASK", "water_plant")
+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.npz"))
+TASK_TEXT_FILE = os.environ.get("RCB_TASK_TEXT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "task_text.txt"))
+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "5400"))
+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 = 640, 480
+CTRL_HZ = 50.0
+DT = 1.0 / CTRL_HZ
+SUBSTEPS = 10
+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"] = "" # the sidecar's Session is not the agent's interaction log
+import rcb_dexjoco as M # noqa: E402
+import mujoco # noqa: E402
+
+M.SESSION_LOG = ""
+BIM = TASK.startswith("bimanual_")
+ADIM = 46 if BIM else 23
+EP = L.Episode(DATA, dim=ADIM, resume="exact")
+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()
+S = M.Session(TASK, instance=INSTANCE, image_size=(CAM_H, CAM_W))
+MD, D = S.model, S.data
+ARMS = S.arms()
+SFX = {a: (f"_{a}" if BIM else "") for a in ARMS}
+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz
+
+# ------------------------------------------------------------------------------------------------- the robot
+ARM_JOINTS = {a: [f"joint{i}{SFX[a]}" for i in range(1, 8)] for a in ARMS}
+HAND_CTRL = {a: np.asarray(S._hand_ctrl_ids(a)) for a in ARMS}
+HAND_JOINTS = {a: [MD.joint(int(MD.actuator_trnid[i, 0])).name for i in HAND_CTRL[a]] for a in ARMS} # action order
+ARM_CTRL = {a: [MD.actuator(f"actuator{i}{SFX[a]}").id for i in range(1, 8)] for a in ARMS}
+JOINTS = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]] # kinematics q = proprio joint_pos columns
+QADR = np.array([MD.jnt_qposadr[MD.joint(j).id] for j in JOINTS])
+VADR = np.array([MD.jnt_dofadr[MD.joint(j).id] for j in JOINTS])
+EFF_ACT = np.array([i for a in ARMS for i in list(ARM_CTRL[a]) + list(HAND_CTRL[a])])
+TCP_SITE = {a: MD.site(f"attachment_site{SFX[a]}").id for a in ARMS}
+TCP = {a: f"tcp{SFX[a]}" for a in ARMS}
+MOUNT_BODY = {a: f"attachment{SFX[a]}" for a in ARMS}
+LINKS = {a: [f"link{i}{SFX[a]}" for i in range(0, 8) if mujoco.mj_name2id(MD, mujoco.mjtObj.mjOBJ_BODY, f"link{i}{SFX[a]}") >= 0]
+ + [MOUNT_BODY[a]] for a in ARMS}
+KIN_LINKS = [n for a in ARMS for n in LINKS[a] + [TCP[a]]]
+JLIM = {j: MD.jnt_range[MD.joint(j).id].astype(float).tolist() for j in JOINTS}
+HLIM = {a: S.hand_limits(a) for a in ARMS} # actuator ctrlrange, action order
+ALIM = {} # joint_position limits (inside the joint ranges)
+for a in ARMS:
+ for j in ARM_JOINTS[a]:
+ ALIM[j] = JLIM[j]
+ for j, (lo, hi) in zip(HAND_JOINTS[a], HLIM[a]):
+ ALIM[j] = [max(float(lo), JLIM[j][0]), min(float(hi), JLIM[j][1])]
+POSE = ["x", "y", "z", "qw", "qx", "qy", "qz"]
+EE_LAYOUT = [] # per arm, right first
+for a in ARMS:
+ EE_LAYOUT += [f"{TCP[a]}_target_{k}" for k in POSE] + [f"{j}_target" for j in HAND_JOINTS[a]]
+JP_LAYOUT = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]]
+
+GROUPS = [
+ ("joint_pos", JOINTS, "measured joint positions (rad): per arm (right first) the 7 Panda joints, then the 16 Allegro "
+ "joints in the action's order"),
+ ("joint_vel", [f"{j}_vel" for j in JOINTS], "measured joint velocities (rad/s)"),
+ ("joint_effort", [f"{j}_effort" for j in JOINTS], "actuator efforts (N m): the arm's operational-space torques and the "
+ "hand's position-actuator forces"),
+ ("gripper_opening", [], "none: a 16-DoF Allegro hand, its finger joints are in joint_pos"),
+ ("tcp_pose", [f"{TCP[a]}_{k}" for a in ARMS for k in POSE], "measured tcp pose per arm (x y z m, quaternion wxyz, world)"),
+ ("tcp_target", [f"{TCP[a]}_target_{k}" for a in ARMS for k in POSE], "the tcp target the controller tracks now (the "
+ "ee_pose part of the last executed row)"),
+ ("hand_target", [f"{j}_target" for a in ARMS for j in HAND_JOINTS[a]], "the Allegro joint targets now (rad)"),
+]
+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)
+
+
+def _quat(xmat) -> np.ndarray:
+ q = np.zeros(4)
+ mujoco.mju_mat2Quat(q, np.asarray(xmat, dtype=np.float64).reshape(9))
+ return q
+
+
+# ------------------------------------------------------------------------------------------------- cameras
+CAMS = S.cameras()
+HAND_CAMS = [c for c in CAMS if c.startswith("handcam")]
+DEFAULT_CAMS = [S.default_camera()]
+GL2CV = np.diag([1.0, -1.0, -1.0, 1.0])
+
+
+def _intrinsic(cam: str) -> list:
+ fovy = math.radians(float(MD.cam_fovy[MD.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 _cam2world_gl(cam: str) -> np.ndarray:
+ i = MD.camera(cam).id
+ T = np.eye(4)
+ T[:3, :3] = D.cam_xmat[i].reshape(3, 3) # MuJoCo camera axes: OpenGL (x right, y up, z back)
+ T[:3, 3] = D.cam_xpos[i]
+ return T
+
+
+def _extrinsic(cam: str) -> np.ndarray:
+ return np.linalg.inv(_cam2world_gl(cam) @ GL2CV)[:3, :]
+
+
+def camera_info(cam: str) -> dict:
+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist(),
+ "image_size": [CAM_W, CAM_H]}
+
+
+def _mount(cam: str) -> dict:
+ i = MD.camera(cam).id
+ body = MD.body(int(MD.cam_bodyid[i])).name
+ if int(MD.cam_bodyid[i]) == 0:
+ return {"type": "static", "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist()}
+ T = np.eye(4) # body -> camera (OpenGL axes), then to OpenCV axes
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.cam_quat[i])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.cam_pos[i]
+ return {"type": "link", "parent_link": body, "link_T_cam_cv": (T @ GL2CV).tolist()}
+
+
+def _mounted(cam: str) -> str:
+ if cam.startswith("handcam"):
+ side = "the right" if cam.endswith("_right") else "the left" if cam.endswith("_left") else "the"
+ return f"on {side} hand's mount (moves with the hand)"
+ return {"front": "static, across the table, facing the robot", "back": "static, behind the robot, looking over the table",
+ "left": "static, at the robot's left", "right": "static, at the robot's right",
+ "top0": "static, above the table, looking down"}.get(cam, "static")
+
+
+# ------------------------------------------------------------------------------------------------- kinematics
+KD = mujoco.MjData(MD) # kinematics only: never stepped; the robot's joints are set, everything else stays put
+ARM_QI = {a: [JOINTS.index(j) for j in ARM_JOINTS[a]] for a in ARMS}
+
+
+def _fk(q) -> None:
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR] = np.asarray(q, dtype=np.float64)
+ mujoco.mj_kinematics(MD, KD)
+
+
+def _link_pose(name: str) -> list:
+ for a in ARMS:
+ if name == TCP[a]:
+ s = TCP_SITE[a]
+ return [*KD.site_xpos[s].tolist(), *_quat(KD.site_xmat[s]).tolist()]
+ b = MD.body(name).id
+ return [*KD.xpos[b].tolist(), *KD.xquat[b].tolist()]
+
+
+def tcp_from_arm_joints(a: str, q7) -> np.ndarray:
+ """The tcp pose (xyz + wxyz) of arm `a` with its 7 joints at q7 (the joint_position action's tcp target)."""
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR[ARM_QI[a]]] = q7
+ mujoco.mj_kinematics(MD, KD)
+ s = TCP_SITE[a]
+ return np.concatenate([KD.site_xpos[s], _quat(KD.site_xmat[s])])
+
+
+def do_kinematics(req: dict) -> dict:
+ """World frame. FK: every link of spec kinematics.links for q. IK: per tcp target, damped least squares over that
+ arm's 7 joints (position and orientation), within the joint ranges; the hand joints are taken from the seed."""
+ if req["op"] == "fk":
+ _fk(req["q"])
+ return L.fk_response({n: _link_pose(n) for n in req["links"]}, "world")
+ q = np.array(req["seed"] if req["seed"] is not None else D.qpos[QADR], dtype=np.float64)
+ errors = {}
+ jp, jr = np.zeros((3, MD.nv)), np.zeros((3, MD.nv))
+ for frame, pose in req["targets"].items():
+ a = next(x for x in ARMS if TCP[x] == frame)
+ idx = ARM_QI[a]
+ dofs = VADR[idx]
+ tp, tq = np.asarray(pose[:3]), np.asarray(pose[3:7])
+ lo = np.array([JLIM[JOINTS[i]][0] for i in idx]); hi = np.array([JLIM[JOINTS[i]][1] for i in idx])
+ for _ in range(req["max_iters"]):
+ _fk(q)
+ mujoco.mj_comPos(MD, KD) # the Jacobian needs cdof, which mj_kinematics alone leaves stale
+ s = TCP_SITE[a]
+ ep = tp - KD.site_xpos[s]
+ cq = _quat(KD.site_xmat[s])
+ dq = np.zeros(4); neg = np.zeros(4); er = np.zeros(3)
+ mujoco.mju_negQuat(neg, cq); mujoco.mju_mulQuat(dq, tq, neg); mujoco.mju_quat2Vel(er, dq, 1.0)
+ if np.linalg.norm(ep) < req["tol_pos_m"] and np.linalg.norm(er) < req["tol_rot_rad"]:
+ break
+ mujoco.mj_jacSite(MD, KD, jp, jr, s)
+ J = np.vstack([jp[:, dofs], jr[:, dofs]])
+ err = np.concatenate([ep, er])
+ step = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), err)
+ q[idx] = np.clip(q[idx] + step, lo, hi)
+ _fk(q)
+ s = TCP_SITE[a]
+ errors[frame] = (float(np.linalg.norm(tp - KD.site_xpos[s])), L.quat_angle(_quat(KD.site_xmat[s]), tq / np.linalg.norm(tq)))
+ ok = all(e[0] <= req["tol_pos_m"] and e[1] <= req["tol_rot_rad"] for e in errors.values())
+ return L.ik_response(q, ok, errors, "world", note="the tcp (attachment_site) of each arm; the hand joints are the seed's")
+
+
+# ------------------------------------------------------------------------------------------------- spec
+def _joint_spec(a: str) -> list:
+ out = []
+ for j, ai in zip(ARM_JOINTS[a], ARM_CTRL[a]):
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_ctrlrange[ai][1]), "group": f"{a}_arm"})
+ for j, ai in zip(HAND_JOINTS[a], HAND_CTRL[a]):
+ fl = bool(MD.actuator_forcelimited[ai]) and float(MD.actuator_forcerange[ai][1]) > 0
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_forcerange[ai][1]) if fl else None, "group": f"{a}_hand"})
+ return out
+
+
+def _tcp_spec(a: str) -> dict:
+ s = TCP_SITE[a]
+ T = np.eye(4)
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.site_quat[s])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.site_pos[s]
+ return {"parent_link": MD.body(int(MD.site_bodyid[s])).name, "link_T_frame": T.tolist(),
+ "definition": "DexJoCo's attachment_site: the flange where the Allegro hand is mounted, the point its "
+ "operational-space controller drives to the ee_pose target (not the fingertips)"}
+
+
+def _base(a: str) -> list:
+ b = D.body(f"link0{SFX[a]}")
+ return [*np.round(b.xpos, 6).tolist(), *np.round(b.xquat, 6).tolist()]
+
+
+GAINS = {}
+for _a in ARMS:
+ for _j, _ai in zip(HAND_JOINTS[_a], HAND_CTRL[_a]):
+ GAINS[_j] = {"stiffness": float(MD.actuator_gainprm[_ai][0]), "damping": float(MD.dof_damping[MD.jnt_dofadr[MD.joint(_j).id]])}
+ROBOT_NAME = "franka-allegro-bimanual" if BIM else "franka-allegro"
+try:
+ TASK_TEXT = open(TASK_TEXT_FILE).read().strip()
+except OSError:
+ TASK_TEXT = f"DexJoCo {TASK}"
+SPEC = {
+ "protocol": L.PROTOCOL,
+ "protocol_compat": list(L.COMPAT),
+ "simulator": "DexJoCo @ 8d23b0f on MuJoCo 3.4.0 (CPU physics, OSMesa rendering)",
+ "robot": ROBOT_NAME,
+ "task_text": TASK_TEXT,
+ "control_hz": CTRL_HZ,
+ "physics_substeps": SUBSTEPS,
+ "physics_hz": CTRL_HZ * SUBSTEPS,
+ "max_chunk_s": MAX_CHUNK_S,
+ "max_watch_s": MAX_WATCH_S,
+ "cameras": {c: {"rgb": True, "depth": True, "mounted": _mounted(c), "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),
+ "mount": _mount(c)} for c in CAMS},
+ "default_cameras": DEFAULT_CAMS,
+ "action_types": {
+ "ee_pose": {
+ "dim": ADIM, "layout": EE_LAYOUT,
+ "units": "per arm (right first): tcp target position (m, world frame), tcp target orientation (quaternion wxyz), "
+ "16 Allegro joint targets (rad)",
+ "frame": "world", "quaternion_order": "wxyz", "ee_frames": [TCP[a] for a in ARMS],
+ "hand_limits": {j: ALIM[j] for a in ARMS for j in HAND_JOINTS[a]},
+ "semantics": "DexJoCo's own action row. The arm tracks the tcp target through DexJoCo's operational-space "
+ "controller (it lags a moving target and stops where contact blocks it); the hand joints are "
+ "position-controlled. Rows are `dt` apart (a whole multiple of 1/50 s, at most 0.5 s); between rows "
+ "positions and joints move linearly and orientations by slerp (`linear`) or jump (`hold`); a row's "
+ "own values land exactly on its last control step. Hand targets outside the ranges are clamped by "
+ "the simulator and reported in `clipped`; a zero quaternion is a 400.",
+ },
+ "joint_position": {
+ "dim": ADIM, "layout": JP_LAYOUT, "units": "rad", "limits": {j: ALIM[j] for j in JP_LAYOUT},
+ "semantics": "per arm (right first): 7 Panda joint targets, then the 16 Allegro joint targets. The arm's "
+ "targets are turned into a tcp target by forward kinematics (as POST /kinematics fk) and the arm "
+ "tracks that pose through the same operational-space controller as ee_pose, whose null space "
+ "pulls towards DexJoCo's home posture: the tcp reaches FK(q), the measured joints may differ from q "
+ "in the arm's redundant direction. Rows `dt` apart, `linear` (in joint space) or `hold`; values "
+ "outside the limits are clipped and reported.",
+ },
+ "not_yet": ["joint_delta", "joint_velocity", "ee_delta", "joint_torque"],
+ },
+ "proprio_layout": PROPRIO_LAYOUT,
+ "proprio_groups": PROPRIO_GROUPS,
+ "static": {},
+ "world": {"frame": "DexJoCo's world frame: z up, metres; the robot" + ("s stand" if BIM else " stands")
+ + " at low x and reach" + ("" if BIM else "es") + " towards +x"
+ + (" (right arm at y < 0, left arm at y > 0)" if BIM else ""),
+ "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},
+ "episode": "one episode, no reset: it ends at the first success, at a task failure (see task_text), or when your time is over",
+ "robot_spec": {
+ "name": ROBOT_NAME,
+ "description": ("two Franka Panda arms side by side, each with a 16-DoF Allegro hand (right arm first)" if BIM
+ else "a Franka Panda arm with a 16-DoF Allegro hand"),
+ "base": {"type": "fixed", "pose": _base(ARMS[0]), **({"per_arm": {a: _base(a) for a in ARMS}} if BIM else {}),
+ "note": "pose of the arm's base link (link0), world frame, x y z + quaternion wxyz"},
+ "joints": [j for a in ARMS for j in _joint_spec(a)],
+ "grippers": {},
+ "controller": {"type": "arm: operational-space control of the tcp (torques); hand: joint position actuators",
+ "control_hz": CTRL_HZ, "physics_hz": CTRL_HZ * SUBSTEPS, "gains": GAINS,
+ "note": "arm: DexJoCo's opspace controller drives attachment_site to the tcp target (position gains "
+ "400 N/m, damping ratio 4, gravity compensation, null space towards the home posture), "
+ "torques limited to effort_limit; hand: position actuators (stiffness N m/rad) on joints "
+ "with their own damping (N m s/rad)"},
+ "tcp": {TCP[a]: _tcp_spec(a) for a in ARMS},
+ },
+ "kinematics": {"endpoint": "/kinematics", "joint_names": JOINTS, "frame": "world", "quaternion_order": "wxyz",
+ "links": KIN_LINKS, "tcp_frames": [TCP[a] for a in ARMS], "ee_frames": [TCP[a] for a in ARMS],
+ "ik_targets": [TCP[a] for a in ARMS], "ik": {"tol_pos_m": 0.001, "tol_rot_rad": 0.01, "max_iters": 300},
+ "note": "the arm links, the hand mount (the hand cameras' parent) and the tcp, world frame; ik solves "
+ "each tcp target over that arm's 7 joints"},
+ "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()
+
+
+# ------------------------------------------------------------------------------------------------- state and frames
+def ctrl_steps() -> int:
+ return int(S.steps)
+
+
+def proprio_row() -> np.ndarray:
+ tcp, tgt, hand = [], [], []
+ for a in ARMS:
+ s = TCP_SITE[a]
+ tcp += [D.site_xpos[s], _quat(D.site_xmat[s])]
+ t = S._arm_target(a)
+ tgt.append(t[:7]); hand.append(t[7:23])
+ return np.concatenate([D.qpos[QADR], D.qvel[VADR], D.actuator_force[EFF_ACT], *tcp, *tgt, *hand]).astype(np.float32)
+
+
+def grab(cams, want_depth: bool):
+ rgb, dep = {}, {}
+ for c in cams:
+ rgb[c] = S.render_frame(c, (CAM_H, CAM_W))
+ if want_depth:
+ r = S._renderer # the one renderer (a second OSMesa context reads back garbage)
+ r.enable_depth_rendering()
+ try:
+ r.update_scene(D, camera=c)
+ dep[c] = r.render().astype(np.float32).copy()
+ finally:
+ r.disable_depth_rendering()
+ return rgb, dep
+
+
+def extrinsics(cams) -> dict:
+ return {c: _extrinsic(c) for c in cams}
+
+
+def summary() -> dict:
+ n = int(E.get("episode_control_steps") or ctrl_steps())
+ 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"],
+ "task": TASK, "protocol": L.PROTOCOL, "n_actions": len(ROWS), "task_failure": int(str(E["reason"] or "").startswith("failure")),
+ **EP.final_fields()}
+
+
+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 finish(reason: str) -> None:
+ """The episode is over: record the live verdict and dump the trajectory 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()
+ E["success"] = bool(S.success)
+ 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()
+ S.save_trajectory(np.asarray(ROWS, dtype=np.float64).reshape(-1, ADIM), os.path.join(DATA, "trajectory.npz"),
+ {"source": "standard-mode episode", "reason": E["reason"]})
+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})
+ write_final()
+
+
+def ctrl_step(a, rec) -> bool:
+ """One executed control step (DexJoCo's own row), journaled. True when the call must stop here."""
+ a = np.asarray(a, dtype=np.float64)
+ running = S.step(a)
+ ROWS.append(a.copy())
+ stop = EP.journal(a)
+ rec.tick()
+ if not running:
+ finish(S.reason or "done")
+ 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 DEFAULT_CAMS
+ if not isinstance(cams, list) or any(c not in CAMS for c in cams):
+ raise ValueError(f"unknown cameras {cams}; cameras: {CAMS}")
+ return list(dict.fromkeys(cams))
+
+
+def meta_common(cams) -> dict:
+ n = ctrl_steps()
+ return {"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}}
+
+
+def _native_from_ee(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ """ee_pose rows are executed as sent (the recorded row is what the agent commanded); hand targets outside the
+ actuator ranges are clamped by MuJoCo itself (ctrllimited) and only reported."""
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ if float(np.linalg.norm(row[o + 3:o + 7])) < 1e-6:
+ raise ValueError(f"row {ri}: the {a} tcp quaternion has zero norm")
+ for j in range(16):
+ lo, hi = HLIM[a][j]
+ v = row[o + 7 + j]
+ if v < lo or v > hi:
+ clipped.append({"row": ri, "index": int(o + 7 + j), "reason": f"{EE_LAYOUT[o + 7 + j]} outside [{lo:.3f}, {hi:.3f}]: clamped by the simulator"})
+ return row
+
+
+def _clip_joints(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ lo = np.array([ALIM[j][0] for j in JP_LAYOUT]); hi = np.array([ALIM[j][1] for j in JP_LAYOUT])
+ out = np.clip(row, lo, hi)
+ for j in np.flatnonzero(out != row)[:20]:
+ clipped.append({"row": ri, "index": int(j), "reason": f"{JP_LAYOUT[j]} limit [{lo[j]:g}, {hi[j]:g}]"})
+ return out
+
+
+def _native_from_joints(q: np.ndarray) -> np.ndarray:
+ out = []
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ out += [tcp_from_arm_joints(a, q[o:o + 7]), q[o + 7:o + 23]]
+ return np.concatenate(out)
+
+
+def _check_chunk(typ: str, A: np.ndarray, dt: float, interp: str, video: str) -> int:
+ k = dt / DT
+ if A.ndim != 2 or A.shape[1] != ADIM:
+ raise ValueError(f"{typ} actions must be (T, {ADIM}), got {list(A.shape)}")
+ if A.shape[0] == 0:
+ raise ValueError("no rows")
+ 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")
+ return int(round(k))
+
+
+def do_submit(meta: dict, A: np.ndarray):
+ typ = meta.get("type")
+ if typ not in ("ee_pose", "joint_position"):
+ raise ValueError(f"type must be ee_pose or joint_position (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)
+ n = _check_chunk(typ, A, dt, interp, video)
+ clipped: list = []
+ if typ == "ee_pose":
+ A = np.stack([_native_from_ee(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ else:
+ A = np.stack([_clip_joints(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ rec = recorder(cams, fps, meta)
+ E["calls"] += 1
+ step0, before = E["step"], ctrl_steps()
+ rec.tick(force=True)
+ if typ == "ee_pose":
+ prev = np.asarray(S.hold_action(), dtype=np.float64)
+ else:
+ prev = np.concatenate([np.concatenate([D.qpos[QADR[ARM_QI[a]]], S._arm_target(a)[7:23]]) for a in ARMS])
+ for row in A:
+ E["step"] += 1
+ stop = False
+ for s in range(1, n + 1):
+ if interp == "hold" or s == n:
+ target = row # a row's own values land exactly on its last control step
+ else:
+ target = prev + (row - prev) * (s / n)
+ if typ == "ee_pose":
+ for k in range(len(ARMS)):
+ o = 23 * k
+ target[o + 3:o + 7] = M.quat_slerp(prev[o + 3:o + 7], row[o + 3:o + 7], s / n)
+ native = target if typ == "ee_pose" else _native_from_joints(target)
+ if ctrl_step(native, rec):
+ stop = True
+ break
+ prev = row
+ 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"], "type": typ, "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 = np.asarray(S.hold_action(), dtype=np.float64)
+ 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={"task": TASK, "instance_sha": S.instance_sha, "instance_ok": bool(S.instance_exact), "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} DexJoCo sim ready ({TASK}; 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/task_conventions.py b/scripts/task_conventions.py
index cc08c2c043..3fa5643e1e 100644
--- a/scripts/task_conventions.py
+++ b/scripts/task_conventions.py
@@ -47,7 +47,7 @@ BENCHMARKS = [ # (directory prefix, label)
("robowits-", "RoboWits"), ("robopaint-strict-", "RoboPaint-strict"), # before "robopaint-"
("robopaint-", "RoboPaint"), ("robolab-", "RoboLab"),
("behavior-", "BEHAVIOR-1K"), ("maniguard-", "ManiGuard"),
- ("molmospaces-", "MolmoSpaces"), ("myosuite-", "MyoSuite"),
+ ("molmospaces-", "MolmoSpaces"), ("myosuite-", "MyoSuite"), ("dexjoco-", "DexJoCo"),
("vlabench-", "VLABench"),
("robocasa-gr1-", "RoboCasa-GR1"), # before "robocasa-": the first matching prefix wins
("robocasa-", "RoboCasa"), ("robocasa365-", "RoboCasa365"),
diff --git a/tasks/dataset.toml b/tasks/dataset.toml
index 45d0314f31..be78a716c7 100644
--- a/tasks/dataset.toml
+++ b/tasks/dataset.toml
@@ -5117,3 +5117,91 @@ digest = "sha256:a39156e282927ad7dbfa821c80111293caeb551ffc356a4b400822a5f26d0c8
name = "robot-coding-bench/mujoco_playground_spot_joystick_gait_tracking-standard"
digest = "sha256:d1fc73ff53db47e6bb72e31f3c9b91e8e5956d79caf65e1c83777d2427b7f49e"
+[[tasks]]
+name = "robot-coding-bench/dexjoco-bimanual-assembly-i00-privileged"
+digest = "sha256:f694dff30996428d375c1380fb922f61d9bc91281576f6528ee6defe33982909"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-bimanual-assembly-i00-standard"
+digest = "sha256:b79fc2e0158c5f409fbd1cfd89627e83cdd3200bc600c03848c9a3e207f2bc4c"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-bimanual-hanoi-i00-privileged"
+digest = "sha256:046b51b712d6473129dd2b40f239d5d1d01d33f537625932bf56a7fd92fbfaed"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-bimanual-hanoi-i00-standard"
+digest = "sha256:53fc54dec9f42658a37371c0beef39866ce90876346fa86a55996acb9d0b057d"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-bimanual-microwave-cook-i00-privileged"
+digest = "sha256:bb72725f5470d6c003a1bb5c400183753952e56e89eddc843bf2406c6f456ade"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-bimanual-microwave-cook-i00-standard"
+digest = "sha256:2ee7b2be7c14938126f697dfb7d968b1196ba82438054f1d18e2d8d4e77db26b"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-bimanual-photograph-i00-privileged"
+digest = "sha256:894498e1aff23acb06d3a3d4153b5eba0ea20109b6b5520abab392b7b899c17f"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-bimanual-photograph-i00-standard"
+digest = "sha256:36fcc50e2388b74ccfd88adcb5b6509473aeee422216259b8b1d06cc3f2003f8"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-bimanual-unlock-ipad-i00-privileged"
+digest = "sha256:56ce91e6fe7418554792903461614c6a9040149423cb600d9cffbdf20b331502"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-bimanual-unlock-ipad-i00-standard"
+digest = "sha256:6c195b434fbcab3df2594fb435923db9f1b841715739b5475142c2771caef2c1"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-click-mouse-i00-privileged"
+digest = "sha256:951737bef9b9f6040ac78a06d845232116702fe7c00a263edb9c72a1609d6b87"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-click-mouse-i00-standard"
+digest = "sha256:5e1b4a77e1dc00749c9b2ffc92a2482fe2b2ddce572e3b1ef786dd9298c4acb6"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-fold-glasses-i00-privileged"
+digest = "sha256:8bb93e5d5459e1ad6020fd0889f78e7588f63edafce4ce52ecd87a23df109f00"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-fold-glasses-i00-standard"
+digest = "sha256:278ffc15aefcdd6afb217de9bf8f2bd176259b97011b3ea263c11c11e77f558b"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-hammer-nail-i00-privileged"
+digest = "sha256:ed84b115a81285361800499377787b8f6f135967ad42c921ff8c09df849b2a39"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-hammer-nail-i00-standard"
+digest = "sha256:7f4018a8b260383753e8d53be4ed8ef5f63714b9c8cd7894f249d35adf64fc8b"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-pick-bucket-i00-privileged"
+digest = "sha256:16874cb8a33e29802b3da64ee044b6458a90e10ffa8f7981c15af926bc3cbf52"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-pick-bucket-i00-standard"
+digest = "sha256:9df447e71585c6ec93233d6e627b2b86a1cae524e6aaafb3bf044ae75c00e2ae"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-pinch-tongs-i00-privileged"
+digest = "sha256:dcd4cca08649748ecb014f75aa78fbd343d2ca3ff5fab070a3637b5e174ae311"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-pinch-tongs-i00-standard"
+digest = "sha256:0f7e6c105f3bc21ea5510a7951e1c850719213c8eacf099974d2f6f3a19068c9"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-water-plant-i00-privileged"
+digest = "sha256:3967f060583e2ffd6a4cecbf78ad3351e04698293ee74298eba19f2844d19b30"
+
+[[tasks]]
+name = "robot-coding-bench/dexjoco-water-plant-i00-standard"
+digest = "sha256:a515e9a6868f5745811e349340a399ae48c1123e568aab35d1882451d79ad6a2"
+
diff --git a/tasks/dexjoco-bimanual-assembly-i00-privileged/README.md b/tasks/dexjoco-bimanual-assembly-i00-privileged/README.md
new file mode 100644
index 0000000000..3b55424155
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-privileged/README.md
@@ -0,0 +1,49 @@
+# dexjoco-bimanual-assembly-i00-privileged
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | privileged |
+| Twin | `dexjoco-bimanual-assembly-i00-standard` |
+| Simulator / robot | `dexjoco` / `franka-allegro-bimanual` |
+| Family / instance | `bimanual_assembly` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `bimanual_assembly` (two Franka Panda arms, each with a 16-DoF Allegro hand): Hold the tray with one hand and insert the round peg into its socket with the other. Success: the peg touches the socket's bottom for 30 consecutive control steps.
+Privileged mode: the agent works in the simulator's container with live object poses, unlimited resets and thin motion
+primitives, and hands in one trajectory replayed open-loop from the frozen instance.
+
+## Difficulty
+First-pass rating: hard. Dexterous manipulation with two 16-DoF hands on two arms (46 action values per control step);
+the primitives only move tcp and hand-joint targets, so grasping, pressing and every other skill is the agent's. The
+reference (the human teleoperator's demonstration) takes 586 control steps (11.7 s at 50 Hz).
+
+## Reference solution
+`solution/oracle_trajectory.npz` = the human demonstration's own actions, rounded to float32 (the standard client's
+precision; the rounded rows still succeed) and replayed from the frozen instance until the episode ends in success
+(586 rows). The demonstration is public (DexJoCo-Datasets-Raw on Hugging Face), so agent egress is
+limited to the model APIs.
+
+## Verification
+Open-loop replay of `/app/output/trajectory.npz` from `tests/instance.npz`, twice in a fresh process in the verifier's own
+sandbox (no network); pass iff both episodes end in success, their final-state hashes agree and the rebuilt instance
+matches its recorded hash (`tests/grade.py`); plus `/logs/verifier/replay.mp4`. Oracle: success after 586 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `assembly_demo_10_2026-03-19_17-36-54_867270` (DexJoCo-Datasets-Raw), restored with DexJoCo's own state restorer; instance sha `e39abc9b3d77cd72` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Tooling notes
+DexJoCo's reset samples object poses from the global RNG and its state restorer edits the MuJoCo model (table height,
+fixed bodies), so `instance.npz` stores the full physics state (`mjSTATE_INTEGRATION`), the mocap targets, the controls,
+every numeric model array a task can change, and the env's Python-side task state. Its per-step camera rendering,
+real-time sleep, episode cap and hanoi's wall-clock auto-reset are disabled in the tooling (`rcb_dexjoco.py`).
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py` from `scripts/dexjoco/instances/bimanual_assembly/` (`make_instances.py`).
diff --git a/tasks/dexjoco-bimanual-assembly-i00-privileged/environment/Dockerfile b/tasks/dexjoco-bimanual-assembly-i00-privileged/environment/Dockerfile
new file mode 100644
index 0000000000..d736fe8a7d
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-privileged/environment/Dockerfile
@@ -0,0 +1,7 @@
+# Base image = DexJoCo on MuJoCo 3.4.0 (images/dexjoco/). Everything task-specific is copied here. CPU only.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY instance.npz /app/instance.npz
+COPY rcb_dexjoco.py /opt/tools/rcb_dexjoco.py
+ENV PYTHONPATH=/opt/tools
+RUN mkdir -p /app/output
+WORKDIR /app
diff --git a/tasks/dexjoco-bimanual-assembly-i00-privileged/environment/instance.npz b/tasks/dexjoco-bimanual-assembly-i00-privileged/environment/instance.npz
new file mode 100644
index 0000000000..d8c094224d
Binary files /dev/null and b/tasks/dexjoco-bimanual-assembly-i00-privileged/environment/instance.npz differ
diff --git a/tasks/dexjoco-bimanual-assembly-i00-privileged/environment/rcb_dexjoco.py b/tasks/dexjoco-bimanual-assembly-i00-privileged/environment/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-privileged/environment/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-bimanual-assembly-i00-privileged/instruction.md b/tasks/dexjoco-bimanual-assembly-i00-privileged/instruction.md
new file mode 100644
index 0000000000..9b09a327b1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-privileged/instruction.md
@@ -0,0 +1,91 @@
+# DexJoCo · bimanual_assembly — frozen instance
+
+You control two Franka Panda arms, each with a 16-DoF Allegro hand (DexJoCo on MuJoCo 3.4) via Python. **Task:** Hold the tray with one hand and insert the round peg into its socket with the other. Success: the peg touches the socket's bottom for 30 consecutive control steps.
+
+The tray with a round socket and the 8 mm round peg lie on the table in front of the robots. `s.objects()` gives the live poses of the task objects (`peg`, `peg_tip`, `tray`, `socket`, `table_top`). DexJoCo's success code (from
+`/opt/dexjoco/dexjoco/dexjoco/sim/envs/panda_bimanual_assembly_env.py`; `step()` ends the episode on success or on a task failure):
+```python
+def _compute_success(self) -> bool:
+ success, _, _ = self._compute_success_metrics()
+ return bool(success)
+
+def _compute_success_metrics(self) -> Tuple[bool, bool, int]:
+ contact_count = 0
+ for i in range(int(self._data.ncon)):
+ c = self._data.contact[i]
+ g1 = int(c.geom1)
+ g2 = int(c.geom2)
+ if (
+ (g1 == self._peg_geom_id and g2 == self._socket_bottom_geom_id)
+ or (g2 == self._peg_geom_id and g1 == self._socket_bottom_geom_id)
+ ):
+ contact_count += 1
+ bottom_contact = contact_count > 0
+ triggered = bottom_contact
+
+ if triggered:
+ if not getattr(self, "_success_started", False):
+ self._success_started = True
+ self._success_counter = 1
+ else:
+ self._success_counter += 1
+ else:
+ self._success_started = False
+ self._success_counter = 0
+ # print(f"Triggered: {triggered}")
+ if getattr(self, "_success_counter", 0) >= 30:
+ return True
+
+ return False
+ # return bool(bottom_contact), bool(bottom_contact), int(contact_count)
+```
+
+This is a *fixed scene instance*: object poses, the table height and the robot's start pose never change between
+resets. You may reset and retry as many times as you want. Your deliverable is **one replayable trajectory**, not a
+general policy.
+
+## Deliverable
+Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
+open-loop from the same initial state in a fresh process and scored 1 if its episode ends in success, else 0. Also
+leave the script that produced it at `/app/output/gen.py`. You have 90 minutes of wall clock: save a
+first trajectory early, improve it, and do not stop before the task is solved.
+
+## Tooling (already installed; run `python` from any directory)
+```python
+from rcb_dexjoco import Session
+s = Session("bimanual_assembly", instance="/app/instance.npz") # ~1 s: builds the env and loads the frozen state
+s.reset() # back to the frozen initial state (as often as you like; an exact snapshot restore)
+s.objects() # live task objects: name -> pos, quat_wxyz (bodies) / pos (sites) / qpos (joints)
+s.state() # DexJoCo's state dict: tcp_pose, gripper_pose (hand joints), INITIAL object poses, table height
+p = s.primitives() # thin wrappers of the low-level action; each has a docstring: help(p["move_ee"])
+p["move_ee"]("right", pos, quat_wxyz) # straight-line + slerp motion of an arm's tcp target, then settle
+p["set_hand"]("right", q16) # interpolate the 16 Allegro joint targets
+p["hold"](10); p["set_targets"](row, steps) # keep every target / send one raw action row
+p["get_ee_pose"]("right"); p["get_ee_target"]("right"); p["get_hand"]("right"); p["get_body_pose"](name)
+s.render_frame("back") # RGB uint8 (480, 640, 3); cameras: ['back', 'handcam_rgb_right', 'handcam_rgb_left']; s.render_grid()
+s.step(action) # one control step (46 values, below) = 1/50 s; returns False once the episode is over
+s.record_start(); ...; actions = s.record_stop() # (T, 46) actions, one row per control step
+s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+s.replay(actions) # resets, replays open-loop until the episode ends, returns status -> self-check
+s.save_trajectory(actions, "/app/output/trajectory.npz")
+s.render_video(actions, "/app/output/check.mp4", cameras=["back"]) # replays from the frozen state into a video
+```
+The primitives are deliberately thin (tcp target moves, hand joint targets, hold): grasping, pressing, striking and
+every other skill are yours to build from them. `s.bodies()` lists every MuJoCo body for `p["get_body_pose"]`.
+
+CLI equivalent of the grader:
+`python /opt/tools/rcb_dexjoco.py replay --task bimanual_assembly --instance /app/instance.npz --traj /app/output/trajectory.npz`
+
+## Conventions
+- World frame, metres; z up; the robots stand at low x and reach towards +x. The table top is at z = 0.956. Arm base (`link0`): link0_right [-0.75, -0.4, 0.924], link0_left [-0.75, 0.4, 0.924]. The right arm works at y < 0, the left arm at y > 0. Quaternions are **WXYZ**.
+- Action (46): per arm, right first: tcp target position (3), tcp target orientation (4, wxyz), 16 Allegro
+ joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+ target and stops where contact blocks it); the hand joints are position-controlled. `s.hold_action()` is the no-op.
+ At the start the tcp target is right [-0.443, -0.4, 1.517] / [0.0, -1.0, 0.0, -0.0025], left [-0.443, 0.4, 1.517] / [0.0, -1.0, 0.0, -0.0025].
+- Allegro joint order (right hand): index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger =
+ spread, 1-3 = flexion from the knuckle out; thumb 12 = opposition). The LEFT hand's 16 values are mirrored: ring 0-3, middle 4-7, index 8-11, thumb 12-15.
+ Target ranges (rad, same for every finger slot, thumb last): low [-0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, 0.26, -0.1, -0.19, -0.16], high [0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 1.4, 1.16, 1.64, 1.72]; the simulator clamps
+ targets to them.
+- Control runs at 50 Hz (10 physics substeps of 2 ms). DexJoCo's own episode cap and real-time pacing are lifted: there
+ is no step budget, your wall-clock time is the limit (~230 control steps/s here). An episode ends at the
+ first success or task failure; `s.step` then refuses further actions until `s.reset()`.
diff --git a/tasks/dexjoco-bimanual-assembly-i00-privileged/solution/gen.py b/tasks/dexjoco-bimanual-assembly-i00-privileged/solution/gen.py
new file mode 100644
index 0000000000..0e1f7e3bc7
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-privileged/solution/gen.py
@@ -0,0 +1,4 @@
+# How solution/oracle_trajectory.npz was made (scripts/dexjoco/make_instances.py): the DexJoCo human demonstration's
+# own actions (replay.zarr data/action), rounded to float32, replayed from the frozen instance with Session.replay until
+# the episode ended in success (holding the last row a few steps where the rounded rows ended short of a hold count),
+# truncated there and saved with Session.save_trajectory.
diff --git a/tasks/dexjoco-bimanual-assembly-i00-privileged/solution/oracle_trajectory.npz b/tasks/dexjoco-bimanual-assembly-i00-privileged/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..1e77b98bbf
Binary files /dev/null and b/tasks/dexjoco-bimanual-assembly-i00-privileged/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-bimanual-assembly-i00-privileged/solution/solve.sh b/tasks/dexjoco-bimanual-assembly-i00-privileged/solution/solve.sh
new file mode 100755
index 0000000000..7909c90cb8
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-privileged/solution/solve.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+# Reference solution: the human demonstration's actions (float32), replayed through the task tooling until success.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_trajectory.npz /app/output/trajectory.npz
+cp /solution/gen.py /app/output/gen.py
diff --git a/tasks/dexjoco-bimanual-assembly-i00-privileged/task.toml b/tasks/dexjoco-bimanual-assembly-i00-privileged/task.toml
new file mode 100644
index 0000000000..8dd8e8bbec
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-privileged/task.toml
@@ -0,0 +1,37 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator or the instance, not this.
+schema_version = "1.3"
+artifacts = ["/app/output/"]
+
+[task]
+name = "robot-coding-bench/dexjoco-bimanual-assembly-i00-privileged"
+description = "DexJoCo bimanual_assembly (two Franka Panda arms, each with a 16-DoF Allegro hand, MuJoCo): produce one replayable trajectory. Hold the tray with one hand and insert the round peg into its socket with the other. Frozen scene instance (the initial state of a DexJoCo human demonstration)."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "code-as-policy", "trajectory", "bimanual_assembly"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro-bimanual"
+family = "bimanual_assembly"
+mode = "privileged"
+oracle = "full"
+expert_time_estimate_hours = 2.5
+
+[verifier]
+timeout_sec = 1800.0
+environment_mode = "separate" # the verifier runs in its own sandbox (tests/Dockerfile); the agent container is gone by then
+network_mode = "no-network"
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
+
+[verifier.environment]
+build_timeout_sec = 1800.0
diff --git a/tasks/dexjoco-bimanual-assembly-i00-privileged/tests/Dockerfile b/tasks/dexjoco-bimanual-assembly-i00-privileged/tests/Dockerfile
new file mode 100644
index 0000000000..a2620a4da8
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-privileged/tests/Dockerfile
@@ -0,0 +1,8 @@
+# Separate verifier sandbox (PROTOCOL §2.6): the same simulator image with the verifier's own copies of the tooling and
+# the frozen instance baked in. Nothing the agent did in its container reaches this one: Harbor uploads only the declared
+# artifacts (/app/output/), so a patched success check in the agent container cannot count.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY grade.py instance.npz rcb_dexjoco.py test.sh /tests/
+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
+ENV PYTHONPATH=/tests
+WORKDIR /tests
diff --git a/tasks/dexjoco-bimanual-assembly-i00-privileged/tests/grade.py b/tasks/dexjoco-bimanual-assembly-i00-privileged/tests/grade.py
new file mode 100644
index 0000000000..ad916e8bb9
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-privileged/tests/grade.py
@@ -0,0 +1,109 @@
+"""Verifier entry point for the privileged DexJoCo tasks: replay /app/output/trajectory.npz from the frozen instance and
+write Harbor rewards.
+
+ python /tests/grade.py --family water_plant --instance /tests/instance.npz --traj /app/output/trajectory.npz
+
+Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only; Harbor rejects strings), a replay video
+/logs/verifier/replay.mp4 (front camera + wrist camera) and replay.last.png. Replays `--repeat` times in this fresh
+process; success requires every replay to end its episode in success (DexJoCo's own rule: the episode ends at the first
+success or task failure) AND all final-state hashes to agree (MuJoCo on the CPU is bit-deterministic), and the frozen
+instance rebuilt here from tests/instance.npz must match its recorded hash.
+"""
+from __future__ import annotations
+import argparse, json, os, sys, time, traceback
+import numpy as np
+
+LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")
+
+
+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 self_reported_cost() -> dict:
+ # From the tooling's append-only log in the agent's container: SELF-REPORTED accounting, never evidence.
+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_records": 0, "agent_replays": 0,
+ "agent_cost_self_reported": 1}
+ try:
+ with open("/app/output/rcb_session_log.jsonl") 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 == "session_end": cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)
+ elif ev == "record": cost["agent_records"] += 1
+ elif ev == "replay": cost["agent_replays"] += 1
+ except Exception: # noqa: BLE001 — one bad line must not sink the verdict
+ continue
+ except Exception: # noqa: BLE001
+ pass
+ return cost
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--family", required=True); ap.add_argument("--instance", required=True)
+ ap.add_argument("--traj", default="/app/output/trajectory.npz"); ap.add_argument("--repeat", type=int, default=2)
+ ap.add_argument("--no-video", action="store_true")
+ a = ap.parse_args()
+ cost = self_reported_cost()
+ os.environ["RCB_SESSION_LOG"] = "" # the verifier's own sessions are not the agent's cost
+ if not os.path.isfile(a.traj):
+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost}); return 0
+ s = None
+ try:
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the verifier's own copy of the tooling
+ import rcb_dexjoco
+ rcb_dexjoco.SESSION_LOG = ""
+ from rcb_dexjoco import Session, MAX_STEPS
+ d = np.load(a.traj, allow_pickle=False)
+ if str(d["task"]) != a.family:
+ write(False, {"success": 0, "wrong_family": 1, "grader_error": 0, **cost}); return 0
+ acts = np.asarray(d["actions"], dtype=np.float64)
+ s = Session(a.family, instance=a.instance)
+ if (acts.ndim != 2 or acts.shape[1] != s.action_dim or acts.shape[0] > MAX_STEPS
+ or not np.all(np.isfinite(acts))):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0,
+ "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0, **cost}); return 0
+ t0 = time.time()
+ outs = []
+ for _ in range(a.repeat):
+ try:
+ outs.append(s.replay(acts))
+ except (ValueError, rcb_dexjoco.PrimitiveError):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0, "n_actions": int(len(acts)), **cost}); return 0
+ all_success = all(o["success"] for o in outs)
+ deterministic = len({o["state_sha"] for o in outs}) == 1
+ instance_ok = bool(s.instance_exact)
+ ok = all_success and deterministic and instance_ok
+ out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
+ "instance_ok": int(instance_ok), "n_actions": int(len(acts)), "sim_steps": int(outs[0]["steps"]),
+ "task_failure": int(bool(outs[0]["reason"]) and not outs[0]["success"]),
+ "replay_wall_s": round(time.time() - t0, 1), "grader_error": 0, "video_rendered": 0, **cost}
+ if not a.no_video: # human-viewable replay (never affects the verdict)
+ try:
+ n = int(outs[0]["replayed_rows"])
+ s.render_video(acts[:n], os.path.join(LOG_DIR, "replay.mp4"), cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ import imageio.v2 as imageio
+ imageio.imwrite(os.path.join(LOG_DIR, "replay.last.png"), s.render_frame(s.default_camera(), (480, 640)))
+ out["video_rendered"] = int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4")))
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(ok, out)
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(False, {"success": 0, "grader_error": 1, **cost})
+ finally:
+ if s is not None:
+ s.close()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tasks/dexjoco-bimanual-assembly-i00-privileged/tests/instance.npz b/tasks/dexjoco-bimanual-assembly-i00-privileged/tests/instance.npz
new file mode 100644
index 0000000000..d8c094224d
Binary files /dev/null and b/tasks/dexjoco-bimanual-assembly-i00-privileged/tests/instance.npz differ
diff --git a/tasks/dexjoco-bimanual-assembly-i00-privileged/tests/rcb_dexjoco.py b/tasks/dexjoco-bimanual-assembly-i00-privileged/tests/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-privileged/tests/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-bimanual-assembly-i00-privileged/tests/test.sh b/tasks/dexjoco-bimanual-assembly-i00-privileged/tests/test.sh
new file mode 100755
index 0000000000..50e403e402
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-privileged/tests/test.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in a fresh process.
+# 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/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)
+mkdir -p /logs/verifier
+python /tests/grade.py --family bimanual_assembly --instance /tests/instance.npz --traj /app/output/trajectory.npz --repeat 2 \
+ 2> /logs/verifier/grade.log
diff --git a/tasks/dexjoco-bimanual-assembly-i00-standard/README.md b/tasks/dexjoco-bimanual-assembly-i00-standard/README.md
new file mode 100644
index 0000000000..0aa782cc0b
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-standard/README.md
@@ -0,0 +1,45 @@
+# dexjoco-bimanual-assembly-i00-standard
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | standard (`eai-standard/2.2`) |
+| Twin | `dexjoco-bimanual-assembly-i00-privileged` |
+| Simulator / robot | `dexjoco` / `franka-allegro-bimanual` |
+| Family / instance | `bimanual_assembly` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `bimanual_assembly` (two Franka Panda arms, each with a 16-DoF Allegro hand) on the same frozen instance as `dexjoco-bimanual-assembly-i00-privileged`: Hold the tray with one hand and insert the round peg into its socket with the other. Success: the peg touches the socket's bottom for 30 consecutive control steps.
+Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with the robot's own
+sensors, calibrated cameras (RGB, optional depth) and the robot's kinematics.
+
+## Difficulty
+Same instance and success check as `dexjoco-bimanual-assembly-i00-privileged`. In standard mode the agent loses resets, the
+simulator and the object poses: it sees camera images and proprioception, acts in chunks of tcp-target + hand-joint rows
+(or joint targets), and gets one episode, so it has to close the loop on what the cameras show and recover from its own
+mistakes without starting over.
+
+## Reference solution
+`solution/oracle_stream.py` streams the privileged reference's rows (`solution/oracle_trajectory.npz`, 586 rows, float32-exact)
+through the client as `ee_pose` 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 586 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 586 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `assembly_demo_10_2026-03-19_17-36-54_867270` (DexJoCo-Datasets-Raw); instance sha `e39abc9b3d77cd72` |
+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); action types `ee_pose` and `joint_position`; cameras `back`, `handcam_rgb_right`, `handcam_rgb_left` (640 x 480); `/kinematics` for the arm links, the hand mount and the tcp; crash recovery class `exact` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py`, as its privileged twin.
diff --git a/tasks/dexjoco-bimanual-assembly-i00-standard/environment/Dockerfile b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/Dockerfile
new file mode 100644
index 0000000000..a778c94561
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/Dockerfile
@@ -0,0 +1,9 @@
+# Standard mode: the agent container has NO simulator and no DexJoCo 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 /app
diff --git a/tasks/dexjoco-bimanual-assembly-i00-standard/environment/client-requirements.txt b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/client-requirements.txt
new file mode 100644
index 0000000000..8aa73a968f
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-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.0
diff --git a/tasks/dexjoco-bimanual-assembly-i00-standard/environment/docker-compose.yaml b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/docker-compose.yaml
new file mode 100644
index 0000000000..abc3467feb
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/docker-compose.yaml
@@ -0,0 +1,24 @@
+# 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 OSMesa rendering; 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-dexjoco:0.1.2
+ 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_TASK: bimanual_assembly
+ RCB_INSTANCE: /srv/instance.npz
+ RCB_TOOL: /srv/rcb_dexjoco.py
+ RCB_DATA: /data
+ RCB_WALL_CLOCK_S: "5400"
+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in a few seconds
+ PYTHONPATH: /srv
+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction log
diff --git a/tasks/dexjoco-bimanual-assembly-i00-standard/environment/rcb1.py b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-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/dexjoco-bimanual-assembly-i00-standard/environment/rcb_client.py b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/rcb_client.py
new file mode 100644
index 0000000000..aa25b0e050
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-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/dexjoco-bimanual-assembly-i00-standard/environment/sim/finalize.sh b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/sim/finalize.sh
new file mode 100755
index 0000000000..e0cf248720
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-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_dexjoco.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:?}"; TASK="${RCB_TASK:?}"
+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 --task "$TASK" --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --repeat 1 \
+ --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"))
+PY
diff --git a/tasks/dexjoco-bimanual-assembly-i00-standard/environment/sim/instance.npz b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/sim/instance.npz
new file mode 100644
index 0000000000..d8c094224d
Binary files /dev/null and b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/sim/instance.npz differ
diff --git a/tasks/dexjoco-bimanual-assembly-i00-standard/environment/sim/rcb1.py b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/sim/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-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/dexjoco-bimanual-assembly-i00-standard/environment/sim/rcb_dexjoco.py b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/sim/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/sim/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-bimanual-assembly-i00-standard/environment/sim/rcb_limited.py b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/sim/rcb_limited.py
new file mode 100644
index 0000000000..1ce1171787
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-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/dexjoco-bimanual-assembly-i00-standard/environment/sim/run.sh b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/sim/run.sh
new file mode 100755
index 0000000000..49d4d045d4
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-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; done
diff --git a/tasks/dexjoco-bimanual-assembly-i00-standard/environment/sim/server.py b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/sim/server.py
new file mode 100644
index 0000000000..ca5b61fc5c
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/sim/server.py
@@ -0,0 +1,625 @@
+"""eai-standard/2.2 sim service for DexJoCo (docs/STANDARD_MODE_2_2.md): the adapter of the shared layer rcb_limited.py;
+the simulator is rcb_dexjoco.Session (DexJoCo on MuJoCo 3.4, CPU physics, OSMesa rendering).
+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to
+/data/episode.jsonl.
+
+The robot is a Franka Panda with a 16-DoF Allegro hand, or two of them side by side (right arm first). One control step
+= 1/50 s (10 physics substeps of 2 ms). Two action types:
+ ee_pose DexJoCo's own row, per arm: the tcp target pose (xyz m, quaternion wxyz, world frame) that its
+ operational-space controller tracks + 16 Allegro joint targets (rad);
+ joint_position per arm: 7 arm joint targets + 16 Allegro joint targets; the arm's targets are turned into a tcp target
+ by forward kinematics (the controller tracks the tcp pose, not the joints).
+Either way, the executed (journaled, recorded) row is DexJoCo's own row, so the recorded trajectory replays in the
+privileged tooling unchanged. As in DexJoCo's evaluation the episode ends at the first success or task failure;
+otherwise when the agent's time is over (the collect hook's SIGUSR1).
+
+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 instance 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")
+TASK = os.environ.get("RCB_TASK", "water_plant")
+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.npz"))
+TASK_TEXT_FILE = os.environ.get("RCB_TASK_TEXT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "task_text.txt"))
+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "5400"))
+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 = 640, 480
+CTRL_HZ = 50.0
+DT = 1.0 / CTRL_HZ
+SUBSTEPS = 10
+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"] = "" # the sidecar's Session is not the agent's interaction log
+import rcb_dexjoco as M # noqa: E402
+import mujoco # noqa: E402
+
+M.SESSION_LOG = ""
+BIM = TASK.startswith("bimanual_")
+ADIM = 46 if BIM else 23
+EP = L.Episode(DATA, dim=ADIM, resume="exact")
+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()
+S = M.Session(TASK, instance=INSTANCE, image_size=(CAM_H, CAM_W))
+MD, D = S.model, S.data
+ARMS = S.arms()
+SFX = {a: (f"_{a}" if BIM else "") for a in ARMS}
+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz
+
+# ------------------------------------------------------------------------------------------------- the robot
+ARM_JOINTS = {a: [f"joint{i}{SFX[a]}" for i in range(1, 8)] for a in ARMS}
+HAND_CTRL = {a: np.asarray(S._hand_ctrl_ids(a)) for a in ARMS}
+HAND_JOINTS = {a: [MD.joint(int(MD.actuator_trnid[i, 0])).name for i in HAND_CTRL[a]] for a in ARMS} # action order
+ARM_CTRL = {a: [MD.actuator(f"actuator{i}{SFX[a]}").id for i in range(1, 8)] for a in ARMS}
+JOINTS = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]] # kinematics q = proprio joint_pos columns
+QADR = np.array([MD.jnt_qposadr[MD.joint(j).id] for j in JOINTS])
+VADR = np.array([MD.jnt_dofadr[MD.joint(j).id] for j in JOINTS])
+EFF_ACT = np.array([i for a in ARMS for i in list(ARM_CTRL[a]) + list(HAND_CTRL[a])])
+TCP_SITE = {a: MD.site(f"attachment_site{SFX[a]}").id for a in ARMS}
+TCP = {a: f"tcp{SFX[a]}" for a in ARMS}
+MOUNT_BODY = {a: f"attachment{SFX[a]}" for a in ARMS}
+LINKS = {a: [f"link{i}{SFX[a]}" for i in range(0, 8) if mujoco.mj_name2id(MD, mujoco.mjtObj.mjOBJ_BODY, f"link{i}{SFX[a]}") >= 0]
+ + [MOUNT_BODY[a]] for a in ARMS}
+KIN_LINKS = [n for a in ARMS for n in LINKS[a] + [TCP[a]]]
+JLIM = {j: MD.jnt_range[MD.joint(j).id].astype(float).tolist() for j in JOINTS}
+HLIM = {a: S.hand_limits(a) for a in ARMS} # actuator ctrlrange, action order
+ALIM = {} # joint_position limits (inside the joint ranges)
+for a in ARMS:
+ for j in ARM_JOINTS[a]:
+ ALIM[j] = JLIM[j]
+ for j, (lo, hi) in zip(HAND_JOINTS[a], HLIM[a]):
+ ALIM[j] = [max(float(lo), JLIM[j][0]), min(float(hi), JLIM[j][1])]
+POSE = ["x", "y", "z", "qw", "qx", "qy", "qz"]
+EE_LAYOUT = [] # per arm, right first
+for a in ARMS:
+ EE_LAYOUT += [f"{TCP[a]}_target_{k}" for k in POSE] + [f"{j}_target" for j in HAND_JOINTS[a]]
+JP_LAYOUT = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]]
+
+GROUPS = [
+ ("joint_pos", JOINTS, "measured joint positions (rad): per arm (right first) the 7 Panda joints, then the 16 Allegro "
+ "joints in the action's order"),
+ ("joint_vel", [f"{j}_vel" for j in JOINTS], "measured joint velocities (rad/s)"),
+ ("joint_effort", [f"{j}_effort" for j in JOINTS], "actuator efforts (N m): the arm's operational-space torques and the "
+ "hand's position-actuator forces"),
+ ("gripper_opening", [], "none: a 16-DoF Allegro hand, its finger joints are in joint_pos"),
+ ("tcp_pose", [f"{TCP[a]}_{k}" for a in ARMS for k in POSE], "measured tcp pose per arm (x y z m, quaternion wxyz, world)"),
+ ("tcp_target", [f"{TCP[a]}_target_{k}" for a in ARMS for k in POSE], "the tcp target the controller tracks now (the "
+ "ee_pose part of the last executed row)"),
+ ("hand_target", [f"{j}_target" for a in ARMS for j in HAND_JOINTS[a]], "the Allegro joint targets now (rad)"),
+]
+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)
+
+
+def _quat(xmat) -> np.ndarray:
+ q = np.zeros(4)
+ mujoco.mju_mat2Quat(q, np.asarray(xmat, dtype=np.float64).reshape(9))
+ return q
+
+
+# ------------------------------------------------------------------------------------------------- cameras
+CAMS = S.cameras()
+HAND_CAMS = [c for c in CAMS if c.startswith("handcam")]
+DEFAULT_CAMS = [S.default_camera()]
+GL2CV = np.diag([1.0, -1.0, -1.0, 1.0])
+
+
+def _intrinsic(cam: str) -> list:
+ fovy = math.radians(float(MD.cam_fovy[MD.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 _cam2world_gl(cam: str) -> np.ndarray:
+ i = MD.camera(cam).id
+ T = np.eye(4)
+ T[:3, :3] = D.cam_xmat[i].reshape(3, 3) # MuJoCo camera axes: OpenGL (x right, y up, z back)
+ T[:3, 3] = D.cam_xpos[i]
+ return T
+
+
+def _extrinsic(cam: str) -> np.ndarray:
+ return np.linalg.inv(_cam2world_gl(cam) @ GL2CV)[:3, :]
+
+
+def camera_info(cam: str) -> dict:
+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist(),
+ "image_size": [CAM_W, CAM_H]}
+
+
+def _mount(cam: str) -> dict:
+ i = MD.camera(cam).id
+ body = MD.body(int(MD.cam_bodyid[i])).name
+ if int(MD.cam_bodyid[i]) == 0:
+ return {"type": "static", "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist()}
+ T = np.eye(4) # body -> camera (OpenGL axes), then to OpenCV axes
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.cam_quat[i])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.cam_pos[i]
+ return {"type": "link", "parent_link": body, "link_T_cam_cv": (T @ GL2CV).tolist()}
+
+
+def _mounted(cam: str) -> str:
+ if cam.startswith("handcam"):
+ side = "the right" if cam.endswith("_right") else "the left" if cam.endswith("_left") else "the"
+ return f"on {side} hand's mount (moves with the hand)"
+ return {"front": "static, across the table, facing the robot", "back": "static, behind the robot, looking over the table",
+ "left": "static, at the robot's left", "right": "static, at the robot's right",
+ "top0": "static, above the table, looking down"}.get(cam, "static")
+
+
+# ------------------------------------------------------------------------------------------------- kinematics
+KD = mujoco.MjData(MD) # kinematics only: never stepped; the robot's joints are set, everything else stays put
+ARM_QI = {a: [JOINTS.index(j) for j in ARM_JOINTS[a]] for a in ARMS}
+
+
+def _fk(q) -> None:
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR] = np.asarray(q, dtype=np.float64)
+ mujoco.mj_kinematics(MD, KD)
+
+
+def _link_pose(name: str) -> list:
+ for a in ARMS:
+ if name == TCP[a]:
+ s = TCP_SITE[a]
+ return [*KD.site_xpos[s].tolist(), *_quat(KD.site_xmat[s]).tolist()]
+ b = MD.body(name).id
+ return [*KD.xpos[b].tolist(), *KD.xquat[b].tolist()]
+
+
+def tcp_from_arm_joints(a: str, q7) -> np.ndarray:
+ """The tcp pose (xyz + wxyz) of arm `a` with its 7 joints at q7 (the joint_position action's tcp target)."""
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR[ARM_QI[a]]] = q7
+ mujoco.mj_kinematics(MD, KD)
+ s = TCP_SITE[a]
+ return np.concatenate([KD.site_xpos[s], _quat(KD.site_xmat[s])])
+
+
+def do_kinematics(req: dict) -> dict:
+ """World frame. FK: every link of spec kinematics.links for q. IK: per tcp target, damped least squares over that
+ arm's 7 joints (position and orientation), within the joint ranges; the hand joints are taken from the seed."""
+ if req["op"] == "fk":
+ _fk(req["q"])
+ return L.fk_response({n: _link_pose(n) for n in req["links"]}, "world")
+ q = np.array(req["seed"] if req["seed"] is not None else D.qpos[QADR], dtype=np.float64)
+ errors = {}
+ jp, jr = np.zeros((3, MD.nv)), np.zeros((3, MD.nv))
+ for frame, pose in req["targets"].items():
+ a = next(x for x in ARMS if TCP[x] == frame)
+ idx = ARM_QI[a]
+ dofs = VADR[idx]
+ tp, tq = np.asarray(pose[:3]), np.asarray(pose[3:7])
+ lo = np.array([JLIM[JOINTS[i]][0] for i in idx]); hi = np.array([JLIM[JOINTS[i]][1] for i in idx])
+ for _ in range(req["max_iters"]):
+ _fk(q)
+ mujoco.mj_comPos(MD, KD) # the Jacobian needs cdof, which mj_kinematics alone leaves stale
+ s = TCP_SITE[a]
+ ep = tp - KD.site_xpos[s]
+ cq = _quat(KD.site_xmat[s])
+ dq = np.zeros(4); neg = np.zeros(4); er = np.zeros(3)
+ mujoco.mju_negQuat(neg, cq); mujoco.mju_mulQuat(dq, tq, neg); mujoco.mju_quat2Vel(er, dq, 1.0)
+ if np.linalg.norm(ep) < req["tol_pos_m"] and np.linalg.norm(er) < req["tol_rot_rad"]:
+ break
+ mujoco.mj_jacSite(MD, KD, jp, jr, s)
+ J = np.vstack([jp[:, dofs], jr[:, dofs]])
+ err = np.concatenate([ep, er])
+ step = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), err)
+ q[idx] = np.clip(q[idx] + step, lo, hi)
+ _fk(q)
+ s = TCP_SITE[a]
+ errors[frame] = (float(np.linalg.norm(tp - KD.site_xpos[s])), L.quat_angle(_quat(KD.site_xmat[s]), tq / np.linalg.norm(tq)))
+ ok = all(e[0] <= req["tol_pos_m"] and e[1] <= req["tol_rot_rad"] for e in errors.values())
+ return L.ik_response(q, ok, errors, "world", note="the tcp (attachment_site) of each arm; the hand joints are the seed's")
+
+
+# ------------------------------------------------------------------------------------------------- spec
+def _joint_spec(a: str) -> list:
+ out = []
+ for j, ai in zip(ARM_JOINTS[a], ARM_CTRL[a]):
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_ctrlrange[ai][1]), "group": f"{a}_arm"})
+ for j, ai in zip(HAND_JOINTS[a], HAND_CTRL[a]):
+ fl = bool(MD.actuator_forcelimited[ai]) and float(MD.actuator_forcerange[ai][1]) > 0
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_forcerange[ai][1]) if fl else None, "group": f"{a}_hand"})
+ return out
+
+
+def _tcp_spec(a: str) -> dict:
+ s = TCP_SITE[a]
+ T = np.eye(4)
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.site_quat[s])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.site_pos[s]
+ return {"parent_link": MD.body(int(MD.site_bodyid[s])).name, "link_T_frame": T.tolist(),
+ "definition": "DexJoCo's attachment_site: the flange where the Allegro hand is mounted, the point its "
+ "operational-space controller drives to the ee_pose target (not the fingertips)"}
+
+
+def _base(a: str) -> list:
+ b = D.body(f"link0{SFX[a]}")
+ return [*np.round(b.xpos, 6).tolist(), *np.round(b.xquat, 6).tolist()]
+
+
+GAINS = {}
+for _a in ARMS:
+ for _j, _ai in zip(HAND_JOINTS[_a], HAND_CTRL[_a]):
+ GAINS[_j] = {"stiffness": float(MD.actuator_gainprm[_ai][0]), "damping": float(MD.dof_damping[MD.jnt_dofadr[MD.joint(_j).id]])}
+ROBOT_NAME = "franka-allegro-bimanual" if BIM else "franka-allegro"
+try:
+ TASK_TEXT = open(TASK_TEXT_FILE).read().strip()
+except OSError:
+ TASK_TEXT = f"DexJoCo {TASK}"
+SPEC = {
+ "protocol": L.PROTOCOL,
+ "protocol_compat": list(L.COMPAT),
+ "simulator": "DexJoCo @ 8d23b0f on MuJoCo 3.4.0 (CPU physics, OSMesa rendering)",
+ "robot": ROBOT_NAME,
+ "task_text": TASK_TEXT,
+ "control_hz": CTRL_HZ,
+ "physics_substeps": SUBSTEPS,
+ "physics_hz": CTRL_HZ * SUBSTEPS,
+ "max_chunk_s": MAX_CHUNK_S,
+ "max_watch_s": MAX_WATCH_S,
+ "cameras": {c: {"rgb": True, "depth": True, "mounted": _mounted(c), "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),
+ "mount": _mount(c)} for c in CAMS},
+ "default_cameras": DEFAULT_CAMS,
+ "action_types": {
+ "ee_pose": {
+ "dim": ADIM, "layout": EE_LAYOUT,
+ "units": "per arm (right first): tcp target position (m, world frame), tcp target orientation (quaternion wxyz), "
+ "16 Allegro joint targets (rad)",
+ "frame": "world", "quaternion_order": "wxyz", "ee_frames": [TCP[a] for a in ARMS],
+ "hand_limits": {j: ALIM[j] for a in ARMS for j in HAND_JOINTS[a]},
+ "semantics": "DexJoCo's own action row. The arm tracks the tcp target through DexJoCo's operational-space "
+ "controller (it lags a moving target and stops where contact blocks it); the hand joints are "
+ "position-controlled. Rows are `dt` apart (a whole multiple of 1/50 s, at most 0.5 s); between rows "
+ "positions and joints move linearly and orientations by slerp (`linear`) or jump (`hold`); a row's "
+ "own values land exactly on its last control step. Hand targets outside the ranges are clamped by "
+ "the simulator and reported in `clipped`; a zero quaternion is a 400.",
+ },
+ "joint_position": {
+ "dim": ADIM, "layout": JP_LAYOUT, "units": "rad", "limits": {j: ALIM[j] for j in JP_LAYOUT},
+ "semantics": "per arm (right first): 7 Panda joint targets, then the 16 Allegro joint targets. The arm's "
+ "targets are turned into a tcp target by forward kinematics (as POST /kinematics fk) and the arm "
+ "tracks that pose through the same operational-space controller as ee_pose, whose null space "
+ "pulls towards DexJoCo's home posture: the tcp reaches FK(q), the measured joints may differ from q "
+ "in the arm's redundant direction. Rows `dt` apart, `linear` (in joint space) or `hold`; values "
+ "outside the limits are clipped and reported.",
+ },
+ "not_yet": ["joint_delta", "joint_velocity", "ee_delta", "joint_torque"],
+ },
+ "proprio_layout": PROPRIO_LAYOUT,
+ "proprio_groups": PROPRIO_GROUPS,
+ "static": {},
+ "world": {"frame": "DexJoCo's world frame: z up, metres; the robot" + ("s stand" if BIM else " stands")
+ + " at low x and reach" + ("" if BIM else "es") + " towards +x"
+ + (" (right arm at y < 0, left arm at y > 0)" if BIM else ""),
+ "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},
+ "episode": "one episode, no reset: it ends at the first success, at a task failure (see task_text), or when your time is over",
+ "robot_spec": {
+ "name": ROBOT_NAME,
+ "description": ("two Franka Panda arms side by side, each with a 16-DoF Allegro hand (right arm first)" if BIM
+ else "a Franka Panda arm with a 16-DoF Allegro hand"),
+ "base": {"type": "fixed", "pose": _base(ARMS[0]), **({"per_arm": {a: _base(a) for a in ARMS}} if BIM else {}),
+ "note": "pose of the arm's base link (link0), world frame, x y z + quaternion wxyz"},
+ "joints": [j for a in ARMS for j in _joint_spec(a)],
+ "grippers": {},
+ "controller": {"type": "arm: operational-space control of the tcp (torques); hand: joint position actuators",
+ "control_hz": CTRL_HZ, "physics_hz": CTRL_HZ * SUBSTEPS, "gains": GAINS,
+ "note": "arm: DexJoCo's opspace controller drives attachment_site to the tcp target (position gains "
+ "400 N/m, damping ratio 4, gravity compensation, null space towards the home posture), "
+ "torques limited to effort_limit; hand: position actuators (stiffness N m/rad) on joints "
+ "with their own damping (N m s/rad)"},
+ "tcp": {TCP[a]: _tcp_spec(a) for a in ARMS},
+ },
+ "kinematics": {"endpoint": "/kinematics", "joint_names": JOINTS, "frame": "world", "quaternion_order": "wxyz",
+ "links": KIN_LINKS, "tcp_frames": [TCP[a] for a in ARMS], "ee_frames": [TCP[a] for a in ARMS],
+ "ik_targets": [TCP[a] for a in ARMS], "ik": {"tol_pos_m": 0.001, "tol_rot_rad": 0.01, "max_iters": 300},
+ "note": "the arm links, the hand mount (the hand cameras' parent) and the tcp, world frame; ik solves "
+ "each tcp target over that arm's 7 joints"},
+ "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()
+
+
+# ------------------------------------------------------------------------------------------------- state and frames
+def ctrl_steps() -> int:
+ return int(S.steps)
+
+
+def proprio_row() -> np.ndarray:
+ tcp, tgt, hand = [], [], []
+ for a in ARMS:
+ s = TCP_SITE[a]
+ tcp += [D.site_xpos[s], _quat(D.site_xmat[s])]
+ t = S._arm_target(a)
+ tgt.append(t[:7]); hand.append(t[7:23])
+ return np.concatenate([D.qpos[QADR], D.qvel[VADR], D.actuator_force[EFF_ACT], *tcp, *tgt, *hand]).astype(np.float32)
+
+
+def grab(cams, want_depth: bool):
+ rgb, dep = {}, {}
+ for c in cams:
+ rgb[c] = S.render_frame(c, (CAM_H, CAM_W))
+ if want_depth:
+ r = S._renderer # the one renderer (a second OSMesa context reads back garbage)
+ r.enable_depth_rendering()
+ try:
+ r.update_scene(D, camera=c)
+ dep[c] = r.render().astype(np.float32).copy()
+ finally:
+ r.disable_depth_rendering()
+ return rgb, dep
+
+
+def extrinsics(cams) -> dict:
+ return {c: _extrinsic(c) for c in cams}
+
+
+def summary() -> dict:
+ n = int(E.get("episode_control_steps") or ctrl_steps())
+ 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"],
+ "task": TASK, "protocol": L.PROTOCOL, "n_actions": len(ROWS), "task_failure": int(str(E["reason"] or "").startswith("failure")),
+ **EP.final_fields()}
+
+
+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 finish(reason: str) -> None:
+ """The episode is over: record the live verdict and dump the trajectory 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()
+ E["success"] = bool(S.success)
+ 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()
+ S.save_trajectory(np.asarray(ROWS, dtype=np.float64).reshape(-1, ADIM), os.path.join(DATA, "trajectory.npz"),
+ {"source": "standard-mode episode", "reason": E["reason"]})
+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})
+ write_final()
+
+
+def ctrl_step(a, rec) -> bool:
+ """One executed control step (DexJoCo's own row), journaled. True when the call must stop here."""
+ a = np.asarray(a, dtype=np.float64)
+ running = S.step(a)
+ ROWS.append(a.copy())
+ stop = EP.journal(a)
+ rec.tick()
+ if not running:
+ finish(S.reason or "done")
+ 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 DEFAULT_CAMS
+ if not isinstance(cams, list) or any(c not in CAMS for c in cams):
+ raise ValueError(f"unknown cameras {cams}; cameras: {CAMS}")
+ return list(dict.fromkeys(cams))
+
+
+def meta_common(cams) -> dict:
+ n = ctrl_steps()
+ return {"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}}
+
+
+def _native_from_ee(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ """ee_pose rows are executed as sent (the recorded row is what the agent commanded); hand targets outside the
+ actuator ranges are clamped by MuJoCo itself (ctrllimited) and only reported."""
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ if float(np.linalg.norm(row[o + 3:o + 7])) < 1e-6:
+ raise ValueError(f"row {ri}: the {a} tcp quaternion has zero norm")
+ for j in range(16):
+ lo, hi = HLIM[a][j]
+ v = row[o + 7 + j]
+ if v < lo or v > hi:
+ clipped.append({"row": ri, "index": int(o + 7 + j), "reason": f"{EE_LAYOUT[o + 7 + j]} outside [{lo:.3f}, {hi:.3f}]: clamped by the simulator"})
+ return row
+
+
+def _clip_joints(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ lo = np.array([ALIM[j][0] for j in JP_LAYOUT]); hi = np.array([ALIM[j][1] for j in JP_LAYOUT])
+ out = np.clip(row, lo, hi)
+ for j in np.flatnonzero(out != row)[:20]:
+ clipped.append({"row": ri, "index": int(j), "reason": f"{JP_LAYOUT[j]} limit [{lo[j]:g}, {hi[j]:g}]"})
+ return out
+
+
+def _native_from_joints(q: np.ndarray) -> np.ndarray:
+ out = []
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ out += [tcp_from_arm_joints(a, q[o:o + 7]), q[o + 7:o + 23]]
+ return np.concatenate(out)
+
+
+def _check_chunk(typ: str, A: np.ndarray, dt: float, interp: str, video: str) -> int:
+ k = dt / DT
+ if A.ndim != 2 or A.shape[1] != ADIM:
+ raise ValueError(f"{typ} actions must be (T, {ADIM}), got {list(A.shape)}")
+ if A.shape[0] == 0:
+ raise ValueError("no rows")
+ 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")
+ return int(round(k))
+
+
+def do_submit(meta: dict, A: np.ndarray):
+ typ = meta.get("type")
+ if typ not in ("ee_pose", "joint_position"):
+ raise ValueError(f"type must be ee_pose or joint_position (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)
+ n = _check_chunk(typ, A, dt, interp, video)
+ clipped: list = []
+ if typ == "ee_pose":
+ A = np.stack([_native_from_ee(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ else:
+ A = np.stack([_clip_joints(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ rec = recorder(cams, fps, meta)
+ E["calls"] += 1
+ step0, before = E["step"], ctrl_steps()
+ rec.tick(force=True)
+ if typ == "ee_pose":
+ prev = np.asarray(S.hold_action(), dtype=np.float64)
+ else:
+ prev = np.concatenate([np.concatenate([D.qpos[QADR[ARM_QI[a]]], S._arm_target(a)[7:23]]) for a in ARMS])
+ for row in A:
+ E["step"] += 1
+ stop = False
+ for s in range(1, n + 1):
+ if interp == "hold" or s == n:
+ target = row # a row's own values land exactly on its last control step
+ else:
+ target = prev + (row - prev) * (s / n)
+ if typ == "ee_pose":
+ for k in range(len(ARMS)):
+ o = 23 * k
+ target[o + 3:o + 7] = M.quat_slerp(prev[o + 3:o + 7], row[o + 3:o + 7], s / n)
+ native = target if typ == "ee_pose" else _native_from_joints(target)
+ if ctrl_step(native, rec):
+ stop = True
+ break
+ prev = row
+ 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"], "type": typ, "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 = np.asarray(S.hold_action(), dtype=np.float64)
+ 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={"task": TASK, "instance_sha": S.instance_sha, "instance_ok": bool(S.instance_exact), "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} DexJoCo sim ready ({TASK}; 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/dexjoco-bimanual-assembly-i00-standard/environment/sim/task_text.txt b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/sim/task_text.txt
new file mode 100644
index 0000000000..7eccac88ff
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-standard/environment/sim/task_text.txt
@@ -0,0 +1,3 @@
+Hold the tray with one hand and insert the round peg into its socket with the other. Success: the peg touches the socket's bottom for 30 consecutive control steps.
+
+The tray with a round socket and the 8 mm round peg lie on the table in front of the robots.
diff --git a/tasks/dexjoco-bimanual-assembly-i00-standard/instruction.md b/tasks/dexjoco-bimanual-assembly-i00-standard/instruction.md
new file mode 100644
index 0000000000..9b44890181
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-standard/instruction.md
@@ -0,0 +1,68 @@
+# DexJoCo · bimanual_assembly — STANDARD MODE (robot as a service, eai-standard/2.2)
+
+You control two Franka Panda arms, each with a 16-DoF Allegro hand, **as if it were real hardware**: the simulator runs in a service you cannot open. You get
+one client and one episode. **Task:** Hold the tray with one hand and insert the round peg into its socket with the other. Success: the peg touches the socket's bottom for 30 consecutive control steps.
+
+The tray with a round socket and the 8 mm round peg lie on the table in front of the robots.
+
+## Rules (real-robot rules)
+- **No reset.** The episode starts when the service comes up and ends on success, on a task failure (see the task), when
+ your time is up, or on a simulator error. Knocked-over objects stay knocked over.
+- **No privileged state.** You see what the cameras see (RGB, and depth on request, with each camera's calibration) plus
+ the robot's own proprioception (joints, tcp poses, the current targets). No object poses, no success check:
+ `meta["done"]` / `meta["reason"]` tell you when the episode is over and why.
+- Steps are unlimited; your wall-clock budget (90 minutes) is the limit (`meta["time_left_s"]`). Actions and
+ simulated time are reported as cost. Do not stop before the task is solved.
+- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
+ `/app/output/gen.py` for the record (save it early, update it as you go).
+- **Nothing is put into your context automatically.** Images and videos come back as arrays/bytes in a Python object;
+ what you look at and where you store it is your code's decision.
+
+## Client (`/opt/tools/rcb_client.py`, protocol `eai-standard/2.2`)
+```python
+from rcb_client import Robot
+r = Robot() # connects (waits while the service starts)
+spec = r.spec() # action types, cameras (+ calibration), proprio layout, robot_spec, kinematics, budget
+obs = r.get_obs() # current frames of spec["default_cameras"]: obs.last[cam] -> uint8 (480, 640, 3)
+obs = r.get_obs(cameras=["back", "handcam_rgb_right"], depth=True) # + obs.last_depth[cam] -> float32 (480, 640) z-depth (m)
+obs.meta["proprio"] # {"layout": [...], "now": [...]}; obs.group("tcp_pose", now=True)
+obs.meta["cameras"] # per camera intrinsic_cv / extrinsic_cv / cam2world_gl for these frames
+obs = r.get_obs(seconds=2.0, video="mp4") # hold the current targets and watch for 2 s (max 30): obs.video[cam] = mp4 bytes
+
+res = r.submit("ee_pose", rows, dt=0.1) # rows: (T, 46) targets dt seconds apart, executed at 50 Hz with interpolation
+res = r.submit("joint_position", q_rows, dt=0.1) # (T, 46) joint targets instead (see below)
+res.meta["done"], res.meta["reason"], res.meta["clipped"], res.meta["control_steps_chunk"]
+res.video["back"]; res.last["back"]; res.proprio # mp4 of the chunk, last frame, float32 (N, P) proprio per frame
+res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, proprio.npy, ...
+r.fk(q); r.ik({"tcp_right": pose}, seed=q) # kinematics of the robot (stateless: no physics, no time)
+r.status() # calls, control steps, done, reason, elapsed time
+```
+Cameras: `back` (static), `handcam_rgb_right`, `handcam_rgb_left` (on the hand mounts; they move,
+so use the calibration that comes with each response; `spec["cameras"][cam]["mount"]` gives the static pose or the mount
+link). Resolution 640x480. Rendering runs on the CPU: ask only for the cameras you need; `video="none"` makes a chunk
+fastest. If a call fails with a connection error the service may have crashed: it resumes the same episode;
+`r.wait_ready()`, then check `r.status()` (`spec["on_service_error"]`).
+
+### Action type `ee_pose` (46) — DexJoCo's own action
+Per arm, right first: tcp target position (3, metres, world frame), tcp target orientation (4, quaternion wxyz), 16
+Allegro joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+target and stops where contact blocks it); the hand joints are position-controlled. Rows are `dt` apart (a whole multiple
+of 1/50 s, at most 0.5 s); between rows positions and joints move linearly and orientations by slerp
+(`interpolate="linear"`) or jump (`"hold"`); a chunk may cover at most 10 s. Hand targets outside the ranges
+(`spec["action_types"]["ee_pose"]["hand_limits"]`) are clamped by the simulator and listed in `meta["clipped"]`. Build
+the next row from the `tcp_target` and `hand_target` proprio groups to move smoothly.
+
+### Action type `joint_position` (46)
+Per arm, right first: 7 Panda joint targets, then the 16 Allegro joint targets (rad). The service turns the arm's targets
+into a tcp target by forward kinematics and the same controller tracks it: the tcp reaches FK(q), but the measured arm
+joints may differ from q in the arm's redundant direction (the controller's null space pulls towards a home posture).
+Out-of-limit values are clipped and reported.
+
+## Conventions
+- World frame, metres, z up; the robots stand at low x and reach towards +x (right arm at y < 0, left arm at y > 0); each
+ arm's base pose is in `spec["robot_spec"]["base"]`. No other world coordinates are given (D7: the cameras are
+ calibrated, depth is available). Quaternions are **WXYZ**.
+- The tcp (`tcp_right`, `tcp_left`) is the hand's mounting flange (`spec["robot_spec"]["tcp"]`), not the fingertips. Allegro joint
+ order (right hand): index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger = spread, 1-3 = flexion
+ from the knuckle out; thumb 12 = opposition). The LEFT hand's 16 values are mirrored: ring 0-3, middle 4-7, index 8-11, thumb 12-15 (the joint names in `spec["proprio_layout"]` say which).
+- Control runs at 50 Hz (10 physics substeps of 2 ms). There is no step budget: your wall-clock time is the limit.
diff --git a/tasks/dexjoco-bimanual-assembly-i00-standard/solution/oracle_stream.py b/tasks/dexjoco-bimanual-assembly-i00-standard/solution/oracle_stream.py
new file mode 100644
index 0000000000..19877300c1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-standard/solution/oracle_stream.py
@@ -0,0 +1,43 @@
+"""Oracle (standard mode): streams the reference rows (the human demonstration's own actions, one per 1/50 s control step,
+float32-exact) as `ee_pose` 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
+
+A = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle_trajectory.npz"))["actions"].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(A), flush=True)
+t0, i = time.time(), 0
+while i < len(A):
+ chunk = A[i:i + per_chunk]
+ try:
+ res = r.submit("ee_pose", chunk, dt=dt, interpolate="hold", 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/dexjoco-bimanual-assembly-i00-standard/solution/oracle_trajectory.npz b/tasks/dexjoco-bimanual-assembly-i00-standard/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..1e77b98bbf
Binary files /dev/null and b/tasks/dexjoco-bimanual-assembly-i00-standard/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-bimanual-assembly-i00-standard/solution/solve.sh b/tasks/dexjoco-bimanual-assembly-i00-standard/solution/solve.sh
new file mode 100755
index 0000000000..1bd55d898f
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-standard/solution/solve.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+# Oracle (standard mode): streams the reference trajectory's rows (solution/oracle_trajectory.npz, one row per control
+# step) as `ee_pose` chunks through the client. Uses no privileged information at run time (only the pre-recorded rows);
+# the service's recorded trajectory is then exactly the privileged reference.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_stream.py /app/output/gen.py
+python /solution/oracle_stream.py
diff --git a/tasks/dexjoco-bimanual-assembly-i00-standard/task.toml b/tasks/dexjoco-bimanual-assembly-i00-standard/task.toml
new file mode 100644
index 0000000000..87e8b2d317
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-standard/task.toml
@@ -0,0 +1,52 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator 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/dexjoco-bimanual-assembly-i00-standard"
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): DexJoCo bimanual_assembly (two Franka Panda arms, each with a 16-DoF Allegro hand) on the same frozen instance as dexjoco-bimanual-assembly-i00-privileged. Hold the tray with one hand and insert the round peg into its socket with the other. The agent only gets a client: calibrated cameras (RGB, optional depth), the robot's joints and tcp poses, tcp-target + hand-joint chunks at 50 Hz, the robot's kinematics; one episode, no reset, no object state; the sim service records the episode, replays it in fresh processes and grades it."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "standard-mode", "robot-as-a-service", "bimanual_assembly"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro-bimanual"
+family = "bimanual_assembly"
+mode = "standard"
+protocol = "eai-standard/2.2"
+oracle = "full"
+expert_time_estimate_hours = 2.5
+
+[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 = 3600
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
diff --git a/tasks/dexjoco-bimanual-assembly-i00-standard/tests/Dockerfile b/tasks/dexjoco-bimanual-assembly-i00-standard/tests/Dockerfile
new file mode 100644
index 0000000000..26bc699ebe
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-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.sh
diff --git a/tasks/dexjoco-bimanual-assembly-i00-standard/tests/grade.py b/tasks/dexjoco-bimanual-assembly-i00-standard/tests/grade.py
new file mode 100644
index 0000000000..003b933315
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-standard/tests/grade.py
@@ -0,0 +1,60 @@
+"""Standard-mode verifier (DexJoCo): 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 frozen 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"))),
+ "task_failure": int(bool(d.get("task_failure"))),
+ "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),
+ "calls": int(d.get("calls") or 0),
+ "elapsed_s": float(d.get("elapsed_s") or 0),
+ "video_rendered": int(bool(d.get("video"))),
+ # 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 frozen 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/dexjoco-bimanual-assembly-i00-standard/tests/test.sh b/tasks/dexjoco-bimanual-assembly-i00-standard/tests/test.sh
new file mode 100755
index 0000000000..bc608aa8b9
--- /dev/null
+++ b/tasks/dexjoco-bimanual-assembly-i00-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
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-privileged/README.md b/tasks/dexjoco-bimanual-hanoi-i00-privileged/README.md
new file mode 100644
index 0000000000..bd60a12ae4
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-privileged/README.md
@@ -0,0 +1,49 @@
+# dexjoco-bimanual-hanoi-i00-privileged
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | privileged |
+| Twin | `dexjoco-bimanual-hanoi-i00-standard` |
+| Simulator / robot | `dexjoco` / `franka-allegro-bimanual` |
+| Family / instance | `bimanual_hanoi` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `bimanual_hanoi` (two Franka Panda arms, each with a 16-DoF Allegro hand): Tower of Hanoi with three disks on three vertical posts in a row along y: the small disk is on post A (y > 0, the left arm's side), the medium disk on post B (middle), the large disk on post C (y < 0). Build the full tower on post C: large at the bottom, then medium, then small, posts A and B empty, every disk at rest and seated on the post (horizontally within 4 cm of it, at its stacking height within 1.2 cm), held for 20 consecutive control steps. A larger disk resting on a smaller one, or a disk resting on the table, for 10 consecutive steps ends the episode as a failure.
+Privileged mode: the agent works in the simulator's container with live object poses, unlimited resets and thin motion
+primitives, and hands in one trajectory replayed open-loop from the frozen instance.
+
+## Difficulty
+First-pass rating: medium. Dexterous manipulation with two 16-DoF hands on two arms (46 action values per control step);
+the primitives only move tcp and hand-joint targets, so grasping, pressing and every other skill is the agent's. The
+reference (the human teleoperator's demonstration) takes 1085 control steps (21.7 s at 50 Hz).
+
+## Reference solution
+`solution/oracle_trajectory.npz` = the human demonstration's own actions, rounded to float32 (the standard client's
+precision; the rounded rows still succeed) and replayed from the frozen instance until the episode ends in success
+(1085 rows). The demonstration is public (DexJoCo-Datasets-Raw on Hugging Face), so agent egress is
+limited to the model APIs.
+
+## Verification
+Open-loop replay of `/app/output/trajectory.npz` from `tests/instance.npz`, twice in a fresh process in the verifier's own
+sandbox (no network); pass iff both episodes end in success, their final-state hashes agree and the rebuilt instance
+matches its recorded hash (`tests/grade.py`); plus `/logs/verifier/replay.mp4`. Oracle: success after 1085 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `hanoi_demo_10_2026-03-13_15-45-06_925668` (DexJoCo-Datasets-Raw), restored with DexJoCo's own state restorer; instance sha `93165d7fd0c8813c` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Tooling notes
+DexJoCo's reset samples object poses from the global RNG and its state restorer edits the MuJoCo model (table height,
+fixed bodies), so `instance.npz` stores the full physics state (`mjSTATE_INTEGRATION`), the mocap targets, the controls,
+every numeric model array a task can change, and the env's Python-side task state. Its per-step camera rendering,
+real-time sleep, episode cap and hanoi's wall-clock auto-reset are disabled in the tooling (`rcb_dexjoco.py`).
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py` from `scripts/dexjoco/instances/bimanual_hanoi/` (`make_instances.py`).
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-privileged/environment/Dockerfile b/tasks/dexjoco-bimanual-hanoi-i00-privileged/environment/Dockerfile
new file mode 100644
index 0000000000..d736fe8a7d
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-privileged/environment/Dockerfile
@@ -0,0 +1,7 @@
+# Base image = DexJoCo on MuJoCo 3.4.0 (images/dexjoco/). Everything task-specific is copied here. CPU only.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY instance.npz /app/instance.npz
+COPY rcb_dexjoco.py /opt/tools/rcb_dexjoco.py
+ENV PYTHONPATH=/opt/tools
+RUN mkdir -p /app/output
+WORKDIR /app
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-privileged/environment/instance.npz b/tasks/dexjoco-bimanual-hanoi-i00-privileged/environment/instance.npz
new file mode 100644
index 0000000000..0f1065cea8
Binary files /dev/null and b/tasks/dexjoco-bimanual-hanoi-i00-privileged/environment/instance.npz differ
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-privileged/environment/rcb_dexjoco.py b/tasks/dexjoco-bimanual-hanoi-i00-privileged/environment/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-privileged/environment/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-privileged/instruction.md b/tasks/dexjoco-bimanual-hanoi-i00-privileged/instruction.md
new file mode 100644
index 0000000000..7f61cdbbed
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-privileged/instruction.md
@@ -0,0 +1,142 @@
+# DexJoCo · bimanual_hanoi — frozen instance
+
+You control two Franka Panda arms, each with a 16-DoF Allegro hand (DexJoCo on MuJoCo 3.4) via Python. **Task:** Tower of Hanoi with three disks on three vertical posts in a row along y: the small disk is on post A (y > 0, the left arm's side), the medium disk on post B (middle), the large disk on post C (y < 0). Build the full tower on post C: large at the bottom, then medium, then small, posts A and B empty, every disk at rest and seated on the post (horizontally within 4 cm of it, at its stacking height within 1.2 cm), held for 20 consecutive control steps. A larger disk resting on a smaller one, or a disk resting on the table, for 10 consecutive steps ends the episode as a failure.
+
+Two arms with a hand each stand side by side facing the table (right arm at y < 0, left arm at y > 0); the wooden Hanoi base with its three posts is in front of them. Each disk has a hole and slides over a post. `s.objects()` gives the live poses of the task objects (`disk_small`, `disk_medium`, `disk_large`, `post_a`, `post_b`, `post_c`). DexJoCo's success code (from
+`/opt/dexjoco/dexjoco/dexjoco/sim/envs/panda_bimanual_hanoi_env.py`; `step()` ends the episode on success or on a task failure):
+```python
+def _compute_success_metrics(self) -> Tuple[bool, Dict[str, Any]]:
+ state = self._reconstruct_tower_state()
+ towers = state["towers"]
+ disk_assignment = state["disk_assignment"]
+ disk_positions = state["disk_positions"]
+ disk_static = state["disk_static"]
+ post_positions = state["post_positions"]
+ base_top_z = state["base_top_z"]
+
+ tower_state = self._tower_state_repr(towers)
+ all_disks_static = all(bool(v) for v in disk_static.values())
+
+ illegal_candidate = False
+ illegal_reason = ""
+
+ for post_name, disks in towers.items():
+ ranks = [self._disk_size_rank[disk] for disk in disks]
+ if any(ranks[i] < ranks[i + 1] for i in range(len(ranks) - 1)):
+ if all(disk_static[disk] for disk in disks):
+ xy_error, height_error = self._tower_geometry_errors(
+ disks, post_name, disk_positions, post_positions, base_top_z
+ )
+ if (
+ xy_error <= self._post_assignment_tol
+ and height_error <= self._placement_height_tol
+ ):
+ illegal_candidate = True
+ illegal_reason = f"illegal_stack_{post_name}"
+ break
+
+ if not illegal_candidate and all_disks_static:
+ on_table = [disk for disk, assign in disk_assignment.items() if assign == "table"]
+ if on_table:
+ illegal_candidate = True
+ illegal_reason = "disk_on_table"
+
+ if illegal_candidate:
+ if illegal_reason == self._illegal_trigger_reason:
+ self._illegal_trigger_count += 1
+ else:
+ self._illegal_trigger_reason = illegal_reason
+ self._illegal_trigger_count = 1
+ else:
+ self._illegal_trigger_reason = ""
+ self._illegal_trigger_count = 0
+
+ illegal_state = self._illegal_trigger_count >= self._illegal_trigger_target
+
+ xy_error_max = 0.0
+ height_error_max = 0.0
+ target_stack = ["hanoi_disk_large", "hanoi_disk_medium", "hanoi_disk_small"]
+
+ if towers["C"] == target_stack and len(towers["A"]) == 0 and len(towers["B"]) == 0:
+ xy_error_max, height_error_max = self._tower_geometry_errors(
+ target_stack, "C", disk_positions, post_positions, base_top_z
+ )
+ geom_success = (
+ xy_error_max <= self._post_assignment_tol
+ and height_error_max <= self._placement_height_tol
+ and all_disks_static
+ )
+ else:
+ geom_success = False
+
+ if geom_success and not illegal_state:
+ self._success_trigger_count += 1
+ else:
+ self._success_trigger_count = 0
+
+ success = self._success_trigger_count >= self._success_trigger_target
+
+ return bool(success), {
+ "tower_state": tower_state,
+ "disk_assignment": dict(disk_assignment),
+ "all_disks_static": bool(all_disks_static),
+ "illegal_state": bool(illegal_state),
+ "illegal_reason": illegal_reason,
+ "xy_error_max": float(xy_error_max),
+ "height_error_max": float(height_error_max),
+ }
+
+def _compute_success(self) -> bool:
+ success, _ = self._compute_success_metrics()
+ return bool(success)
+```
+
+This is a *fixed scene instance*: object poses, the table height and the robot's start pose never change between
+resets. You may reset and retry as many times as you want. Your deliverable is **one replayable trajectory**, not a
+general policy.
+
+## Deliverable
+Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
+open-loop from the same initial state in a fresh process and scored 1 if its episode ends in success, else 0. Also
+leave the script that produced it at `/app/output/gen.py`. You have 90 minutes of wall clock: save a
+first trajectory early, improve it, and do not stop before the task is solved.
+
+## Tooling (already installed; run `python` from any directory)
+```python
+from rcb_dexjoco import Session
+s = Session("bimanual_hanoi", instance="/app/instance.npz") # ~1 s: builds the env and loads the frozen state
+s.reset() # back to the frozen initial state (as often as you like; an exact snapshot restore)
+s.objects() # live task objects: name -> pos, quat_wxyz (bodies) / pos (sites) / qpos (joints)
+s.state() # DexJoCo's state dict: tcp_pose, gripper_pose (hand joints), INITIAL object poses, table height
+p = s.primitives() # thin wrappers of the low-level action; each has a docstring: help(p["move_ee"])
+p["move_ee"]("right", pos, quat_wxyz) # straight-line + slerp motion of an arm's tcp target, then settle
+p["set_hand"]("right", q16) # interpolate the 16 Allegro joint targets
+p["hold"](10); p["set_targets"](row, steps) # keep every target / send one raw action row
+p["get_ee_pose"]("right"); p["get_ee_target"]("right"); p["get_hand"]("right"); p["get_body_pose"](name)
+s.render_frame("front") # RGB uint8 (480, 640, 3); cameras: ['front', 'back', 'left', 'right', 'top0', 'handcam_rgb_right', 'handcam_rgb_left']; s.render_grid()
+s.step(action) # one control step (46 values, below) = 1/50 s; returns False once the episode is over
+s.record_start(); ...; actions = s.record_stop() # (T, 46) actions, one row per control step
+s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+s.replay(actions) # resets, replays open-loop until the episode ends, returns status -> self-check
+s.save_trajectory(actions, "/app/output/trajectory.npz")
+s.render_video(actions, "/app/output/check.mp4", cameras=["front"]) # replays from the frozen state into a video
+```
+The primitives are deliberately thin (tcp target moves, hand joint targets, hold): grasping, pressing, striking and
+every other skill are yours to build from them. `s.bodies()` lists every MuJoCo body for `p["get_body_pose"]`.
+
+CLI equivalent of the grader:
+`python /opt/tools/rcb_dexjoco.py replay --task bimanual_hanoi --instance /app/instance.npz --traj /app/output/trajectory.npz`
+
+## Conventions
+- World frame, metres; z up; the robots stand at low x and reach towards +x. The table top is at z = 0.942. Arm base (`link0`): link0_right [-0.75, -0.4, 0.924], link0_left [-0.75, 0.4, 0.924]. The right arm works at y < 0, the left arm at y > 0. Quaternions are **WXYZ**.
+- Action (46): per arm, right first: tcp target position (3), tcp target orientation (4, wxyz), 16 Allegro
+ joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+ target and stops where contact blocks it); the hand joints are position-controlled. `s.hold_action()` is the no-op.
+ At the start the tcp target is right [-0.443, -0.4, 1.517] / [0.0, -1.0, 0.0, -0.0025], left [-0.443, 0.4, 1.517] / [0.0, -1.0, 0.0, -0.0025].
+- Allegro joint order (right hand): index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger =
+ spread, 1-3 = flexion from the knuckle out; thumb 12 = opposition). The LEFT hand's 16 values are mirrored: ring 0-3, middle 4-7, index 8-11, thumb 12-15.
+ Target ranges (rad, same for every finger slot, thumb last): low [-0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, 0.26, -0.1, -0.19, -0.16], high [0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 1.4, 1.16, 1.64, 1.72]; the simulator clamps
+ targets to them.
+- Control runs at 50 Hz (10 physics substeps of 2 ms). DexJoCo's own episode cap and real-time pacing are lifted: there
+ is no step budget, your wall-clock time is the limit (~140 control steps/s here). An episode ends at the
+ first success or task failure; `s.step` then refuses further actions until `s.reset()`.
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-privileged/solution/gen.py b/tasks/dexjoco-bimanual-hanoi-i00-privileged/solution/gen.py
new file mode 100644
index 0000000000..0e1f7e3bc7
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-privileged/solution/gen.py
@@ -0,0 +1,4 @@
+# How solution/oracle_trajectory.npz was made (scripts/dexjoco/make_instances.py): the DexJoCo human demonstration's
+# own actions (replay.zarr data/action), rounded to float32, replayed from the frozen instance with Session.replay until
+# the episode ended in success (holding the last row a few steps where the rounded rows ended short of a hold count),
+# truncated there and saved with Session.save_trajectory.
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-privileged/solution/oracle_trajectory.npz b/tasks/dexjoco-bimanual-hanoi-i00-privileged/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..7195531771
Binary files /dev/null and b/tasks/dexjoco-bimanual-hanoi-i00-privileged/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-privileged/solution/solve.sh b/tasks/dexjoco-bimanual-hanoi-i00-privileged/solution/solve.sh
new file mode 100755
index 0000000000..7909c90cb8
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-privileged/solution/solve.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+# Reference solution: the human demonstration's actions (float32), replayed through the task tooling until success.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_trajectory.npz /app/output/trajectory.npz
+cp /solution/gen.py /app/output/gen.py
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-privileged/task.toml b/tasks/dexjoco-bimanual-hanoi-i00-privileged/task.toml
new file mode 100644
index 0000000000..f7c2fe6eff
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-privileged/task.toml
@@ -0,0 +1,37 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator or the instance, not this.
+schema_version = "1.3"
+artifacts = ["/app/output/"]
+
+[task]
+name = "robot-coding-bench/dexjoco-bimanual-hanoi-i00-privileged"
+description = "DexJoCo bimanual_hanoi (two Franka Panda arms, each with a 16-DoF Allegro hand, MuJoCo): produce one replayable trajectory. Tower of Hanoi with three disks on three vertical posts in a row along y: the small disk is on post A (y > 0, the left arm's side), the medium disk on post B (middle), the large disk on post C (y < 0). Frozen scene instance (the initial state of a DexJoCo human demonstration)."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "code-as-policy", "trajectory", "bimanual_hanoi"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro-bimanual"
+family = "bimanual_hanoi"
+mode = "privileged"
+oracle = "full"
+expert_time_estimate_hours = 2.0
+
+[verifier]
+timeout_sec = 1800.0
+environment_mode = "separate" # the verifier runs in its own sandbox (tests/Dockerfile); the agent container is gone by then
+network_mode = "no-network"
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
+
+[verifier.environment]
+build_timeout_sec = 1800.0
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-privileged/tests/Dockerfile b/tasks/dexjoco-bimanual-hanoi-i00-privileged/tests/Dockerfile
new file mode 100644
index 0000000000..a2620a4da8
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-privileged/tests/Dockerfile
@@ -0,0 +1,8 @@
+# Separate verifier sandbox (PROTOCOL §2.6): the same simulator image with the verifier's own copies of the tooling and
+# the frozen instance baked in. Nothing the agent did in its container reaches this one: Harbor uploads only the declared
+# artifacts (/app/output/), so a patched success check in the agent container cannot count.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY grade.py instance.npz rcb_dexjoco.py test.sh /tests/
+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
+ENV PYTHONPATH=/tests
+WORKDIR /tests
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-privileged/tests/grade.py b/tasks/dexjoco-bimanual-hanoi-i00-privileged/tests/grade.py
new file mode 100644
index 0000000000..ad916e8bb9
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-privileged/tests/grade.py
@@ -0,0 +1,109 @@
+"""Verifier entry point for the privileged DexJoCo tasks: replay /app/output/trajectory.npz from the frozen instance and
+write Harbor rewards.
+
+ python /tests/grade.py --family water_plant --instance /tests/instance.npz --traj /app/output/trajectory.npz
+
+Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only; Harbor rejects strings), a replay video
+/logs/verifier/replay.mp4 (front camera + wrist camera) and replay.last.png. Replays `--repeat` times in this fresh
+process; success requires every replay to end its episode in success (DexJoCo's own rule: the episode ends at the first
+success or task failure) AND all final-state hashes to agree (MuJoCo on the CPU is bit-deterministic), and the frozen
+instance rebuilt here from tests/instance.npz must match its recorded hash.
+"""
+from __future__ import annotations
+import argparse, json, os, sys, time, traceback
+import numpy as np
+
+LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")
+
+
+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 self_reported_cost() -> dict:
+ # From the tooling's append-only log in the agent's container: SELF-REPORTED accounting, never evidence.
+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_records": 0, "agent_replays": 0,
+ "agent_cost_self_reported": 1}
+ try:
+ with open("/app/output/rcb_session_log.jsonl") 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 == "session_end": cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)
+ elif ev == "record": cost["agent_records"] += 1
+ elif ev == "replay": cost["agent_replays"] += 1
+ except Exception: # noqa: BLE001 — one bad line must not sink the verdict
+ continue
+ except Exception: # noqa: BLE001
+ pass
+ return cost
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--family", required=True); ap.add_argument("--instance", required=True)
+ ap.add_argument("--traj", default="/app/output/trajectory.npz"); ap.add_argument("--repeat", type=int, default=2)
+ ap.add_argument("--no-video", action="store_true")
+ a = ap.parse_args()
+ cost = self_reported_cost()
+ os.environ["RCB_SESSION_LOG"] = "" # the verifier's own sessions are not the agent's cost
+ if not os.path.isfile(a.traj):
+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost}); return 0
+ s = None
+ try:
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the verifier's own copy of the tooling
+ import rcb_dexjoco
+ rcb_dexjoco.SESSION_LOG = ""
+ from rcb_dexjoco import Session, MAX_STEPS
+ d = np.load(a.traj, allow_pickle=False)
+ if str(d["task"]) != a.family:
+ write(False, {"success": 0, "wrong_family": 1, "grader_error": 0, **cost}); return 0
+ acts = np.asarray(d["actions"], dtype=np.float64)
+ s = Session(a.family, instance=a.instance)
+ if (acts.ndim != 2 or acts.shape[1] != s.action_dim or acts.shape[0] > MAX_STEPS
+ or not np.all(np.isfinite(acts))):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0,
+ "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0, **cost}); return 0
+ t0 = time.time()
+ outs = []
+ for _ in range(a.repeat):
+ try:
+ outs.append(s.replay(acts))
+ except (ValueError, rcb_dexjoco.PrimitiveError):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0, "n_actions": int(len(acts)), **cost}); return 0
+ all_success = all(o["success"] for o in outs)
+ deterministic = len({o["state_sha"] for o in outs}) == 1
+ instance_ok = bool(s.instance_exact)
+ ok = all_success and deterministic and instance_ok
+ out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
+ "instance_ok": int(instance_ok), "n_actions": int(len(acts)), "sim_steps": int(outs[0]["steps"]),
+ "task_failure": int(bool(outs[0]["reason"]) and not outs[0]["success"]),
+ "replay_wall_s": round(time.time() - t0, 1), "grader_error": 0, "video_rendered": 0, **cost}
+ if not a.no_video: # human-viewable replay (never affects the verdict)
+ try:
+ n = int(outs[0]["replayed_rows"])
+ s.render_video(acts[:n], os.path.join(LOG_DIR, "replay.mp4"), cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ import imageio.v2 as imageio
+ imageio.imwrite(os.path.join(LOG_DIR, "replay.last.png"), s.render_frame(s.default_camera(), (480, 640)))
+ out["video_rendered"] = int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4")))
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(ok, out)
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(False, {"success": 0, "grader_error": 1, **cost})
+ finally:
+ if s is not None:
+ s.close()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-privileged/tests/instance.npz b/tasks/dexjoco-bimanual-hanoi-i00-privileged/tests/instance.npz
new file mode 100644
index 0000000000..0f1065cea8
Binary files /dev/null and b/tasks/dexjoco-bimanual-hanoi-i00-privileged/tests/instance.npz differ
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-privileged/tests/rcb_dexjoco.py b/tasks/dexjoco-bimanual-hanoi-i00-privileged/tests/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-privileged/tests/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-privileged/tests/test.sh b/tasks/dexjoco-bimanual-hanoi-i00-privileged/tests/test.sh
new file mode 100755
index 0000000000..24a4109eee
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-privileged/tests/test.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in a fresh process.
+# 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/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)
+mkdir -p /logs/verifier
+python /tests/grade.py --family bimanual_hanoi --instance /tests/instance.npz --traj /app/output/trajectory.npz --repeat 2 \
+ 2> /logs/verifier/grade.log
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-standard/README.md b/tasks/dexjoco-bimanual-hanoi-i00-standard/README.md
new file mode 100644
index 0000000000..8196acb0cb
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-standard/README.md
@@ -0,0 +1,45 @@
+# dexjoco-bimanual-hanoi-i00-standard
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | standard (`eai-standard/2.2`) |
+| Twin | `dexjoco-bimanual-hanoi-i00-privileged` |
+| Simulator / robot | `dexjoco` / `franka-allegro-bimanual` |
+| Family / instance | `bimanual_hanoi` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `bimanual_hanoi` (two Franka Panda arms, each with a 16-DoF Allegro hand) on the same frozen instance as `dexjoco-bimanual-hanoi-i00-privileged`: Tower of Hanoi with three disks on three vertical posts in a row along y: the small disk is on post A (y > 0, the left arm's side), the medium disk on post B (middle), the large disk on post C (y < 0). Build the full tower on post C: large at the bottom, then medium, then small, posts A and B empty, every disk at rest and seated on the post (horizontally within 4 cm of it, at its stacking height within 1.2 cm), held for 20 consecutive control steps. A larger disk resting on a smaller one, or a disk resting on the table, for 10 consecutive steps ends the episode as a failure.
+Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with the robot's own
+sensors, calibrated cameras (RGB, optional depth) and the robot's kinematics.
+
+## Difficulty
+Same instance and success check as `dexjoco-bimanual-hanoi-i00-privileged`. In standard mode the agent loses resets, the
+simulator and the object poses: it sees camera images and proprioception, acts in chunks of tcp-target + hand-joint rows
+(or joint targets), and gets one episode, so it has to close the loop on what the cameras show and recover from its own
+mistakes without starting over.
+
+## Reference solution
+`solution/oracle_stream.py` streams the privileged reference's rows (`solution/oracle_trajectory.npz`, 1085 rows, float32-exact)
+through the client as `ee_pose` 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 1085 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 1085 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `hanoi_demo_10_2026-03-13_15-45-06_925668` (DexJoCo-Datasets-Raw); instance sha `93165d7fd0c8813c` |
+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); action types `ee_pose` and `joint_position`; cameras `front`, `back`, `left`, `right`, `top0`, `handcam_rgb_right`, `handcam_rgb_left` (640 x 480); `/kinematics` for the arm links, the hand mount and the tcp; crash recovery class `exact` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py`, as its privileged twin.
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/Dockerfile b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/Dockerfile
new file mode 100644
index 0000000000..a778c94561
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/Dockerfile
@@ -0,0 +1,9 @@
+# Standard mode: the agent container has NO simulator and no DexJoCo 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 /app
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/client-requirements.txt b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/client-requirements.txt
new file mode 100644
index 0000000000..8aa73a968f
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-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.0
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/docker-compose.yaml b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/docker-compose.yaml
new file mode 100644
index 0000000000..1a4a878a8e
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/docker-compose.yaml
@@ -0,0 +1,24 @@
+# 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 OSMesa rendering; 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-dexjoco:0.1.2
+ 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_TASK: bimanual_hanoi
+ RCB_INSTANCE: /srv/instance.npz
+ RCB_TOOL: /srv/rcb_dexjoco.py
+ RCB_DATA: /data
+ RCB_WALL_CLOCK_S: "5400"
+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in a few seconds
+ PYTHONPATH: /srv
+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction log
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/rcb1.py b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-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/dexjoco-bimanual-hanoi-i00-standard/environment/rcb_client.py b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/rcb_client.py
new file mode 100644
index 0000000000..aa25b0e050
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-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/dexjoco-bimanual-hanoi-i00-standard/environment/sim/finalize.sh b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/sim/finalize.sh
new file mode 100755
index 0000000000..e0cf248720
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-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_dexjoco.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:?}"; TASK="${RCB_TASK:?}"
+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 --task "$TASK" --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --repeat 1 \
+ --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"))
+PY
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/sim/instance.npz b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/sim/instance.npz
new file mode 100644
index 0000000000..0f1065cea8
Binary files /dev/null and b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/sim/instance.npz differ
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/sim/rcb1.py b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/sim/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-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/dexjoco-bimanual-hanoi-i00-standard/environment/sim/rcb_dexjoco.py b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/sim/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/sim/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/sim/rcb_limited.py b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/sim/rcb_limited.py
new file mode 100644
index 0000000000..1ce1171787
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-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/dexjoco-bimanual-hanoi-i00-standard/environment/sim/run.sh b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/sim/run.sh
new file mode 100755
index 0000000000..49d4d045d4
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-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; done
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/sim/server.py b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/sim/server.py
new file mode 100644
index 0000000000..ca5b61fc5c
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/sim/server.py
@@ -0,0 +1,625 @@
+"""eai-standard/2.2 sim service for DexJoCo (docs/STANDARD_MODE_2_2.md): the adapter of the shared layer rcb_limited.py;
+the simulator is rcb_dexjoco.Session (DexJoCo on MuJoCo 3.4, CPU physics, OSMesa rendering).
+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to
+/data/episode.jsonl.
+
+The robot is a Franka Panda with a 16-DoF Allegro hand, or two of them side by side (right arm first). One control step
+= 1/50 s (10 physics substeps of 2 ms). Two action types:
+ ee_pose DexJoCo's own row, per arm: the tcp target pose (xyz m, quaternion wxyz, world frame) that its
+ operational-space controller tracks + 16 Allegro joint targets (rad);
+ joint_position per arm: 7 arm joint targets + 16 Allegro joint targets; the arm's targets are turned into a tcp target
+ by forward kinematics (the controller tracks the tcp pose, not the joints).
+Either way, the executed (journaled, recorded) row is DexJoCo's own row, so the recorded trajectory replays in the
+privileged tooling unchanged. As in DexJoCo's evaluation the episode ends at the first success or task failure;
+otherwise when the agent's time is over (the collect hook's SIGUSR1).
+
+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 instance 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")
+TASK = os.environ.get("RCB_TASK", "water_plant")
+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.npz"))
+TASK_TEXT_FILE = os.environ.get("RCB_TASK_TEXT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "task_text.txt"))
+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "5400"))
+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 = 640, 480
+CTRL_HZ = 50.0
+DT = 1.0 / CTRL_HZ
+SUBSTEPS = 10
+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"] = "" # the sidecar's Session is not the agent's interaction log
+import rcb_dexjoco as M # noqa: E402
+import mujoco # noqa: E402
+
+M.SESSION_LOG = ""
+BIM = TASK.startswith("bimanual_")
+ADIM = 46 if BIM else 23
+EP = L.Episode(DATA, dim=ADIM, resume="exact")
+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()
+S = M.Session(TASK, instance=INSTANCE, image_size=(CAM_H, CAM_W))
+MD, D = S.model, S.data
+ARMS = S.arms()
+SFX = {a: (f"_{a}" if BIM else "") for a in ARMS}
+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz
+
+# ------------------------------------------------------------------------------------------------- the robot
+ARM_JOINTS = {a: [f"joint{i}{SFX[a]}" for i in range(1, 8)] for a in ARMS}
+HAND_CTRL = {a: np.asarray(S._hand_ctrl_ids(a)) for a in ARMS}
+HAND_JOINTS = {a: [MD.joint(int(MD.actuator_trnid[i, 0])).name for i in HAND_CTRL[a]] for a in ARMS} # action order
+ARM_CTRL = {a: [MD.actuator(f"actuator{i}{SFX[a]}").id for i in range(1, 8)] for a in ARMS}
+JOINTS = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]] # kinematics q = proprio joint_pos columns
+QADR = np.array([MD.jnt_qposadr[MD.joint(j).id] for j in JOINTS])
+VADR = np.array([MD.jnt_dofadr[MD.joint(j).id] for j in JOINTS])
+EFF_ACT = np.array([i for a in ARMS for i in list(ARM_CTRL[a]) + list(HAND_CTRL[a])])
+TCP_SITE = {a: MD.site(f"attachment_site{SFX[a]}").id for a in ARMS}
+TCP = {a: f"tcp{SFX[a]}" for a in ARMS}
+MOUNT_BODY = {a: f"attachment{SFX[a]}" for a in ARMS}
+LINKS = {a: [f"link{i}{SFX[a]}" for i in range(0, 8) if mujoco.mj_name2id(MD, mujoco.mjtObj.mjOBJ_BODY, f"link{i}{SFX[a]}") >= 0]
+ + [MOUNT_BODY[a]] for a in ARMS}
+KIN_LINKS = [n for a in ARMS for n in LINKS[a] + [TCP[a]]]
+JLIM = {j: MD.jnt_range[MD.joint(j).id].astype(float).tolist() for j in JOINTS}
+HLIM = {a: S.hand_limits(a) for a in ARMS} # actuator ctrlrange, action order
+ALIM = {} # joint_position limits (inside the joint ranges)
+for a in ARMS:
+ for j in ARM_JOINTS[a]:
+ ALIM[j] = JLIM[j]
+ for j, (lo, hi) in zip(HAND_JOINTS[a], HLIM[a]):
+ ALIM[j] = [max(float(lo), JLIM[j][0]), min(float(hi), JLIM[j][1])]
+POSE = ["x", "y", "z", "qw", "qx", "qy", "qz"]
+EE_LAYOUT = [] # per arm, right first
+for a in ARMS:
+ EE_LAYOUT += [f"{TCP[a]}_target_{k}" for k in POSE] + [f"{j}_target" for j in HAND_JOINTS[a]]
+JP_LAYOUT = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]]
+
+GROUPS = [
+ ("joint_pos", JOINTS, "measured joint positions (rad): per arm (right first) the 7 Panda joints, then the 16 Allegro "
+ "joints in the action's order"),
+ ("joint_vel", [f"{j}_vel" for j in JOINTS], "measured joint velocities (rad/s)"),
+ ("joint_effort", [f"{j}_effort" for j in JOINTS], "actuator efforts (N m): the arm's operational-space torques and the "
+ "hand's position-actuator forces"),
+ ("gripper_opening", [], "none: a 16-DoF Allegro hand, its finger joints are in joint_pos"),
+ ("tcp_pose", [f"{TCP[a]}_{k}" for a in ARMS for k in POSE], "measured tcp pose per arm (x y z m, quaternion wxyz, world)"),
+ ("tcp_target", [f"{TCP[a]}_target_{k}" for a in ARMS for k in POSE], "the tcp target the controller tracks now (the "
+ "ee_pose part of the last executed row)"),
+ ("hand_target", [f"{j}_target" for a in ARMS for j in HAND_JOINTS[a]], "the Allegro joint targets now (rad)"),
+]
+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)
+
+
+def _quat(xmat) -> np.ndarray:
+ q = np.zeros(4)
+ mujoco.mju_mat2Quat(q, np.asarray(xmat, dtype=np.float64).reshape(9))
+ return q
+
+
+# ------------------------------------------------------------------------------------------------- cameras
+CAMS = S.cameras()
+HAND_CAMS = [c for c in CAMS if c.startswith("handcam")]
+DEFAULT_CAMS = [S.default_camera()]
+GL2CV = np.diag([1.0, -1.0, -1.0, 1.0])
+
+
+def _intrinsic(cam: str) -> list:
+ fovy = math.radians(float(MD.cam_fovy[MD.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 _cam2world_gl(cam: str) -> np.ndarray:
+ i = MD.camera(cam).id
+ T = np.eye(4)
+ T[:3, :3] = D.cam_xmat[i].reshape(3, 3) # MuJoCo camera axes: OpenGL (x right, y up, z back)
+ T[:3, 3] = D.cam_xpos[i]
+ return T
+
+
+def _extrinsic(cam: str) -> np.ndarray:
+ return np.linalg.inv(_cam2world_gl(cam) @ GL2CV)[:3, :]
+
+
+def camera_info(cam: str) -> dict:
+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist(),
+ "image_size": [CAM_W, CAM_H]}
+
+
+def _mount(cam: str) -> dict:
+ i = MD.camera(cam).id
+ body = MD.body(int(MD.cam_bodyid[i])).name
+ if int(MD.cam_bodyid[i]) == 0:
+ return {"type": "static", "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist()}
+ T = np.eye(4) # body -> camera (OpenGL axes), then to OpenCV axes
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.cam_quat[i])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.cam_pos[i]
+ return {"type": "link", "parent_link": body, "link_T_cam_cv": (T @ GL2CV).tolist()}
+
+
+def _mounted(cam: str) -> str:
+ if cam.startswith("handcam"):
+ side = "the right" if cam.endswith("_right") else "the left" if cam.endswith("_left") else "the"
+ return f"on {side} hand's mount (moves with the hand)"
+ return {"front": "static, across the table, facing the robot", "back": "static, behind the robot, looking over the table",
+ "left": "static, at the robot's left", "right": "static, at the robot's right",
+ "top0": "static, above the table, looking down"}.get(cam, "static")
+
+
+# ------------------------------------------------------------------------------------------------- kinematics
+KD = mujoco.MjData(MD) # kinematics only: never stepped; the robot's joints are set, everything else stays put
+ARM_QI = {a: [JOINTS.index(j) for j in ARM_JOINTS[a]] for a in ARMS}
+
+
+def _fk(q) -> None:
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR] = np.asarray(q, dtype=np.float64)
+ mujoco.mj_kinematics(MD, KD)
+
+
+def _link_pose(name: str) -> list:
+ for a in ARMS:
+ if name == TCP[a]:
+ s = TCP_SITE[a]
+ return [*KD.site_xpos[s].tolist(), *_quat(KD.site_xmat[s]).tolist()]
+ b = MD.body(name).id
+ return [*KD.xpos[b].tolist(), *KD.xquat[b].tolist()]
+
+
+def tcp_from_arm_joints(a: str, q7) -> np.ndarray:
+ """The tcp pose (xyz + wxyz) of arm `a` with its 7 joints at q7 (the joint_position action's tcp target)."""
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR[ARM_QI[a]]] = q7
+ mujoco.mj_kinematics(MD, KD)
+ s = TCP_SITE[a]
+ return np.concatenate([KD.site_xpos[s], _quat(KD.site_xmat[s])])
+
+
+def do_kinematics(req: dict) -> dict:
+ """World frame. FK: every link of spec kinematics.links for q. IK: per tcp target, damped least squares over that
+ arm's 7 joints (position and orientation), within the joint ranges; the hand joints are taken from the seed."""
+ if req["op"] == "fk":
+ _fk(req["q"])
+ return L.fk_response({n: _link_pose(n) for n in req["links"]}, "world")
+ q = np.array(req["seed"] if req["seed"] is not None else D.qpos[QADR], dtype=np.float64)
+ errors = {}
+ jp, jr = np.zeros((3, MD.nv)), np.zeros((3, MD.nv))
+ for frame, pose in req["targets"].items():
+ a = next(x for x in ARMS if TCP[x] == frame)
+ idx = ARM_QI[a]
+ dofs = VADR[idx]
+ tp, tq = np.asarray(pose[:3]), np.asarray(pose[3:7])
+ lo = np.array([JLIM[JOINTS[i]][0] for i in idx]); hi = np.array([JLIM[JOINTS[i]][1] for i in idx])
+ for _ in range(req["max_iters"]):
+ _fk(q)
+ mujoco.mj_comPos(MD, KD) # the Jacobian needs cdof, which mj_kinematics alone leaves stale
+ s = TCP_SITE[a]
+ ep = tp - KD.site_xpos[s]
+ cq = _quat(KD.site_xmat[s])
+ dq = np.zeros(4); neg = np.zeros(4); er = np.zeros(3)
+ mujoco.mju_negQuat(neg, cq); mujoco.mju_mulQuat(dq, tq, neg); mujoco.mju_quat2Vel(er, dq, 1.0)
+ if np.linalg.norm(ep) < req["tol_pos_m"] and np.linalg.norm(er) < req["tol_rot_rad"]:
+ break
+ mujoco.mj_jacSite(MD, KD, jp, jr, s)
+ J = np.vstack([jp[:, dofs], jr[:, dofs]])
+ err = np.concatenate([ep, er])
+ step = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), err)
+ q[idx] = np.clip(q[idx] + step, lo, hi)
+ _fk(q)
+ s = TCP_SITE[a]
+ errors[frame] = (float(np.linalg.norm(tp - KD.site_xpos[s])), L.quat_angle(_quat(KD.site_xmat[s]), tq / np.linalg.norm(tq)))
+ ok = all(e[0] <= req["tol_pos_m"] and e[1] <= req["tol_rot_rad"] for e in errors.values())
+ return L.ik_response(q, ok, errors, "world", note="the tcp (attachment_site) of each arm; the hand joints are the seed's")
+
+
+# ------------------------------------------------------------------------------------------------- spec
+def _joint_spec(a: str) -> list:
+ out = []
+ for j, ai in zip(ARM_JOINTS[a], ARM_CTRL[a]):
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_ctrlrange[ai][1]), "group": f"{a}_arm"})
+ for j, ai in zip(HAND_JOINTS[a], HAND_CTRL[a]):
+ fl = bool(MD.actuator_forcelimited[ai]) and float(MD.actuator_forcerange[ai][1]) > 0
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_forcerange[ai][1]) if fl else None, "group": f"{a}_hand"})
+ return out
+
+
+def _tcp_spec(a: str) -> dict:
+ s = TCP_SITE[a]
+ T = np.eye(4)
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.site_quat[s])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.site_pos[s]
+ return {"parent_link": MD.body(int(MD.site_bodyid[s])).name, "link_T_frame": T.tolist(),
+ "definition": "DexJoCo's attachment_site: the flange where the Allegro hand is mounted, the point its "
+ "operational-space controller drives to the ee_pose target (not the fingertips)"}
+
+
+def _base(a: str) -> list:
+ b = D.body(f"link0{SFX[a]}")
+ return [*np.round(b.xpos, 6).tolist(), *np.round(b.xquat, 6).tolist()]
+
+
+GAINS = {}
+for _a in ARMS:
+ for _j, _ai in zip(HAND_JOINTS[_a], HAND_CTRL[_a]):
+ GAINS[_j] = {"stiffness": float(MD.actuator_gainprm[_ai][0]), "damping": float(MD.dof_damping[MD.jnt_dofadr[MD.joint(_j).id]])}
+ROBOT_NAME = "franka-allegro-bimanual" if BIM else "franka-allegro"
+try:
+ TASK_TEXT = open(TASK_TEXT_FILE).read().strip()
+except OSError:
+ TASK_TEXT = f"DexJoCo {TASK}"
+SPEC = {
+ "protocol": L.PROTOCOL,
+ "protocol_compat": list(L.COMPAT),
+ "simulator": "DexJoCo @ 8d23b0f on MuJoCo 3.4.0 (CPU physics, OSMesa rendering)",
+ "robot": ROBOT_NAME,
+ "task_text": TASK_TEXT,
+ "control_hz": CTRL_HZ,
+ "physics_substeps": SUBSTEPS,
+ "physics_hz": CTRL_HZ * SUBSTEPS,
+ "max_chunk_s": MAX_CHUNK_S,
+ "max_watch_s": MAX_WATCH_S,
+ "cameras": {c: {"rgb": True, "depth": True, "mounted": _mounted(c), "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),
+ "mount": _mount(c)} for c in CAMS},
+ "default_cameras": DEFAULT_CAMS,
+ "action_types": {
+ "ee_pose": {
+ "dim": ADIM, "layout": EE_LAYOUT,
+ "units": "per arm (right first): tcp target position (m, world frame), tcp target orientation (quaternion wxyz), "
+ "16 Allegro joint targets (rad)",
+ "frame": "world", "quaternion_order": "wxyz", "ee_frames": [TCP[a] for a in ARMS],
+ "hand_limits": {j: ALIM[j] for a in ARMS for j in HAND_JOINTS[a]},
+ "semantics": "DexJoCo's own action row. The arm tracks the tcp target through DexJoCo's operational-space "
+ "controller (it lags a moving target and stops where contact blocks it); the hand joints are "
+ "position-controlled. Rows are `dt` apart (a whole multiple of 1/50 s, at most 0.5 s); between rows "
+ "positions and joints move linearly and orientations by slerp (`linear`) or jump (`hold`); a row's "
+ "own values land exactly on its last control step. Hand targets outside the ranges are clamped by "
+ "the simulator and reported in `clipped`; a zero quaternion is a 400.",
+ },
+ "joint_position": {
+ "dim": ADIM, "layout": JP_LAYOUT, "units": "rad", "limits": {j: ALIM[j] for j in JP_LAYOUT},
+ "semantics": "per arm (right first): 7 Panda joint targets, then the 16 Allegro joint targets. The arm's "
+ "targets are turned into a tcp target by forward kinematics (as POST /kinematics fk) and the arm "
+ "tracks that pose through the same operational-space controller as ee_pose, whose null space "
+ "pulls towards DexJoCo's home posture: the tcp reaches FK(q), the measured joints may differ from q "
+ "in the arm's redundant direction. Rows `dt` apart, `linear` (in joint space) or `hold`; values "
+ "outside the limits are clipped and reported.",
+ },
+ "not_yet": ["joint_delta", "joint_velocity", "ee_delta", "joint_torque"],
+ },
+ "proprio_layout": PROPRIO_LAYOUT,
+ "proprio_groups": PROPRIO_GROUPS,
+ "static": {},
+ "world": {"frame": "DexJoCo's world frame: z up, metres; the robot" + ("s stand" if BIM else " stands")
+ + " at low x and reach" + ("" if BIM else "es") + " towards +x"
+ + (" (right arm at y < 0, left arm at y > 0)" if BIM else ""),
+ "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},
+ "episode": "one episode, no reset: it ends at the first success, at a task failure (see task_text), or when your time is over",
+ "robot_spec": {
+ "name": ROBOT_NAME,
+ "description": ("two Franka Panda arms side by side, each with a 16-DoF Allegro hand (right arm first)" if BIM
+ else "a Franka Panda arm with a 16-DoF Allegro hand"),
+ "base": {"type": "fixed", "pose": _base(ARMS[0]), **({"per_arm": {a: _base(a) for a in ARMS}} if BIM else {}),
+ "note": "pose of the arm's base link (link0), world frame, x y z + quaternion wxyz"},
+ "joints": [j for a in ARMS for j in _joint_spec(a)],
+ "grippers": {},
+ "controller": {"type": "arm: operational-space control of the tcp (torques); hand: joint position actuators",
+ "control_hz": CTRL_HZ, "physics_hz": CTRL_HZ * SUBSTEPS, "gains": GAINS,
+ "note": "arm: DexJoCo's opspace controller drives attachment_site to the tcp target (position gains "
+ "400 N/m, damping ratio 4, gravity compensation, null space towards the home posture), "
+ "torques limited to effort_limit; hand: position actuators (stiffness N m/rad) on joints "
+ "with their own damping (N m s/rad)"},
+ "tcp": {TCP[a]: _tcp_spec(a) for a in ARMS},
+ },
+ "kinematics": {"endpoint": "/kinematics", "joint_names": JOINTS, "frame": "world", "quaternion_order": "wxyz",
+ "links": KIN_LINKS, "tcp_frames": [TCP[a] for a in ARMS], "ee_frames": [TCP[a] for a in ARMS],
+ "ik_targets": [TCP[a] for a in ARMS], "ik": {"tol_pos_m": 0.001, "tol_rot_rad": 0.01, "max_iters": 300},
+ "note": "the arm links, the hand mount (the hand cameras' parent) and the tcp, world frame; ik solves "
+ "each tcp target over that arm's 7 joints"},
+ "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()
+
+
+# ------------------------------------------------------------------------------------------------- state and frames
+def ctrl_steps() -> int:
+ return int(S.steps)
+
+
+def proprio_row() -> np.ndarray:
+ tcp, tgt, hand = [], [], []
+ for a in ARMS:
+ s = TCP_SITE[a]
+ tcp += [D.site_xpos[s], _quat(D.site_xmat[s])]
+ t = S._arm_target(a)
+ tgt.append(t[:7]); hand.append(t[7:23])
+ return np.concatenate([D.qpos[QADR], D.qvel[VADR], D.actuator_force[EFF_ACT], *tcp, *tgt, *hand]).astype(np.float32)
+
+
+def grab(cams, want_depth: bool):
+ rgb, dep = {}, {}
+ for c in cams:
+ rgb[c] = S.render_frame(c, (CAM_H, CAM_W))
+ if want_depth:
+ r = S._renderer # the one renderer (a second OSMesa context reads back garbage)
+ r.enable_depth_rendering()
+ try:
+ r.update_scene(D, camera=c)
+ dep[c] = r.render().astype(np.float32).copy()
+ finally:
+ r.disable_depth_rendering()
+ return rgb, dep
+
+
+def extrinsics(cams) -> dict:
+ return {c: _extrinsic(c) for c in cams}
+
+
+def summary() -> dict:
+ n = int(E.get("episode_control_steps") or ctrl_steps())
+ 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"],
+ "task": TASK, "protocol": L.PROTOCOL, "n_actions": len(ROWS), "task_failure": int(str(E["reason"] or "").startswith("failure")),
+ **EP.final_fields()}
+
+
+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 finish(reason: str) -> None:
+ """The episode is over: record the live verdict and dump the trajectory 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()
+ E["success"] = bool(S.success)
+ 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()
+ S.save_trajectory(np.asarray(ROWS, dtype=np.float64).reshape(-1, ADIM), os.path.join(DATA, "trajectory.npz"),
+ {"source": "standard-mode episode", "reason": E["reason"]})
+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})
+ write_final()
+
+
+def ctrl_step(a, rec) -> bool:
+ """One executed control step (DexJoCo's own row), journaled. True when the call must stop here."""
+ a = np.asarray(a, dtype=np.float64)
+ running = S.step(a)
+ ROWS.append(a.copy())
+ stop = EP.journal(a)
+ rec.tick()
+ if not running:
+ finish(S.reason or "done")
+ 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 DEFAULT_CAMS
+ if not isinstance(cams, list) or any(c not in CAMS for c in cams):
+ raise ValueError(f"unknown cameras {cams}; cameras: {CAMS}")
+ return list(dict.fromkeys(cams))
+
+
+def meta_common(cams) -> dict:
+ n = ctrl_steps()
+ return {"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}}
+
+
+def _native_from_ee(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ """ee_pose rows are executed as sent (the recorded row is what the agent commanded); hand targets outside the
+ actuator ranges are clamped by MuJoCo itself (ctrllimited) and only reported."""
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ if float(np.linalg.norm(row[o + 3:o + 7])) < 1e-6:
+ raise ValueError(f"row {ri}: the {a} tcp quaternion has zero norm")
+ for j in range(16):
+ lo, hi = HLIM[a][j]
+ v = row[o + 7 + j]
+ if v < lo or v > hi:
+ clipped.append({"row": ri, "index": int(o + 7 + j), "reason": f"{EE_LAYOUT[o + 7 + j]} outside [{lo:.3f}, {hi:.3f}]: clamped by the simulator"})
+ return row
+
+
+def _clip_joints(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ lo = np.array([ALIM[j][0] for j in JP_LAYOUT]); hi = np.array([ALIM[j][1] for j in JP_LAYOUT])
+ out = np.clip(row, lo, hi)
+ for j in np.flatnonzero(out != row)[:20]:
+ clipped.append({"row": ri, "index": int(j), "reason": f"{JP_LAYOUT[j]} limit [{lo[j]:g}, {hi[j]:g}]"})
+ return out
+
+
+def _native_from_joints(q: np.ndarray) -> np.ndarray:
+ out = []
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ out += [tcp_from_arm_joints(a, q[o:o + 7]), q[o + 7:o + 23]]
+ return np.concatenate(out)
+
+
+def _check_chunk(typ: str, A: np.ndarray, dt: float, interp: str, video: str) -> int:
+ k = dt / DT
+ if A.ndim != 2 or A.shape[1] != ADIM:
+ raise ValueError(f"{typ} actions must be (T, {ADIM}), got {list(A.shape)}")
+ if A.shape[0] == 0:
+ raise ValueError("no rows")
+ 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")
+ return int(round(k))
+
+
+def do_submit(meta: dict, A: np.ndarray):
+ typ = meta.get("type")
+ if typ not in ("ee_pose", "joint_position"):
+ raise ValueError(f"type must be ee_pose or joint_position (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)
+ n = _check_chunk(typ, A, dt, interp, video)
+ clipped: list = []
+ if typ == "ee_pose":
+ A = np.stack([_native_from_ee(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ else:
+ A = np.stack([_clip_joints(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ rec = recorder(cams, fps, meta)
+ E["calls"] += 1
+ step0, before = E["step"], ctrl_steps()
+ rec.tick(force=True)
+ if typ == "ee_pose":
+ prev = np.asarray(S.hold_action(), dtype=np.float64)
+ else:
+ prev = np.concatenate([np.concatenate([D.qpos[QADR[ARM_QI[a]]], S._arm_target(a)[7:23]]) for a in ARMS])
+ for row in A:
+ E["step"] += 1
+ stop = False
+ for s in range(1, n + 1):
+ if interp == "hold" or s == n:
+ target = row # a row's own values land exactly on its last control step
+ else:
+ target = prev + (row - prev) * (s / n)
+ if typ == "ee_pose":
+ for k in range(len(ARMS)):
+ o = 23 * k
+ target[o + 3:o + 7] = M.quat_slerp(prev[o + 3:o + 7], row[o + 3:o + 7], s / n)
+ native = target if typ == "ee_pose" else _native_from_joints(target)
+ if ctrl_step(native, rec):
+ stop = True
+ break
+ prev = row
+ 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"], "type": typ, "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 = np.asarray(S.hold_action(), dtype=np.float64)
+ 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={"task": TASK, "instance_sha": S.instance_sha, "instance_ok": bool(S.instance_exact), "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} DexJoCo sim ready ({TASK}; 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/dexjoco-bimanual-hanoi-i00-standard/environment/sim/task_text.txt b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/sim/task_text.txt
new file mode 100644
index 0000000000..a8754a0888
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-standard/environment/sim/task_text.txt
@@ -0,0 +1,3 @@
+Tower of Hanoi with three disks on three vertical posts in a row along y: the small disk is on post A (y > 0, the left arm's side), the medium disk on post B (middle), the large disk on post C (y < 0). Build the full tower on post C: large at the bottom, then medium, then small, posts A and B empty, every disk at rest and seated on the post (horizontally within 4 cm of it, at its stacking height within 1.2 cm), held for 20 consecutive control steps. A larger disk resting on a smaller one, or a disk resting on the table, for 10 consecutive steps ends the episode as a failure.
+
+Two arms with a hand each stand side by side facing the table (right arm at y < 0, left arm at y > 0); the wooden Hanoi base with its three posts is in front of them. Each disk has a hole and slides over a post.
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-standard/instruction.md b/tasks/dexjoco-bimanual-hanoi-i00-standard/instruction.md
new file mode 100644
index 0000000000..ce81c5ebf4
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-standard/instruction.md
@@ -0,0 +1,68 @@
+# DexJoCo · bimanual_hanoi — STANDARD MODE (robot as a service, eai-standard/2.2)
+
+You control two Franka Panda arms, each with a 16-DoF Allegro hand, **as if it were real hardware**: the simulator runs in a service you cannot open. You get
+one client and one episode. **Task:** Tower of Hanoi with three disks on three vertical posts in a row along y: the small disk is on post A (y > 0, the left arm's side), the medium disk on post B (middle), the large disk on post C (y < 0). Build the full tower on post C: large at the bottom, then medium, then small, posts A and B empty, every disk at rest and seated on the post (horizontally within 4 cm of it, at its stacking height within 1.2 cm), held for 20 consecutive control steps. A larger disk resting on a smaller one, or a disk resting on the table, for 10 consecutive steps ends the episode as a failure.
+
+Two arms with a hand each stand side by side facing the table (right arm at y < 0, left arm at y > 0); the wooden Hanoi base with its three posts is in front of them. Each disk has a hole and slides over a post.
+
+## Rules (real-robot rules)
+- **No reset.** The episode starts when the service comes up and ends on success, on a task failure (see the task), when
+ your time is up, or on a simulator error. Knocked-over objects stay knocked over.
+- **No privileged state.** You see what the cameras see (RGB, and depth on request, with each camera's calibration) plus
+ the robot's own proprioception (joints, tcp poses, the current targets). No object poses, no success check:
+ `meta["done"]` / `meta["reason"]` tell you when the episode is over and why.
+- Steps are unlimited; your wall-clock budget (90 minutes) is the limit (`meta["time_left_s"]`). Actions and
+ simulated time are reported as cost. Do not stop before the task is solved.
+- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
+ `/app/output/gen.py` for the record (save it early, update it as you go).
+- **Nothing is put into your context automatically.** Images and videos come back as arrays/bytes in a Python object;
+ what you look at and where you store it is your code's decision.
+
+## Client (`/opt/tools/rcb_client.py`, protocol `eai-standard/2.2`)
+```python
+from rcb_client import Robot
+r = Robot() # connects (waits while the service starts)
+spec = r.spec() # action types, cameras (+ calibration), proprio layout, robot_spec, kinematics, budget
+obs = r.get_obs() # current frames of spec["default_cameras"]: obs.last[cam] -> uint8 (480, 640, 3)
+obs = r.get_obs(cameras=["front", "handcam_rgb_right"], depth=True) # + obs.last_depth[cam] -> float32 (480, 640) z-depth (m)
+obs.meta["proprio"] # {"layout": [...], "now": [...]}; obs.group("tcp_pose", now=True)
+obs.meta["cameras"] # per camera intrinsic_cv / extrinsic_cv / cam2world_gl for these frames
+obs = r.get_obs(seconds=2.0, video="mp4") # hold the current targets and watch for 2 s (max 30): obs.video[cam] = mp4 bytes
+
+res = r.submit("ee_pose", rows, dt=0.1) # rows: (T, 46) targets dt seconds apart, executed at 50 Hz with interpolation
+res = r.submit("joint_position", q_rows, dt=0.1) # (T, 46) joint targets instead (see below)
+res.meta["done"], res.meta["reason"], res.meta["clipped"], res.meta["control_steps_chunk"]
+res.video["front"]; res.last["front"]; res.proprio # mp4 of the chunk, last frame, float32 (N, P) proprio per frame
+res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, proprio.npy, ...
+r.fk(q); r.ik({"tcp_right": pose}, seed=q) # kinematics of the robot (stateless: no physics, no time)
+r.status() # calls, control steps, done, reason, elapsed time
+```
+Cameras: `front`, `back`, `left`, `right`, `top0` (static), `handcam_rgb_right`, `handcam_rgb_left` (on the hand mounts; they move,
+so use the calibration that comes with each response; `spec["cameras"][cam]["mount"]` gives the static pose or the mount
+link). Resolution 640x480. Rendering runs on the CPU: ask only for the cameras you need; `video="none"` makes a chunk
+fastest. If a call fails with a connection error the service may have crashed: it resumes the same episode;
+`r.wait_ready()`, then check `r.status()` (`spec["on_service_error"]`).
+
+### Action type `ee_pose` (46) — DexJoCo's own action
+Per arm, right first: tcp target position (3, metres, world frame), tcp target orientation (4, quaternion wxyz), 16
+Allegro joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+target and stops where contact blocks it); the hand joints are position-controlled. Rows are `dt` apart (a whole multiple
+of 1/50 s, at most 0.5 s); between rows positions and joints move linearly and orientations by slerp
+(`interpolate="linear"`) or jump (`"hold"`); a chunk may cover at most 10 s. Hand targets outside the ranges
+(`spec["action_types"]["ee_pose"]["hand_limits"]`) are clamped by the simulator and listed in `meta["clipped"]`. Build
+the next row from the `tcp_target` and `hand_target` proprio groups to move smoothly.
+
+### Action type `joint_position` (46)
+Per arm, right first: 7 Panda joint targets, then the 16 Allegro joint targets (rad). The service turns the arm's targets
+into a tcp target by forward kinematics and the same controller tracks it: the tcp reaches FK(q), but the measured arm
+joints may differ from q in the arm's redundant direction (the controller's null space pulls towards a home posture).
+Out-of-limit values are clipped and reported.
+
+## Conventions
+- World frame, metres, z up; the robots stand at low x and reach towards +x (right arm at y < 0, left arm at y > 0); each
+ arm's base pose is in `spec["robot_spec"]["base"]`. No other world coordinates are given (D7: the cameras are
+ calibrated, depth is available). Quaternions are **WXYZ**.
+- The tcp (`tcp_right`, `tcp_left`) is the hand's mounting flange (`spec["robot_spec"]["tcp"]`), not the fingertips. Allegro joint
+ order (right hand): index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger = spread, 1-3 = flexion
+ from the knuckle out; thumb 12 = opposition). The LEFT hand's 16 values are mirrored: ring 0-3, middle 4-7, index 8-11, thumb 12-15 (the joint names in `spec["proprio_layout"]` say which).
+- Control runs at 50 Hz (10 physics substeps of 2 ms). There is no step budget: your wall-clock time is the limit.
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-standard/solution/oracle_stream.py b/tasks/dexjoco-bimanual-hanoi-i00-standard/solution/oracle_stream.py
new file mode 100644
index 0000000000..19877300c1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-standard/solution/oracle_stream.py
@@ -0,0 +1,43 @@
+"""Oracle (standard mode): streams the reference rows (the human demonstration's own actions, one per 1/50 s control step,
+float32-exact) as `ee_pose` 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
+
+A = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle_trajectory.npz"))["actions"].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(A), flush=True)
+t0, i = time.time(), 0
+while i < len(A):
+ chunk = A[i:i + per_chunk]
+ try:
+ res = r.submit("ee_pose", chunk, dt=dt, interpolate="hold", 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/dexjoco-bimanual-hanoi-i00-standard/solution/oracle_trajectory.npz b/tasks/dexjoco-bimanual-hanoi-i00-standard/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..7195531771
Binary files /dev/null and b/tasks/dexjoco-bimanual-hanoi-i00-standard/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-standard/solution/solve.sh b/tasks/dexjoco-bimanual-hanoi-i00-standard/solution/solve.sh
new file mode 100755
index 0000000000..1bd55d898f
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-standard/solution/solve.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+# Oracle (standard mode): streams the reference trajectory's rows (solution/oracle_trajectory.npz, one row per control
+# step) as `ee_pose` chunks through the client. Uses no privileged information at run time (only the pre-recorded rows);
+# the service's recorded trajectory is then exactly the privileged reference.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_stream.py /app/output/gen.py
+python /solution/oracle_stream.py
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-standard/task.toml b/tasks/dexjoco-bimanual-hanoi-i00-standard/task.toml
new file mode 100644
index 0000000000..272b27832e
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-standard/task.toml
@@ -0,0 +1,52 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator 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/dexjoco-bimanual-hanoi-i00-standard"
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): DexJoCo bimanual_hanoi (two Franka Panda arms, each with a 16-DoF Allegro hand) on the same frozen instance as dexjoco-bimanual-hanoi-i00-privileged. Tower of Hanoi with three disks on three vertical posts in a row along y: the small disk is on post A (y > 0, the left arm's side), the medium disk on post B (middle), the large disk on post C (y < 0). The agent only gets a client: calibrated cameras (RGB, optional depth), the robot's joints and tcp poses, tcp-target + hand-joint chunks at 50 Hz, the robot's kinematics; one episode, no reset, no object state; the sim service records the episode, replays it in fresh processes and grades it."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "standard-mode", "robot-as-a-service", "bimanual_hanoi"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro-bimanual"
+family = "bimanual_hanoi"
+mode = "standard"
+protocol = "eai-standard/2.2"
+oracle = "full"
+expert_time_estimate_hours = 2.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 = 3600
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-standard/tests/Dockerfile b/tasks/dexjoco-bimanual-hanoi-i00-standard/tests/Dockerfile
new file mode 100644
index 0000000000..26bc699ebe
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-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.sh
diff --git a/tasks/dexjoco-bimanual-hanoi-i00-standard/tests/grade.py b/tasks/dexjoco-bimanual-hanoi-i00-standard/tests/grade.py
new file mode 100644
index 0000000000..003b933315
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-standard/tests/grade.py
@@ -0,0 +1,60 @@
+"""Standard-mode verifier (DexJoCo): 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 frozen 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"))),
+ "task_failure": int(bool(d.get("task_failure"))),
+ "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),
+ "calls": int(d.get("calls") or 0),
+ "elapsed_s": float(d.get("elapsed_s") or 0),
+ "video_rendered": int(bool(d.get("video"))),
+ # 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 frozen 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/dexjoco-bimanual-hanoi-i00-standard/tests/test.sh b/tasks/dexjoco-bimanual-hanoi-i00-standard/tests/test.sh
new file mode 100755
index 0000000000..bc608aa8b9
--- /dev/null
+++ b/tasks/dexjoco-bimanual-hanoi-i00-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
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/README.md b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/README.md
new file mode 100644
index 0000000000..7f67c1d1ed
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/README.md
@@ -0,0 +1,49 @@
+# dexjoco-bimanual-microwave-cook-i00-privileged
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | privileged |
+| Twin | `dexjoco-bimanual-microwave-cook-i00-standard` |
+| Simulator / robot | `dexjoco` / `franka-allegro-bimanual` |
+| Family / instance | `bimanual_microwave_cook` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `bimanual_microwave_cook` (two Franka Panda arms, each with a 16-DoF Allegro hand): Open the microwave door, put the hot dog inside, close the door and press the start button. Success, at one control step: the hot dog is inside the cavity (1 cm margin), the door hinge is within 0.01 rad of closed, and the start button is in contact with something.
+Privileged mode: the agent works in the simulator's container with live object poses, unlimited resets and thin motion
+primitives, and hands in one trajectory replayed open-loop from the frozen instance.
+
+## Difficulty
+First-pass rating: hard. Dexterous manipulation with two 16-DoF hands on two arms (46 action values per control step);
+the primitives only move tcp and hand-joint targets, so grasping, pressing and every other skill is the agent's. The
+reference (the human teleoperator's demonstration) takes 815 control steps (16.3 s at 50 Hz).
+
+## Reference solution
+`solution/oracle_trajectory.npz` = the human demonstration's own actions, rounded to float32 (the standard client's
+precision; the rounded rows still succeed) and replayed from the frozen instance until the episode ends in success
+(815 rows). The demonstration is public (DexJoCo-Datasets-Raw on Hugging Face), so agent egress is
+limited to the model APIs.
+
+## Verification
+Open-loop replay of `/app/output/trajectory.npz` from `tests/instance.npz`, twice in a fresh process in the verifier's own
+sandbox (no network); pass iff both episodes end in success, their final-state hashes agree and the rebuilt instance
+matches its recorded hash (`tests/grade.py`); plus `/logs/verifier/replay.mp4`. Oracle: success after 815 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `microwave_cook_demo_10_2026-02-09_11-56-09_655851` (DexJoCo-Datasets-Raw), restored with DexJoCo's own state restorer; instance sha `6c16f3cfa1c737c7` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Tooling notes
+DexJoCo's reset samples object poses from the global RNG and its state restorer edits the MuJoCo model (table height,
+fixed bodies), so `instance.npz` stores the full physics state (`mjSTATE_INTEGRATION`), the mocap targets, the controls,
+every numeric model array a task can change, and the env's Python-side task state. Its per-step camera rendering,
+real-time sleep, episode cap and hanoi's wall-clock auto-reset are disabled in the tooling (`rcb_dexjoco.py`).
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py` from `scripts/dexjoco/instances/bimanual_microwave_cook/` (`make_instances.py`).
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/environment/Dockerfile b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/environment/Dockerfile
new file mode 100644
index 0000000000..d736fe8a7d
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/environment/Dockerfile
@@ -0,0 +1,7 @@
+# Base image = DexJoCo on MuJoCo 3.4.0 (images/dexjoco/). Everything task-specific is copied here. CPU only.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY instance.npz /app/instance.npz
+COPY rcb_dexjoco.py /opt/tools/rcb_dexjoco.py
+ENV PYTHONPATH=/opt/tools
+RUN mkdir -p /app/output
+WORKDIR /app
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/environment/instance.npz b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/environment/instance.npz
new file mode 100644
index 0000000000..d07075df98
Binary files /dev/null and b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/environment/instance.npz differ
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/environment/rcb_dexjoco.py b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/environment/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/environment/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/instruction.md b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/instruction.md
new file mode 100644
index 0000000000..5f78fa7178
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/instruction.md
@@ -0,0 +1,93 @@
+# DexJoCo · bimanual_microwave_cook — frozen instance
+
+You control two Franka Panda arms, each with a 16-DoF Allegro hand (DexJoCo on MuJoCo 3.4) via Python. **Task:** Open the microwave door, put the hot dog inside, close the door and press the start button. Success, at one control step: the hot dog is inside the cavity (1 cm margin), the door hinge is within 0.01 rad of closed, and the start button is in contact with something.
+
+The microwave stands on the table with its door closed; the hot dog lies in front of it. The door has a handle and a hinge (`door_hinge`); the start and stop buttons are on the front panel. `s.objects()` gives the live poses of the task objects (`hot_dog`, `microwave`, `door_hinge`, `door_handle`, `start_button`, `stop_button`, `table_top`). DexJoCo's success code (from
+`/opt/dexjoco/dexjoco/dexjoco/sim/envs/panda_bimanual_microwave_cook_env.py`; `step()` ends the episode on success or on a task failure):
+```python
+def _compute_success(self):
+ # ---- door must be closed ----
+ micro_qpos = float(self._data.joint("microjoint").qpos)
+ microwave_closed = abs(micro_qpos) < 1e-2
+
+ # ---- hot_dog must be inside interior bbox ----
+ inside = self.hot_dog_inside_microwave(margin=0.01)
+
+ contact = self._geom_in_contact("start_button")
+
+ # Debug helpers kept nearby for local inspection when needed.
+ # print("microjoint qpos:", micro_qpos)
+ # print("hot_dog inside:", inside)
+ # print("start button pressed:", contact)
+
+ return inside and microwave_closed and contact
+
+def hot_dog_inside_microwave(self, margin=0.0):
+ # ---- hot_dog world position ----
+ p_world = self._data.sensor("hot_dog_pos").data
+
+ # ---- transform to microwave local frame ----
+ p_local = self.world_to_body("microwave_object", p_world)
+
+ # ---- read interior box sites (local frame) ----
+ p0 = self._model.site("int_p0").pos
+ px = self._model.site("int_px").pos
+ py = self._model.site("int_py").pos
+ pz = self._model.site("int_pz").pos
+
+ inside_x = (p0[0] - margin) <= p_local[0] <= (px[0] + margin)
+ inside_y = (p0[1] - margin) <= p_local[1] <= (py[1] + margin)
+ inside_z = (p0[2] - margin) <= p_local[2] <= (pz[2] + margin)
+
+ return inside_x and inside_y and inside_z
+```
+
+This is a *fixed scene instance*: object poses, the table height and the robot's start pose never change between
+resets. You may reset and retry as many times as you want. Your deliverable is **one replayable trajectory**, not a
+general policy.
+
+## Deliverable
+Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
+open-loop from the same initial state in a fresh process and scored 1 if its episode ends in success, else 0. Also
+leave the script that produced it at `/app/output/gen.py`. You have 90 minutes of wall clock: save a
+first trajectory early, improve it, and do not stop before the task is solved.
+
+## Tooling (already installed; run `python` from any directory)
+```python
+from rcb_dexjoco import Session
+s = Session("bimanual_microwave_cook", instance="/app/instance.npz") # ~1 s: builds the env and loads the frozen state
+s.reset() # back to the frozen initial state (as often as you like; an exact snapshot restore)
+s.objects() # live task objects: name -> pos, quat_wxyz (bodies) / pos (sites) / qpos (joints)
+s.state() # DexJoCo's state dict: tcp_pose, gripper_pose (hand joints), INITIAL object poses, table height
+p = s.primitives() # thin wrappers of the low-level action; each has a docstring: help(p["move_ee"])
+p["move_ee"]("right", pos, quat_wxyz) # straight-line + slerp motion of an arm's tcp target, then settle
+p["set_hand"]("right", q16) # interpolate the 16 Allegro joint targets
+p["hold"](10); p["set_targets"](row, steps) # keep every target / send one raw action row
+p["get_ee_pose"]("right"); p["get_ee_target"]("right"); p["get_hand"]("right"); p["get_body_pose"](name)
+s.render_frame("back") # RGB uint8 (480, 640, 3); cameras: ['back', 'handcam_rgb_right', 'handcam_rgb_left']; s.render_grid()
+s.step(action) # one control step (46 values, below) = 1/50 s; returns False once the episode is over
+s.record_start(); ...; actions = s.record_stop() # (T, 46) actions, one row per control step
+s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+s.replay(actions) # resets, replays open-loop until the episode ends, returns status -> self-check
+s.save_trajectory(actions, "/app/output/trajectory.npz")
+s.render_video(actions, "/app/output/check.mp4", cameras=["back"]) # replays from the frozen state into a video
+```
+The primitives are deliberately thin (tcp target moves, hand joint targets, hold): grasping, pressing, striking and
+every other skill are yours to build from them. `s.bodies()` lists every MuJoCo body for `p["get_body_pose"]`.
+
+CLI equivalent of the grader:
+`python /opt/tools/rcb_dexjoco.py replay --task bimanual_microwave_cook --instance /app/instance.npz --traj /app/output/trajectory.npz`
+
+## Conventions
+- World frame, metres; z up; the robots stand at low x and reach towards +x. The table top is at z = 0.943. Arm base (`link0`): link0_right [-0.75, -0.4, 0.924], link0_left [-0.75, 0.4, 0.924]. The right arm works at y < 0, the left arm at y > 0. Quaternions are **WXYZ**.
+- Action (46): per arm, right first: tcp target position (3), tcp target orientation (4, wxyz), 16 Allegro
+ joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+ target and stops where contact blocks it); the hand joints are position-controlled. `s.hold_action()` is the no-op.
+ At the start the tcp target is right [-0.443, -0.4, 1.517] / [0.0, 1.0, 0.0, 0.0], left [-0.443, 0.4, 1.517] / [0.0, 1.0, 0.0, 0.0].
+- Allegro joint order (right hand): index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger =
+ spread, 1-3 = flexion from the knuckle out; thumb 12 = opposition). The LEFT hand's 16 values are mirrored: ring 0-3, middle 4-7, index 8-11, thumb 12-15.
+ Target ranges (rad, same for every finger slot, thumb last): low [-0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, 0.26, -0.1, -0.19, -0.16], high [0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 1.4, 1.16, 1.64, 1.72]; the simulator clamps
+ targets to them.
+- Control runs at 50 Hz (10 physics substeps of 2 ms). DexJoCo's own episode cap and real-time pacing are lifted: there
+ is no step budget, your wall-clock time is the limit (~190 control steps/s here). An episode ends at the
+ first success or task failure; `s.step` then refuses further actions until `s.reset()`.
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/solution/gen.py b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/solution/gen.py
new file mode 100644
index 0000000000..0e1f7e3bc7
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/solution/gen.py
@@ -0,0 +1,4 @@
+# How solution/oracle_trajectory.npz was made (scripts/dexjoco/make_instances.py): the DexJoCo human demonstration's
+# own actions (replay.zarr data/action), rounded to float32, replayed from the frozen instance with Session.replay until
+# the episode ended in success (holding the last row a few steps where the rounded rows ended short of a hold count),
+# truncated there and saved with Session.save_trajectory.
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/solution/oracle_trajectory.npz b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..896244501e
Binary files /dev/null and b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/solution/solve.sh b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/solution/solve.sh
new file mode 100755
index 0000000000..7909c90cb8
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/solution/solve.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+# Reference solution: the human demonstration's actions (float32), replayed through the task tooling until success.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_trajectory.npz /app/output/trajectory.npz
+cp /solution/gen.py /app/output/gen.py
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/task.toml b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/task.toml
new file mode 100644
index 0000000000..b20b7b1276
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/task.toml
@@ -0,0 +1,37 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator or the instance, not this.
+schema_version = "1.3"
+artifacts = ["/app/output/"]
+
+[task]
+name = "robot-coding-bench/dexjoco-bimanual-microwave-cook-i00-privileged"
+description = "DexJoCo bimanual_microwave_cook (two Franka Panda arms, each with a 16-DoF Allegro hand, MuJoCo): produce one replayable trajectory. Open the microwave door, put the hot dog inside, close the door and press the start button. Frozen scene instance (the initial state of a DexJoCo human demonstration)."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "code-as-policy", "trajectory", "bimanual_microwave_cook"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro-bimanual"
+family = "bimanual_microwave_cook"
+mode = "privileged"
+oracle = "full"
+expert_time_estimate_hours = 3.0
+
+[verifier]
+timeout_sec = 1800.0
+environment_mode = "separate" # the verifier runs in its own sandbox (tests/Dockerfile); the agent container is gone by then
+network_mode = "no-network"
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
+
+[verifier.environment]
+build_timeout_sec = 1800.0
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/tests/Dockerfile b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/tests/Dockerfile
new file mode 100644
index 0000000000..a2620a4da8
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/tests/Dockerfile
@@ -0,0 +1,8 @@
+# Separate verifier sandbox (PROTOCOL §2.6): the same simulator image with the verifier's own copies of the tooling and
+# the frozen instance baked in. Nothing the agent did in its container reaches this one: Harbor uploads only the declared
+# artifacts (/app/output/), so a patched success check in the agent container cannot count.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY grade.py instance.npz rcb_dexjoco.py test.sh /tests/
+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
+ENV PYTHONPATH=/tests
+WORKDIR /tests
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/tests/grade.py b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/tests/grade.py
new file mode 100644
index 0000000000..ad916e8bb9
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/tests/grade.py
@@ -0,0 +1,109 @@
+"""Verifier entry point for the privileged DexJoCo tasks: replay /app/output/trajectory.npz from the frozen instance and
+write Harbor rewards.
+
+ python /tests/grade.py --family water_plant --instance /tests/instance.npz --traj /app/output/trajectory.npz
+
+Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only; Harbor rejects strings), a replay video
+/logs/verifier/replay.mp4 (front camera + wrist camera) and replay.last.png. Replays `--repeat` times in this fresh
+process; success requires every replay to end its episode in success (DexJoCo's own rule: the episode ends at the first
+success or task failure) AND all final-state hashes to agree (MuJoCo on the CPU is bit-deterministic), and the frozen
+instance rebuilt here from tests/instance.npz must match its recorded hash.
+"""
+from __future__ import annotations
+import argparse, json, os, sys, time, traceback
+import numpy as np
+
+LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")
+
+
+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 self_reported_cost() -> dict:
+ # From the tooling's append-only log in the agent's container: SELF-REPORTED accounting, never evidence.
+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_records": 0, "agent_replays": 0,
+ "agent_cost_self_reported": 1}
+ try:
+ with open("/app/output/rcb_session_log.jsonl") 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 == "session_end": cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)
+ elif ev == "record": cost["agent_records"] += 1
+ elif ev == "replay": cost["agent_replays"] += 1
+ except Exception: # noqa: BLE001 — one bad line must not sink the verdict
+ continue
+ except Exception: # noqa: BLE001
+ pass
+ return cost
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--family", required=True); ap.add_argument("--instance", required=True)
+ ap.add_argument("--traj", default="/app/output/trajectory.npz"); ap.add_argument("--repeat", type=int, default=2)
+ ap.add_argument("--no-video", action="store_true")
+ a = ap.parse_args()
+ cost = self_reported_cost()
+ os.environ["RCB_SESSION_LOG"] = "" # the verifier's own sessions are not the agent's cost
+ if not os.path.isfile(a.traj):
+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost}); return 0
+ s = None
+ try:
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the verifier's own copy of the tooling
+ import rcb_dexjoco
+ rcb_dexjoco.SESSION_LOG = ""
+ from rcb_dexjoco import Session, MAX_STEPS
+ d = np.load(a.traj, allow_pickle=False)
+ if str(d["task"]) != a.family:
+ write(False, {"success": 0, "wrong_family": 1, "grader_error": 0, **cost}); return 0
+ acts = np.asarray(d["actions"], dtype=np.float64)
+ s = Session(a.family, instance=a.instance)
+ if (acts.ndim != 2 or acts.shape[1] != s.action_dim or acts.shape[0] > MAX_STEPS
+ or not np.all(np.isfinite(acts))):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0,
+ "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0, **cost}); return 0
+ t0 = time.time()
+ outs = []
+ for _ in range(a.repeat):
+ try:
+ outs.append(s.replay(acts))
+ except (ValueError, rcb_dexjoco.PrimitiveError):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0, "n_actions": int(len(acts)), **cost}); return 0
+ all_success = all(o["success"] for o in outs)
+ deterministic = len({o["state_sha"] for o in outs}) == 1
+ instance_ok = bool(s.instance_exact)
+ ok = all_success and deterministic and instance_ok
+ out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
+ "instance_ok": int(instance_ok), "n_actions": int(len(acts)), "sim_steps": int(outs[0]["steps"]),
+ "task_failure": int(bool(outs[0]["reason"]) and not outs[0]["success"]),
+ "replay_wall_s": round(time.time() - t0, 1), "grader_error": 0, "video_rendered": 0, **cost}
+ if not a.no_video: # human-viewable replay (never affects the verdict)
+ try:
+ n = int(outs[0]["replayed_rows"])
+ s.render_video(acts[:n], os.path.join(LOG_DIR, "replay.mp4"), cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ import imageio.v2 as imageio
+ imageio.imwrite(os.path.join(LOG_DIR, "replay.last.png"), s.render_frame(s.default_camera(), (480, 640)))
+ out["video_rendered"] = int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4")))
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(ok, out)
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(False, {"success": 0, "grader_error": 1, **cost})
+ finally:
+ if s is not None:
+ s.close()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/tests/instance.npz b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/tests/instance.npz
new file mode 100644
index 0000000000..d07075df98
Binary files /dev/null and b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/tests/instance.npz differ
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/tests/rcb_dexjoco.py b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/tests/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/tests/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/tests/test.sh b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/tests/test.sh
new file mode 100755
index 0000000000..769c7e677d
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-privileged/tests/test.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in a fresh process.
+# 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/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)
+mkdir -p /logs/verifier
+python /tests/grade.py --family bimanual_microwave_cook --instance /tests/instance.npz --traj /app/output/trajectory.npz --repeat 2 \
+ 2> /logs/verifier/grade.log
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-standard/README.md b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/README.md
new file mode 100644
index 0000000000..e1e538b3fa
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/README.md
@@ -0,0 +1,45 @@
+# dexjoco-bimanual-microwave-cook-i00-standard
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | standard (`eai-standard/2.2`) |
+| Twin | `dexjoco-bimanual-microwave-cook-i00-privileged` |
+| Simulator / robot | `dexjoco` / `franka-allegro-bimanual` |
+| Family / instance | `bimanual_microwave_cook` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `bimanual_microwave_cook` (two Franka Panda arms, each with a 16-DoF Allegro hand) on the same frozen instance as `dexjoco-bimanual-microwave-cook-i00-privileged`: Open the microwave door, put the hot dog inside, close the door and press the start button. Success, at one control step: the hot dog is inside the cavity (1 cm margin), the door hinge is within 0.01 rad of closed, and the start button is in contact with something.
+Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with the robot's own
+sensors, calibrated cameras (RGB, optional depth) and the robot's kinematics.
+
+## Difficulty
+Same instance and success check as `dexjoco-bimanual-microwave-cook-i00-privileged`. In standard mode the agent loses resets, the
+simulator and the object poses: it sees camera images and proprioception, acts in chunks of tcp-target + hand-joint rows
+(or joint targets), and gets one episode, so it has to close the loop on what the cameras show and recover from its own
+mistakes without starting over.
+
+## Reference solution
+`solution/oracle_stream.py` streams the privileged reference's rows (`solution/oracle_trajectory.npz`, 815 rows, float32-exact)
+through the client as `ee_pose` 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 815 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 815 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `microwave_cook_demo_10_2026-02-09_11-56-09_655851` (DexJoCo-Datasets-Raw); instance sha `6c16f3cfa1c737c7` |
+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); action types `ee_pose` and `joint_position`; cameras `back`, `handcam_rgb_right`, `handcam_rgb_left` (640 x 480); `/kinematics` for the arm links, the hand mount and the tcp; crash recovery class `exact` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py`, as its privileged twin.
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/Dockerfile b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/Dockerfile
new file mode 100644
index 0000000000..a778c94561
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/Dockerfile
@@ -0,0 +1,9 @@
+# Standard mode: the agent container has NO simulator and no DexJoCo 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 /app
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/client-requirements.txt b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/client-requirements.txt
new file mode 100644
index 0000000000..8aa73a968f
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-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.0
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/docker-compose.yaml b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/docker-compose.yaml
new file mode 100644
index 0000000000..68a45019cd
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/docker-compose.yaml
@@ -0,0 +1,24 @@
+# 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 OSMesa rendering; 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-dexjoco:0.1.2
+ 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_TASK: bimanual_microwave_cook
+ RCB_INSTANCE: /srv/instance.npz
+ RCB_TOOL: /srv/rcb_dexjoco.py
+ RCB_DATA: /data
+ RCB_WALL_CLOCK_S: "5400"
+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in a few seconds
+ PYTHONPATH: /srv
+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction log
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/rcb1.py b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-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/dexjoco-bimanual-microwave-cook-i00-standard/environment/rcb_client.py b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/rcb_client.py
new file mode 100644
index 0000000000..aa25b0e050
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-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/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/finalize.sh b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/finalize.sh
new file mode 100755
index 0000000000..e0cf248720
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-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_dexjoco.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:?}"; TASK="${RCB_TASK:?}"
+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 --task "$TASK" --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --repeat 1 \
+ --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"))
+PY
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/instance.npz b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/instance.npz
new file mode 100644
index 0000000000..d07075df98
Binary files /dev/null and b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/instance.npz differ
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/rcb1.py b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-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/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/rcb_dexjoco.py b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/rcb_limited.py b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/rcb_limited.py
new file mode 100644
index 0000000000..1ce1171787
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-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/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/run.sh b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/run.sh
new file mode 100755
index 0000000000..49d4d045d4
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-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; done
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/server.py b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/server.py
new file mode 100644
index 0000000000..ca5b61fc5c
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/server.py
@@ -0,0 +1,625 @@
+"""eai-standard/2.2 sim service for DexJoCo (docs/STANDARD_MODE_2_2.md): the adapter of the shared layer rcb_limited.py;
+the simulator is rcb_dexjoco.Session (DexJoCo on MuJoCo 3.4, CPU physics, OSMesa rendering).
+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to
+/data/episode.jsonl.
+
+The robot is a Franka Panda with a 16-DoF Allegro hand, or two of them side by side (right arm first). One control step
+= 1/50 s (10 physics substeps of 2 ms). Two action types:
+ ee_pose DexJoCo's own row, per arm: the tcp target pose (xyz m, quaternion wxyz, world frame) that its
+ operational-space controller tracks + 16 Allegro joint targets (rad);
+ joint_position per arm: 7 arm joint targets + 16 Allegro joint targets; the arm's targets are turned into a tcp target
+ by forward kinematics (the controller tracks the tcp pose, not the joints).
+Either way, the executed (journaled, recorded) row is DexJoCo's own row, so the recorded trajectory replays in the
+privileged tooling unchanged. As in DexJoCo's evaluation the episode ends at the first success or task failure;
+otherwise when the agent's time is over (the collect hook's SIGUSR1).
+
+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 instance 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")
+TASK = os.environ.get("RCB_TASK", "water_plant")
+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.npz"))
+TASK_TEXT_FILE = os.environ.get("RCB_TASK_TEXT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "task_text.txt"))
+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "5400"))
+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 = 640, 480
+CTRL_HZ = 50.0
+DT = 1.0 / CTRL_HZ
+SUBSTEPS = 10
+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"] = "" # the sidecar's Session is not the agent's interaction log
+import rcb_dexjoco as M # noqa: E402
+import mujoco # noqa: E402
+
+M.SESSION_LOG = ""
+BIM = TASK.startswith("bimanual_")
+ADIM = 46 if BIM else 23
+EP = L.Episode(DATA, dim=ADIM, resume="exact")
+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()
+S = M.Session(TASK, instance=INSTANCE, image_size=(CAM_H, CAM_W))
+MD, D = S.model, S.data
+ARMS = S.arms()
+SFX = {a: (f"_{a}" if BIM else "") for a in ARMS}
+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz
+
+# ------------------------------------------------------------------------------------------------- the robot
+ARM_JOINTS = {a: [f"joint{i}{SFX[a]}" for i in range(1, 8)] for a in ARMS}
+HAND_CTRL = {a: np.asarray(S._hand_ctrl_ids(a)) for a in ARMS}
+HAND_JOINTS = {a: [MD.joint(int(MD.actuator_trnid[i, 0])).name for i in HAND_CTRL[a]] for a in ARMS} # action order
+ARM_CTRL = {a: [MD.actuator(f"actuator{i}{SFX[a]}").id for i in range(1, 8)] for a in ARMS}
+JOINTS = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]] # kinematics q = proprio joint_pos columns
+QADR = np.array([MD.jnt_qposadr[MD.joint(j).id] for j in JOINTS])
+VADR = np.array([MD.jnt_dofadr[MD.joint(j).id] for j in JOINTS])
+EFF_ACT = np.array([i for a in ARMS for i in list(ARM_CTRL[a]) + list(HAND_CTRL[a])])
+TCP_SITE = {a: MD.site(f"attachment_site{SFX[a]}").id for a in ARMS}
+TCP = {a: f"tcp{SFX[a]}" for a in ARMS}
+MOUNT_BODY = {a: f"attachment{SFX[a]}" for a in ARMS}
+LINKS = {a: [f"link{i}{SFX[a]}" for i in range(0, 8) if mujoco.mj_name2id(MD, mujoco.mjtObj.mjOBJ_BODY, f"link{i}{SFX[a]}") >= 0]
+ + [MOUNT_BODY[a]] for a in ARMS}
+KIN_LINKS = [n for a in ARMS for n in LINKS[a] + [TCP[a]]]
+JLIM = {j: MD.jnt_range[MD.joint(j).id].astype(float).tolist() for j in JOINTS}
+HLIM = {a: S.hand_limits(a) for a in ARMS} # actuator ctrlrange, action order
+ALIM = {} # joint_position limits (inside the joint ranges)
+for a in ARMS:
+ for j in ARM_JOINTS[a]:
+ ALIM[j] = JLIM[j]
+ for j, (lo, hi) in zip(HAND_JOINTS[a], HLIM[a]):
+ ALIM[j] = [max(float(lo), JLIM[j][0]), min(float(hi), JLIM[j][1])]
+POSE = ["x", "y", "z", "qw", "qx", "qy", "qz"]
+EE_LAYOUT = [] # per arm, right first
+for a in ARMS:
+ EE_LAYOUT += [f"{TCP[a]}_target_{k}" for k in POSE] + [f"{j}_target" for j in HAND_JOINTS[a]]
+JP_LAYOUT = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]]
+
+GROUPS = [
+ ("joint_pos", JOINTS, "measured joint positions (rad): per arm (right first) the 7 Panda joints, then the 16 Allegro "
+ "joints in the action's order"),
+ ("joint_vel", [f"{j}_vel" for j in JOINTS], "measured joint velocities (rad/s)"),
+ ("joint_effort", [f"{j}_effort" for j in JOINTS], "actuator efforts (N m): the arm's operational-space torques and the "
+ "hand's position-actuator forces"),
+ ("gripper_opening", [], "none: a 16-DoF Allegro hand, its finger joints are in joint_pos"),
+ ("tcp_pose", [f"{TCP[a]}_{k}" for a in ARMS for k in POSE], "measured tcp pose per arm (x y z m, quaternion wxyz, world)"),
+ ("tcp_target", [f"{TCP[a]}_target_{k}" for a in ARMS for k in POSE], "the tcp target the controller tracks now (the "
+ "ee_pose part of the last executed row)"),
+ ("hand_target", [f"{j}_target" for a in ARMS for j in HAND_JOINTS[a]], "the Allegro joint targets now (rad)"),
+]
+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)
+
+
+def _quat(xmat) -> np.ndarray:
+ q = np.zeros(4)
+ mujoco.mju_mat2Quat(q, np.asarray(xmat, dtype=np.float64).reshape(9))
+ return q
+
+
+# ------------------------------------------------------------------------------------------------- cameras
+CAMS = S.cameras()
+HAND_CAMS = [c for c in CAMS if c.startswith("handcam")]
+DEFAULT_CAMS = [S.default_camera()]
+GL2CV = np.diag([1.0, -1.0, -1.0, 1.0])
+
+
+def _intrinsic(cam: str) -> list:
+ fovy = math.radians(float(MD.cam_fovy[MD.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 _cam2world_gl(cam: str) -> np.ndarray:
+ i = MD.camera(cam).id
+ T = np.eye(4)
+ T[:3, :3] = D.cam_xmat[i].reshape(3, 3) # MuJoCo camera axes: OpenGL (x right, y up, z back)
+ T[:3, 3] = D.cam_xpos[i]
+ return T
+
+
+def _extrinsic(cam: str) -> np.ndarray:
+ return np.linalg.inv(_cam2world_gl(cam) @ GL2CV)[:3, :]
+
+
+def camera_info(cam: str) -> dict:
+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist(),
+ "image_size": [CAM_W, CAM_H]}
+
+
+def _mount(cam: str) -> dict:
+ i = MD.camera(cam).id
+ body = MD.body(int(MD.cam_bodyid[i])).name
+ if int(MD.cam_bodyid[i]) == 0:
+ return {"type": "static", "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist()}
+ T = np.eye(4) # body -> camera (OpenGL axes), then to OpenCV axes
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.cam_quat[i])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.cam_pos[i]
+ return {"type": "link", "parent_link": body, "link_T_cam_cv": (T @ GL2CV).tolist()}
+
+
+def _mounted(cam: str) -> str:
+ if cam.startswith("handcam"):
+ side = "the right" if cam.endswith("_right") else "the left" if cam.endswith("_left") else "the"
+ return f"on {side} hand's mount (moves with the hand)"
+ return {"front": "static, across the table, facing the robot", "back": "static, behind the robot, looking over the table",
+ "left": "static, at the robot's left", "right": "static, at the robot's right",
+ "top0": "static, above the table, looking down"}.get(cam, "static")
+
+
+# ------------------------------------------------------------------------------------------------- kinematics
+KD = mujoco.MjData(MD) # kinematics only: never stepped; the robot's joints are set, everything else stays put
+ARM_QI = {a: [JOINTS.index(j) for j in ARM_JOINTS[a]] for a in ARMS}
+
+
+def _fk(q) -> None:
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR] = np.asarray(q, dtype=np.float64)
+ mujoco.mj_kinematics(MD, KD)
+
+
+def _link_pose(name: str) -> list:
+ for a in ARMS:
+ if name == TCP[a]:
+ s = TCP_SITE[a]
+ return [*KD.site_xpos[s].tolist(), *_quat(KD.site_xmat[s]).tolist()]
+ b = MD.body(name).id
+ return [*KD.xpos[b].tolist(), *KD.xquat[b].tolist()]
+
+
+def tcp_from_arm_joints(a: str, q7) -> np.ndarray:
+ """The tcp pose (xyz + wxyz) of arm `a` with its 7 joints at q7 (the joint_position action's tcp target)."""
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR[ARM_QI[a]]] = q7
+ mujoco.mj_kinematics(MD, KD)
+ s = TCP_SITE[a]
+ return np.concatenate([KD.site_xpos[s], _quat(KD.site_xmat[s])])
+
+
+def do_kinematics(req: dict) -> dict:
+ """World frame. FK: every link of spec kinematics.links for q. IK: per tcp target, damped least squares over that
+ arm's 7 joints (position and orientation), within the joint ranges; the hand joints are taken from the seed."""
+ if req["op"] == "fk":
+ _fk(req["q"])
+ return L.fk_response({n: _link_pose(n) for n in req["links"]}, "world")
+ q = np.array(req["seed"] if req["seed"] is not None else D.qpos[QADR], dtype=np.float64)
+ errors = {}
+ jp, jr = np.zeros((3, MD.nv)), np.zeros((3, MD.nv))
+ for frame, pose in req["targets"].items():
+ a = next(x for x in ARMS if TCP[x] == frame)
+ idx = ARM_QI[a]
+ dofs = VADR[idx]
+ tp, tq = np.asarray(pose[:3]), np.asarray(pose[3:7])
+ lo = np.array([JLIM[JOINTS[i]][0] for i in idx]); hi = np.array([JLIM[JOINTS[i]][1] for i in idx])
+ for _ in range(req["max_iters"]):
+ _fk(q)
+ mujoco.mj_comPos(MD, KD) # the Jacobian needs cdof, which mj_kinematics alone leaves stale
+ s = TCP_SITE[a]
+ ep = tp - KD.site_xpos[s]
+ cq = _quat(KD.site_xmat[s])
+ dq = np.zeros(4); neg = np.zeros(4); er = np.zeros(3)
+ mujoco.mju_negQuat(neg, cq); mujoco.mju_mulQuat(dq, tq, neg); mujoco.mju_quat2Vel(er, dq, 1.0)
+ if np.linalg.norm(ep) < req["tol_pos_m"] and np.linalg.norm(er) < req["tol_rot_rad"]:
+ break
+ mujoco.mj_jacSite(MD, KD, jp, jr, s)
+ J = np.vstack([jp[:, dofs], jr[:, dofs]])
+ err = np.concatenate([ep, er])
+ step = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), err)
+ q[idx] = np.clip(q[idx] + step, lo, hi)
+ _fk(q)
+ s = TCP_SITE[a]
+ errors[frame] = (float(np.linalg.norm(tp - KD.site_xpos[s])), L.quat_angle(_quat(KD.site_xmat[s]), tq / np.linalg.norm(tq)))
+ ok = all(e[0] <= req["tol_pos_m"] and e[1] <= req["tol_rot_rad"] for e in errors.values())
+ return L.ik_response(q, ok, errors, "world", note="the tcp (attachment_site) of each arm; the hand joints are the seed's")
+
+
+# ------------------------------------------------------------------------------------------------- spec
+def _joint_spec(a: str) -> list:
+ out = []
+ for j, ai in zip(ARM_JOINTS[a], ARM_CTRL[a]):
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_ctrlrange[ai][1]), "group": f"{a}_arm"})
+ for j, ai in zip(HAND_JOINTS[a], HAND_CTRL[a]):
+ fl = bool(MD.actuator_forcelimited[ai]) and float(MD.actuator_forcerange[ai][1]) > 0
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_forcerange[ai][1]) if fl else None, "group": f"{a}_hand"})
+ return out
+
+
+def _tcp_spec(a: str) -> dict:
+ s = TCP_SITE[a]
+ T = np.eye(4)
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.site_quat[s])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.site_pos[s]
+ return {"parent_link": MD.body(int(MD.site_bodyid[s])).name, "link_T_frame": T.tolist(),
+ "definition": "DexJoCo's attachment_site: the flange where the Allegro hand is mounted, the point its "
+ "operational-space controller drives to the ee_pose target (not the fingertips)"}
+
+
+def _base(a: str) -> list:
+ b = D.body(f"link0{SFX[a]}")
+ return [*np.round(b.xpos, 6).tolist(), *np.round(b.xquat, 6).tolist()]
+
+
+GAINS = {}
+for _a in ARMS:
+ for _j, _ai in zip(HAND_JOINTS[_a], HAND_CTRL[_a]):
+ GAINS[_j] = {"stiffness": float(MD.actuator_gainprm[_ai][0]), "damping": float(MD.dof_damping[MD.jnt_dofadr[MD.joint(_j).id]])}
+ROBOT_NAME = "franka-allegro-bimanual" if BIM else "franka-allegro"
+try:
+ TASK_TEXT = open(TASK_TEXT_FILE).read().strip()
+except OSError:
+ TASK_TEXT = f"DexJoCo {TASK}"
+SPEC = {
+ "protocol": L.PROTOCOL,
+ "protocol_compat": list(L.COMPAT),
+ "simulator": "DexJoCo @ 8d23b0f on MuJoCo 3.4.0 (CPU physics, OSMesa rendering)",
+ "robot": ROBOT_NAME,
+ "task_text": TASK_TEXT,
+ "control_hz": CTRL_HZ,
+ "physics_substeps": SUBSTEPS,
+ "physics_hz": CTRL_HZ * SUBSTEPS,
+ "max_chunk_s": MAX_CHUNK_S,
+ "max_watch_s": MAX_WATCH_S,
+ "cameras": {c: {"rgb": True, "depth": True, "mounted": _mounted(c), "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),
+ "mount": _mount(c)} for c in CAMS},
+ "default_cameras": DEFAULT_CAMS,
+ "action_types": {
+ "ee_pose": {
+ "dim": ADIM, "layout": EE_LAYOUT,
+ "units": "per arm (right first): tcp target position (m, world frame), tcp target orientation (quaternion wxyz), "
+ "16 Allegro joint targets (rad)",
+ "frame": "world", "quaternion_order": "wxyz", "ee_frames": [TCP[a] for a in ARMS],
+ "hand_limits": {j: ALIM[j] for a in ARMS for j in HAND_JOINTS[a]},
+ "semantics": "DexJoCo's own action row. The arm tracks the tcp target through DexJoCo's operational-space "
+ "controller (it lags a moving target and stops where contact blocks it); the hand joints are "
+ "position-controlled. Rows are `dt` apart (a whole multiple of 1/50 s, at most 0.5 s); between rows "
+ "positions and joints move linearly and orientations by slerp (`linear`) or jump (`hold`); a row's "
+ "own values land exactly on its last control step. Hand targets outside the ranges are clamped by "
+ "the simulator and reported in `clipped`; a zero quaternion is a 400.",
+ },
+ "joint_position": {
+ "dim": ADIM, "layout": JP_LAYOUT, "units": "rad", "limits": {j: ALIM[j] for j in JP_LAYOUT},
+ "semantics": "per arm (right first): 7 Panda joint targets, then the 16 Allegro joint targets. The arm's "
+ "targets are turned into a tcp target by forward kinematics (as POST /kinematics fk) and the arm "
+ "tracks that pose through the same operational-space controller as ee_pose, whose null space "
+ "pulls towards DexJoCo's home posture: the tcp reaches FK(q), the measured joints may differ from q "
+ "in the arm's redundant direction. Rows `dt` apart, `linear` (in joint space) or `hold`; values "
+ "outside the limits are clipped and reported.",
+ },
+ "not_yet": ["joint_delta", "joint_velocity", "ee_delta", "joint_torque"],
+ },
+ "proprio_layout": PROPRIO_LAYOUT,
+ "proprio_groups": PROPRIO_GROUPS,
+ "static": {},
+ "world": {"frame": "DexJoCo's world frame: z up, metres; the robot" + ("s stand" if BIM else " stands")
+ + " at low x and reach" + ("" if BIM else "es") + " towards +x"
+ + (" (right arm at y < 0, left arm at y > 0)" if BIM else ""),
+ "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},
+ "episode": "one episode, no reset: it ends at the first success, at a task failure (see task_text), or when your time is over",
+ "robot_spec": {
+ "name": ROBOT_NAME,
+ "description": ("two Franka Panda arms side by side, each with a 16-DoF Allegro hand (right arm first)" if BIM
+ else "a Franka Panda arm with a 16-DoF Allegro hand"),
+ "base": {"type": "fixed", "pose": _base(ARMS[0]), **({"per_arm": {a: _base(a) for a in ARMS}} if BIM else {}),
+ "note": "pose of the arm's base link (link0), world frame, x y z + quaternion wxyz"},
+ "joints": [j for a in ARMS for j in _joint_spec(a)],
+ "grippers": {},
+ "controller": {"type": "arm: operational-space control of the tcp (torques); hand: joint position actuators",
+ "control_hz": CTRL_HZ, "physics_hz": CTRL_HZ * SUBSTEPS, "gains": GAINS,
+ "note": "arm: DexJoCo's opspace controller drives attachment_site to the tcp target (position gains "
+ "400 N/m, damping ratio 4, gravity compensation, null space towards the home posture), "
+ "torques limited to effort_limit; hand: position actuators (stiffness N m/rad) on joints "
+ "with their own damping (N m s/rad)"},
+ "tcp": {TCP[a]: _tcp_spec(a) for a in ARMS},
+ },
+ "kinematics": {"endpoint": "/kinematics", "joint_names": JOINTS, "frame": "world", "quaternion_order": "wxyz",
+ "links": KIN_LINKS, "tcp_frames": [TCP[a] for a in ARMS], "ee_frames": [TCP[a] for a in ARMS],
+ "ik_targets": [TCP[a] for a in ARMS], "ik": {"tol_pos_m": 0.001, "tol_rot_rad": 0.01, "max_iters": 300},
+ "note": "the arm links, the hand mount (the hand cameras' parent) and the tcp, world frame; ik solves "
+ "each tcp target over that arm's 7 joints"},
+ "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()
+
+
+# ------------------------------------------------------------------------------------------------- state and frames
+def ctrl_steps() -> int:
+ return int(S.steps)
+
+
+def proprio_row() -> np.ndarray:
+ tcp, tgt, hand = [], [], []
+ for a in ARMS:
+ s = TCP_SITE[a]
+ tcp += [D.site_xpos[s], _quat(D.site_xmat[s])]
+ t = S._arm_target(a)
+ tgt.append(t[:7]); hand.append(t[7:23])
+ return np.concatenate([D.qpos[QADR], D.qvel[VADR], D.actuator_force[EFF_ACT], *tcp, *tgt, *hand]).astype(np.float32)
+
+
+def grab(cams, want_depth: bool):
+ rgb, dep = {}, {}
+ for c in cams:
+ rgb[c] = S.render_frame(c, (CAM_H, CAM_W))
+ if want_depth:
+ r = S._renderer # the one renderer (a second OSMesa context reads back garbage)
+ r.enable_depth_rendering()
+ try:
+ r.update_scene(D, camera=c)
+ dep[c] = r.render().astype(np.float32).copy()
+ finally:
+ r.disable_depth_rendering()
+ return rgb, dep
+
+
+def extrinsics(cams) -> dict:
+ return {c: _extrinsic(c) for c in cams}
+
+
+def summary() -> dict:
+ n = int(E.get("episode_control_steps") or ctrl_steps())
+ 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"],
+ "task": TASK, "protocol": L.PROTOCOL, "n_actions": len(ROWS), "task_failure": int(str(E["reason"] or "").startswith("failure")),
+ **EP.final_fields()}
+
+
+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 finish(reason: str) -> None:
+ """The episode is over: record the live verdict and dump the trajectory 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()
+ E["success"] = bool(S.success)
+ 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()
+ S.save_trajectory(np.asarray(ROWS, dtype=np.float64).reshape(-1, ADIM), os.path.join(DATA, "trajectory.npz"),
+ {"source": "standard-mode episode", "reason": E["reason"]})
+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})
+ write_final()
+
+
+def ctrl_step(a, rec) -> bool:
+ """One executed control step (DexJoCo's own row), journaled. True when the call must stop here."""
+ a = np.asarray(a, dtype=np.float64)
+ running = S.step(a)
+ ROWS.append(a.copy())
+ stop = EP.journal(a)
+ rec.tick()
+ if not running:
+ finish(S.reason or "done")
+ 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 DEFAULT_CAMS
+ if not isinstance(cams, list) or any(c not in CAMS for c in cams):
+ raise ValueError(f"unknown cameras {cams}; cameras: {CAMS}")
+ return list(dict.fromkeys(cams))
+
+
+def meta_common(cams) -> dict:
+ n = ctrl_steps()
+ return {"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}}
+
+
+def _native_from_ee(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ """ee_pose rows are executed as sent (the recorded row is what the agent commanded); hand targets outside the
+ actuator ranges are clamped by MuJoCo itself (ctrllimited) and only reported."""
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ if float(np.linalg.norm(row[o + 3:o + 7])) < 1e-6:
+ raise ValueError(f"row {ri}: the {a} tcp quaternion has zero norm")
+ for j in range(16):
+ lo, hi = HLIM[a][j]
+ v = row[o + 7 + j]
+ if v < lo or v > hi:
+ clipped.append({"row": ri, "index": int(o + 7 + j), "reason": f"{EE_LAYOUT[o + 7 + j]} outside [{lo:.3f}, {hi:.3f}]: clamped by the simulator"})
+ return row
+
+
+def _clip_joints(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ lo = np.array([ALIM[j][0] for j in JP_LAYOUT]); hi = np.array([ALIM[j][1] for j in JP_LAYOUT])
+ out = np.clip(row, lo, hi)
+ for j in np.flatnonzero(out != row)[:20]:
+ clipped.append({"row": ri, "index": int(j), "reason": f"{JP_LAYOUT[j]} limit [{lo[j]:g}, {hi[j]:g}]"})
+ return out
+
+
+def _native_from_joints(q: np.ndarray) -> np.ndarray:
+ out = []
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ out += [tcp_from_arm_joints(a, q[o:o + 7]), q[o + 7:o + 23]]
+ return np.concatenate(out)
+
+
+def _check_chunk(typ: str, A: np.ndarray, dt: float, interp: str, video: str) -> int:
+ k = dt / DT
+ if A.ndim != 2 or A.shape[1] != ADIM:
+ raise ValueError(f"{typ} actions must be (T, {ADIM}), got {list(A.shape)}")
+ if A.shape[0] == 0:
+ raise ValueError("no rows")
+ 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")
+ return int(round(k))
+
+
+def do_submit(meta: dict, A: np.ndarray):
+ typ = meta.get("type")
+ if typ not in ("ee_pose", "joint_position"):
+ raise ValueError(f"type must be ee_pose or joint_position (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)
+ n = _check_chunk(typ, A, dt, interp, video)
+ clipped: list = []
+ if typ == "ee_pose":
+ A = np.stack([_native_from_ee(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ else:
+ A = np.stack([_clip_joints(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ rec = recorder(cams, fps, meta)
+ E["calls"] += 1
+ step0, before = E["step"], ctrl_steps()
+ rec.tick(force=True)
+ if typ == "ee_pose":
+ prev = np.asarray(S.hold_action(), dtype=np.float64)
+ else:
+ prev = np.concatenate([np.concatenate([D.qpos[QADR[ARM_QI[a]]], S._arm_target(a)[7:23]]) for a in ARMS])
+ for row in A:
+ E["step"] += 1
+ stop = False
+ for s in range(1, n + 1):
+ if interp == "hold" or s == n:
+ target = row # a row's own values land exactly on its last control step
+ else:
+ target = prev + (row - prev) * (s / n)
+ if typ == "ee_pose":
+ for k in range(len(ARMS)):
+ o = 23 * k
+ target[o + 3:o + 7] = M.quat_slerp(prev[o + 3:o + 7], row[o + 3:o + 7], s / n)
+ native = target if typ == "ee_pose" else _native_from_joints(target)
+ if ctrl_step(native, rec):
+ stop = True
+ break
+ prev = row
+ 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"], "type": typ, "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 = np.asarray(S.hold_action(), dtype=np.float64)
+ 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={"task": TASK, "instance_sha": S.instance_sha, "instance_ok": bool(S.instance_exact), "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} DexJoCo sim ready ({TASK}; 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/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/task_text.txt b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/task_text.txt
new file mode 100644
index 0000000000..1c82a5f2cf
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/environment/sim/task_text.txt
@@ -0,0 +1,3 @@
+Open the microwave door, put the hot dog inside, close the door and press the start button. Success, at one control step: the hot dog is inside the cavity (1 cm margin), the door hinge is within 0.01 rad of closed, and the start button is in contact with something.
+
+The microwave stands on the table with its door closed; the hot dog lies in front of it. The door has a handle and a hinge (`door_hinge`); the start and stop buttons are on the front panel.
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-standard/instruction.md b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/instruction.md
new file mode 100644
index 0000000000..2e8efd003b
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/instruction.md
@@ -0,0 +1,68 @@
+# DexJoCo · bimanual_microwave_cook — STANDARD MODE (robot as a service, eai-standard/2.2)
+
+You control two Franka Panda arms, each with a 16-DoF Allegro hand, **as if it were real hardware**: the simulator runs in a service you cannot open. You get
+one client and one episode. **Task:** Open the microwave door, put the hot dog inside, close the door and press the start button. Success, at one control step: the hot dog is inside the cavity (1 cm margin), the door hinge is within 0.01 rad of closed, and the start button is in contact with something.
+
+The microwave stands on the table with its door closed; the hot dog lies in front of it. The door has a handle and a hinge (`door_hinge`); the start and stop buttons are on the front panel.
+
+## Rules (real-robot rules)
+- **No reset.** The episode starts when the service comes up and ends on success, on a task failure (see the task), when
+ your time is up, or on a simulator error. Knocked-over objects stay knocked over.
+- **No privileged state.** You see what the cameras see (RGB, and depth on request, with each camera's calibration) plus
+ the robot's own proprioception (joints, tcp poses, the current targets). No object poses, no success check:
+ `meta["done"]` / `meta["reason"]` tell you when the episode is over and why.
+- Steps are unlimited; your wall-clock budget (90 minutes) is the limit (`meta["time_left_s"]`). Actions and
+ simulated time are reported as cost. Do not stop before the task is solved.
+- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
+ `/app/output/gen.py` for the record (save it early, update it as you go).
+- **Nothing is put into your context automatically.** Images and videos come back as arrays/bytes in a Python object;
+ what you look at and where you store it is your code's decision.
+
+## Client (`/opt/tools/rcb_client.py`, protocol `eai-standard/2.2`)
+```python
+from rcb_client import Robot
+r = Robot() # connects (waits while the service starts)
+spec = r.spec() # action types, cameras (+ calibration), proprio layout, robot_spec, kinematics, budget
+obs = r.get_obs() # current frames of spec["default_cameras"]: obs.last[cam] -> uint8 (480, 640, 3)
+obs = r.get_obs(cameras=["back", "handcam_rgb_right"], depth=True) # + obs.last_depth[cam] -> float32 (480, 640) z-depth (m)
+obs.meta["proprio"] # {"layout": [...], "now": [...]}; obs.group("tcp_pose", now=True)
+obs.meta["cameras"] # per camera intrinsic_cv / extrinsic_cv / cam2world_gl for these frames
+obs = r.get_obs(seconds=2.0, video="mp4") # hold the current targets and watch for 2 s (max 30): obs.video[cam] = mp4 bytes
+
+res = r.submit("ee_pose", rows, dt=0.1) # rows: (T, 46) targets dt seconds apart, executed at 50 Hz with interpolation
+res = r.submit("joint_position", q_rows, dt=0.1) # (T, 46) joint targets instead (see below)
+res.meta["done"], res.meta["reason"], res.meta["clipped"], res.meta["control_steps_chunk"]
+res.video["back"]; res.last["back"]; res.proprio # mp4 of the chunk, last frame, float32 (N, P) proprio per frame
+res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, proprio.npy, ...
+r.fk(q); r.ik({"tcp_right": pose}, seed=q) # kinematics of the robot (stateless: no physics, no time)
+r.status() # calls, control steps, done, reason, elapsed time
+```
+Cameras: `back` (static), `handcam_rgb_right`, `handcam_rgb_left` (on the hand mounts; they move,
+so use the calibration that comes with each response; `spec["cameras"][cam]["mount"]` gives the static pose or the mount
+link). Resolution 640x480. Rendering runs on the CPU: ask only for the cameras you need; `video="none"` makes a chunk
+fastest. If a call fails with a connection error the service may have crashed: it resumes the same episode;
+`r.wait_ready()`, then check `r.status()` (`spec["on_service_error"]`).
+
+### Action type `ee_pose` (46) — DexJoCo's own action
+Per arm, right first: tcp target position (3, metres, world frame), tcp target orientation (4, quaternion wxyz), 16
+Allegro joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+target and stops where contact blocks it); the hand joints are position-controlled. Rows are `dt` apart (a whole multiple
+of 1/50 s, at most 0.5 s); between rows positions and joints move linearly and orientations by slerp
+(`interpolate="linear"`) or jump (`"hold"`); a chunk may cover at most 10 s. Hand targets outside the ranges
+(`spec["action_types"]["ee_pose"]["hand_limits"]`) are clamped by the simulator and listed in `meta["clipped"]`. Build
+the next row from the `tcp_target` and `hand_target` proprio groups to move smoothly.
+
+### Action type `joint_position` (46)
+Per arm, right first: 7 Panda joint targets, then the 16 Allegro joint targets (rad). The service turns the arm's targets
+into a tcp target by forward kinematics and the same controller tracks it: the tcp reaches FK(q), but the measured arm
+joints may differ from q in the arm's redundant direction (the controller's null space pulls towards a home posture).
+Out-of-limit values are clipped and reported.
+
+## Conventions
+- World frame, metres, z up; the robots stand at low x and reach towards +x (right arm at y < 0, left arm at y > 0); each
+ arm's base pose is in `spec["robot_spec"]["base"]`. No other world coordinates are given (D7: the cameras are
+ calibrated, depth is available). Quaternions are **WXYZ**.
+- The tcp (`tcp_right`, `tcp_left`) is the hand's mounting flange (`spec["robot_spec"]["tcp"]`), not the fingertips. Allegro joint
+ order (right hand): index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger = spread, 1-3 = flexion
+ from the knuckle out; thumb 12 = opposition). The LEFT hand's 16 values are mirrored: ring 0-3, middle 4-7, index 8-11, thumb 12-15 (the joint names in `spec["proprio_layout"]` say which).
+- Control runs at 50 Hz (10 physics substeps of 2 ms). There is no step budget: your wall-clock time is the limit.
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-standard/solution/oracle_stream.py b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/solution/oracle_stream.py
new file mode 100644
index 0000000000..19877300c1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/solution/oracle_stream.py
@@ -0,0 +1,43 @@
+"""Oracle (standard mode): streams the reference rows (the human demonstration's own actions, one per 1/50 s control step,
+float32-exact) as `ee_pose` 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
+
+A = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle_trajectory.npz"))["actions"].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(A), flush=True)
+t0, i = time.time(), 0
+while i < len(A):
+ chunk = A[i:i + per_chunk]
+ try:
+ res = r.submit("ee_pose", chunk, dt=dt, interpolate="hold", 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/dexjoco-bimanual-microwave-cook-i00-standard/solution/oracle_trajectory.npz b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..896244501e
Binary files /dev/null and b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-standard/solution/solve.sh b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/solution/solve.sh
new file mode 100755
index 0000000000..1bd55d898f
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/solution/solve.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+# Oracle (standard mode): streams the reference trajectory's rows (solution/oracle_trajectory.npz, one row per control
+# step) as `ee_pose` chunks through the client. Uses no privileged information at run time (only the pre-recorded rows);
+# the service's recorded trajectory is then exactly the privileged reference.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_stream.py /app/output/gen.py
+python /solution/oracle_stream.py
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-standard/task.toml b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/task.toml
new file mode 100644
index 0000000000..a3da412f2f
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/task.toml
@@ -0,0 +1,52 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator 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/dexjoco-bimanual-microwave-cook-i00-standard"
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): DexJoCo bimanual_microwave_cook (two Franka Panda arms, each with a 16-DoF Allegro hand) on the same frozen instance as dexjoco-bimanual-microwave-cook-i00-privileged. Open the microwave door, put the hot dog inside, close the door and press the start button. The agent only gets a client: calibrated cameras (RGB, optional depth), the robot's joints and tcp poses, tcp-target + hand-joint chunks at 50 Hz, the robot's kinematics; one episode, no reset, no object state; the sim service records the episode, replays it in fresh processes and grades it."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "standard-mode", "robot-as-a-service", "bimanual_microwave_cook"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro-bimanual"
+family = "bimanual_microwave_cook"
+mode = "standard"
+protocol = "eai-standard/2.2"
+oracle = "full"
+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 = 3600
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-standard/tests/Dockerfile b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/tests/Dockerfile
new file mode 100644
index 0000000000..26bc699ebe
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-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.sh
diff --git a/tasks/dexjoco-bimanual-microwave-cook-i00-standard/tests/grade.py b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/tests/grade.py
new file mode 100644
index 0000000000..003b933315
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/tests/grade.py
@@ -0,0 +1,60 @@
+"""Standard-mode verifier (DexJoCo): 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 frozen 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"))),
+ "task_failure": int(bool(d.get("task_failure"))),
+ "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),
+ "calls": int(d.get("calls") or 0),
+ "elapsed_s": float(d.get("elapsed_s") or 0),
+ "video_rendered": int(bool(d.get("video"))),
+ # 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 frozen 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/dexjoco-bimanual-microwave-cook-i00-standard/tests/test.sh b/tasks/dexjoco-bimanual-microwave-cook-i00-standard/tests/test.sh
new file mode 100755
index 0000000000..bc608aa8b9
--- /dev/null
+++ b/tasks/dexjoco-bimanual-microwave-cook-i00-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
diff --git a/tasks/dexjoco-bimanual-photograph-i00-privileged/README.md b/tasks/dexjoco-bimanual-photograph-i00-privileged/README.md
new file mode 100644
index 0000000000..ce4c2a3d0a
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-privileged/README.md
@@ -0,0 +1,49 @@
+# dexjoco-bimanual-photograph-i00-privileged
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | privileged |
+| Twin | `dexjoco-bimanual-photograph-i00-standard` |
+| Simulator / robot | `dexjoco` / `franka-allegro-bimanual` |
+| Family / instance | `bimanual_photograph` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `bimanual_photograph` (two Franka Panda arms, each with a 16-DoF Allegro hand): Hold the camera with the left hand in front of the logo and press its shutter with the right hand. Success, at one control step: the camera's view point is inside the target region (0.16 m radius, +-0.10 m height, 0.40 m in front of the logo along -x, i.e. about 0.3 m above the table), the camera's viewing axis is within 10 degrees of world +x, and the shutter button is touched by something other than the camera.
+Privileged mode: the agent works in the simulator's container with live object poses, unlimited resets and thin motion
+primitives, and hands in one trajectory replayed open-loop from the frozen instance.
+
+## Difficulty
+First-pass rating: hard. Dexterous manipulation with two 16-DoF hands on two arms (46 action values per control step);
+the primitives only move tcp and hand-joint targets, so grasping, pressing and every other skill is the agent's. The
+reference (the human teleoperator's demonstration) takes 260 control steps (5.2 s at 50 Hz).
+
+## Reference solution
+`solution/oracle_trajectory.npz` = the human demonstration's own actions, rounded to float32 (the standard client's
+precision; the rounded rows still succeed) and replayed from the frozen instance until the episode ends in success
+(260 rows). The demonstration is public (DexJoCo-Datasets-Raw on Hugging Face), so agent egress is
+limited to the model APIs.
+
+## Verification
+Open-loop replay of `/app/output/trajectory.npz` from `tests/instance.npz`, twice in a fresh process in the verifier's own
+sandbox (no network); pass iff both episodes end in success, their final-state hashes agree and the rebuilt instance
+matches its recorded hash (`tests/grade.py`); plus `/logs/verifier/replay.mp4`. Oracle: success after 260 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `photograph_demo_10_2026-03-16_14-31-13_305518` (DexJoCo-Datasets-Raw), restored with DexJoCo's own state restorer; instance sha `b8b1dbe8dba6c733` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Tooling notes
+DexJoCo's reset samples object poses from the global RNG and its state restorer edits the MuJoCo model (table height,
+fixed bodies), so `instance.npz` stores the full physics state (`mjSTATE_INTEGRATION`), the mocap targets, the controls,
+every numeric model array a task can change, and the env's Python-side task state. Its per-step camera rendering,
+real-time sleep, episode cap and hanoi's wall-clock auto-reset are disabled in the tooling (`rcb_dexjoco.py`).
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py` from `scripts/dexjoco/instances/bimanual_photograph/` (`make_instances.py`).
diff --git a/tasks/dexjoco-bimanual-photograph-i00-privileged/environment/Dockerfile b/tasks/dexjoco-bimanual-photograph-i00-privileged/environment/Dockerfile
new file mode 100644
index 0000000000..d736fe8a7d
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-privileged/environment/Dockerfile
@@ -0,0 +1,7 @@
+# Base image = DexJoCo on MuJoCo 3.4.0 (images/dexjoco/). Everything task-specific is copied here. CPU only.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY instance.npz /app/instance.npz
+COPY rcb_dexjoco.py /opt/tools/rcb_dexjoco.py
+ENV PYTHONPATH=/opt/tools
+RUN mkdir -p /app/output
+WORKDIR /app
diff --git a/tasks/dexjoco-bimanual-photograph-i00-privileged/environment/instance.npz b/tasks/dexjoco-bimanual-photograph-i00-privileged/environment/instance.npz
new file mode 100644
index 0000000000..6e5ca5b70e
Binary files /dev/null and b/tasks/dexjoco-bimanual-photograph-i00-privileged/environment/instance.npz differ
diff --git a/tasks/dexjoco-bimanual-photograph-i00-privileged/environment/rcb_dexjoco.py b/tasks/dexjoco-bimanual-photograph-i00-privileged/environment/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-privileged/environment/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-bimanual-photograph-i00-privileged/instruction.md b/tasks/dexjoco-bimanual-photograph-i00-privileged/instruction.md
new file mode 100644
index 0000000000..bf3241b864
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-privileged/instruction.md
@@ -0,0 +1,108 @@
+# DexJoCo · bimanual_photograph — frozen instance
+
+You control two Franka Panda arms, each with a 16-DoF Allegro hand (DexJoCo on MuJoCo 3.4) via Python. **Task:** Hold the camera with the left hand in front of the logo and press its shutter with the right hand. Success, at one control step: the camera's view point is inside the target region (0.16 m radius, +-0.10 m height, 0.40 m in front of the logo along -x, i.e. about 0.3 m above the table), the camera's viewing axis is within 10 degrees of world +x, and the shutter button is touched by something other than the camera.
+
+The camera lies on the table between the robots; the logo disk stands at the far side of the table. `s.objects()` gives the live poses of the task objects (`camera`, `view_point`, `shutter`, `logo`, `target_region`, `table_top`). DexJoCo's success code (from
+`/opt/dexjoco/dexjoco/dexjoco/sim/envs/panda_bimanual_photograph_env.py`; `step()` ends the episode on success or on a task failure):
+```python
+def _compute_success(self) -> bool:
+ success, _ = self._compute_success_metrics()
+ return bool(success)
+
+def _compute_success_metrics(self) -> Tuple[bool, Dict[str, Any]]:
+ region_center = self._data.geom_xpos[self._target_region_geom_id].copy()
+ region_rot = self._data.geom_xmat[self._target_region_geom_id].reshape(3, 3)
+ view_pos = self._data.site_xpos[self._view_site_id].copy()
+ delta_local = region_rot.T @ (view_pos - region_center)
+ radial_dist = float(np.linalg.norm(delta_local[:2]))
+ region_height_dist = float(abs(delta_local[2]))
+ region_pass = radial_dist <= _TARGET_REGION_RADIUS and region_height_dist <= _TARGET_REGION_HALF_HEIGHT
+
+ axis_z_world = self._data.geom_xmat[self._camera_axis_z_geom_id].reshape(3, 3)[:, 2].copy()
+ axis_z_norm = float(np.linalg.norm(axis_z_world))
+ if axis_z_norm < 1e-8:
+ axis_z_world = np.array([0.0, 0.0, 1.0], dtype=np.float64)
+ else:
+ axis_z_world = axis_z_world / axis_z_norm
+
+ cos_val = float(np.clip(np.dot(axis_z_world, _WORLD_POS_X), -1.0, 1.0))
+ angle_deg = float(np.degrees(np.arccos(cos_val)))
+ angle_pass = angle_deg <= _TARGET_ANGLE_DEG
+
+ shutter_pressed = False
+ shutter_contact_count = 0
+ ncon = int(self._data.ncon)
+ for i in range(ncon):
+ c = self._data.contact[i]
+ g1 = int(c.geom1)
+ g2 = int(c.geom2)
+ if g1 == self._shutter_geom_id:
+ if g2 not in self._camera_geom_ids:
+ shutter_pressed = True
+ shutter_contact_count += 1
+ elif g2 == self._shutter_geom_id:
+ if g1 not in self._camera_geom_ids:
+ shutter_pressed = True
+ shutter_contact_count += 1
+
+ success = region_pass and angle_pass and shutter_pressed
+ return bool(success), {
+ "region_pass": bool(region_pass),
+ "angle_pass": bool(angle_pass),
+ "shutter_pressed": bool(shutter_pressed),
+ "radial_dist": radial_dist,
+ "region_height_dist": region_height_dist,
+ "view_angle_deg": angle_deg,
+ "shutter_contact_count": int(shutter_contact_count),
+ }
+```
+
+This is a *fixed scene instance*: object poses, the table height and the robot's start pose never change between
+resets. You may reset and retry as many times as you want. Your deliverable is **one replayable trajectory**, not a
+general policy.
+
+## Deliverable
+Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
+open-loop from the same initial state in a fresh process and scored 1 if its episode ends in success, else 0. Also
+leave the script that produced it at `/app/output/gen.py`. You have 90 minutes of wall clock: save a
+first trajectory early, improve it, and do not stop before the task is solved.
+
+## Tooling (already installed; run `python` from any directory)
+```python
+from rcb_dexjoco import Session
+s = Session("bimanual_photograph", instance="/app/instance.npz") # ~1 s: builds the env and loads the frozen state
+s.reset() # back to the frozen initial state (as often as you like; an exact snapshot restore)
+s.objects() # live task objects: name -> pos, quat_wxyz (bodies) / pos (sites) / qpos (joints)
+s.state() # DexJoCo's state dict: tcp_pose, gripper_pose (hand joints), INITIAL object poses, table height
+p = s.primitives() # thin wrappers of the low-level action; each has a docstring: help(p["move_ee"])
+p["move_ee"]("right", pos, quat_wxyz) # straight-line + slerp motion of an arm's tcp target, then settle
+p["set_hand"]("right", q16) # interpolate the 16 Allegro joint targets
+p["hold"](10); p["set_targets"](row, steps) # keep every target / send one raw action row
+p["get_ee_pose"]("right"); p["get_ee_target"]("right"); p["get_hand"]("right"); p["get_body_pose"](name)
+s.render_frame("front") # RGB uint8 (480, 640, 3); cameras: ['front', 'back', 'left', 'right', 'top0', 'handcam_rgb_right', 'handcam_rgb_left', 'cam_pos_z']; s.render_grid()
+s.step(action) # one control step (46 values, below) = 1/50 s; returns False once the episode is over
+s.record_start(); ...; actions = s.record_stop() # (T, 46) actions, one row per control step
+s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+s.replay(actions) # resets, replays open-loop until the episode ends, returns status -> self-check
+s.save_trajectory(actions, "/app/output/trajectory.npz")
+s.render_video(actions, "/app/output/check.mp4", cameras=["front"]) # replays from the frozen state into a video
+```
+The primitives are deliberately thin (tcp target moves, hand joint targets, hold): grasping, pressing, striking and
+every other skill are yours to build from them. `s.bodies()` lists every MuJoCo body for `p["get_body_pose"]`.
+
+CLI equivalent of the grader:
+`python /opt/tools/rcb_dexjoco.py replay --task bimanual_photograph --instance /app/instance.npz --traj /app/output/trajectory.npz`
+
+## Conventions
+- World frame, metres; z up; the robots stand at low x and reach towards +x. The table top is at z = 0.930. Arm base (`link0`): link0_right [-0.75, -0.4, 0.924], link0_left [-0.75, 0.4, 0.924]. The right arm works at y < 0, the left arm at y > 0. Quaternions are **WXYZ**.
+- Action (46): per arm, right first: tcp target position (3), tcp target orientation (4, wxyz), 16 Allegro
+ joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+ target and stops where contact blocks it); the hand joints are position-controlled. `s.hold_action()` is the no-op.
+ At the start the tcp target is right [-0.443, -0.4, 1.517] / [0.0, -1.0, 0.0, -0.0025], left [-0.443, 0.4, 1.517] / [0.0, -1.0, 0.0, -0.0025].
+- Allegro joint order (right hand): index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger =
+ spread, 1-3 = flexion from the knuckle out; thumb 12 = opposition). The LEFT hand's 16 values are mirrored: ring 0-3, middle 4-7, index 8-11, thumb 12-15.
+ Target ranges (rad, same for every finger slot, thumb last): low [-0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, 0.26, -0.1, -0.19, -0.16], high [0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 1.4, 1.16, 1.64, 1.72]; the simulator clamps
+ targets to them.
+- Control runs at 50 Hz (10 physics substeps of 2 ms). DexJoCo's own episode cap and real-time pacing are lifted: there
+ is no step budget, your wall-clock time is the limit (~180 control steps/s here). An episode ends at the
+ first success or task failure; `s.step` then refuses further actions until `s.reset()`.
diff --git a/tasks/dexjoco-bimanual-photograph-i00-privileged/solution/gen.py b/tasks/dexjoco-bimanual-photograph-i00-privileged/solution/gen.py
new file mode 100644
index 0000000000..0e1f7e3bc7
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-privileged/solution/gen.py
@@ -0,0 +1,4 @@
+# How solution/oracle_trajectory.npz was made (scripts/dexjoco/make_instances.py): the DexJoCo human demonstration's
+# own actions (replay.zarr data/action), rounded to float32, replayed from the frozen instance with Session.replay until
+# the episode ended in success (holding the last row a few steps where the rounded rows ended short of a hold count),
+# truncated there and saved with Session.save_trajectory.
diff --git a/tasks/dexjoco-bimanual-photograph-i00-privileged/solution/oracle_trajectory.npz b/tasks/dexjoco-bimanual-photograph-i00-privileged/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..7468c2f0df
Binary files /dev/null and b/tasks/dexjoco-bimanual-photograph-i00-privileged/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-bimanual-photograph-i00-privileged/solution/solve.sh b/tasks/dexjoco-bimanual-photograph-i00-privileged/solution/solve.sh
new file mode 100755
index 0000000000..7909c90cb8
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-privileged/solution/solve.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+# Reference solution: the human demonstration's actions (float32), replayed through the task tooling until success.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_trajectory.npz /app/output/trajectory.npz
+cp /solution/gen.py /app/output/gen.py
diff --git a/tasks/dexjoco-bimanual-photograph-i00-privileged/task.toml b/tasks/dexjoco-bimanual-photograph-i00-privileged/task.toml
new file mode 100644
index 0000000000..044e9cbca7
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-privileged/task.toml
@@ -0,0 +1,37 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator or the instance, not this.
+schema_version = "1.3"
+artifacts = ["/app/output/"]
+
+[task]
+name = "robot-coding-bench/dexjoco-bimanual-photograph-i00-privileged"
+description = "DexJoCo bimanual_photograph (two Franka Panda arms, each with a 16-DoF Allegro hand, MuJoCo): produce one replayable trajectory. Hold the camera with the left hand in front of the logo and press its shutter with the right hand. Frozen scene instance (the initial state of a DexJoCo human demonstration)."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "code-as-policy", "trajectory", "bimanual_photograph"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro-bimanual"
+family = "bimanual_photograph"
+mode = "privileged"
+oracle = "full"
+expert_time_estimate_hours = 2.5
+
+[verifier]
+timeout_sec = 1800.0
+environment_mode = "separate" # the verifier runs in its own sandbox (tests/Dockerfile); the agent container is gone by then
+network_mode = "no-network"
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
+
+[verifier.environment]
+build_timeout_sec = 1800.0
diff --git a/tasks/dexjoco-bimanual-photograph-i00-privileged/tests/Dockerfile b/tasks/dexjoco-bimanual-photograph-i00-privileged/tests/Dockerfile
new file mode 100644
index 0000000000..a2620a4da8
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-privileged/tests/Dockerfile
@@ -0,0 +1,8 @@
+# Separate verifier sandbox (PROTOCOL §2.6): the same simulator image with the verifier's own copies of the tooling and
+# the frozen instance baked in. Nothing the agent did in its container reaches this one: Harbor uploads only the declared
+# artifacts (/app/output/), so a patched success check in the agent container cannot count.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY grade.py instance.npz rcb_dexjoco.py test.sh /tests/
+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
+ENV PYTHONPATH=/tests
+WORKDIR /tests
diff --git a/tasks/dexjoco-bimanual-photograph-i00-privileged/tests/grade.py b/tasks/dexjoco-bimanual-photograph-i00-privileged/tests/grade.py
new file mode 100644
index 0000000000..ad916e8bb9
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-privileged/tests/grade.py
@@ -0,0 +1,109 @@
+"""Verifier entry point for the privileged DexJoCo tasks: replay /app/output/trajectory.npz from the frozen instance and
+write Harbor rewards.
+
+ python /tests/grade.py --family water_plant --instance /tests/instance.npz --traj /app/output/trajectory.npz
+
+Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only; Harbor rejects strings), a replay video
+/logs/verifier/replay.mp4 (front camera + wrist camera) and replay.last.png. Replays `--repeat` times in this fresh
+process; success requires every replay to end its episode in success (DexJoCo's own rule: the episode ends at the first
+success or task failure) AND all final-state hashes to agree (MuJoCo on the CPU is bit-deterministic), and the frozen
+instance rebuilt here from tests/instance.npz must match its recorded hash.
+"""
+from __future__ import annotations
+import argparse, json, os, sys, time, traceback
+import numpy as np
+
+LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")
+
+
+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 self_reported_cost() -> dict:
+ # From the tooling's append-only log in the agent's container: SELF-REPORTED accounting, never evidence.
+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_records": 0, "agent_replays": 0,
+ "agent_cost_self_reported": 1}
+ try:
+ with open("/app/output/rcb_session_log.jsonl") 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 == "session_end": cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)
+ elif ev == "record": cost["agent_records"] += 1
+ elif ev == "replay": cost["agent_replays"] += 1
+ except Exception: # noqa: BLE001 — one bad line must not sink the verdict
+ continue
+ except Exception: # noqa: BLE001
+ pass
+ return cost
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--family", required=True); ap.add_argument("--instance", required=True)
+ ap.add_argument("--traj", default="/app/output/trajectory.npz"); ap.add_argument("--repeat", type=int, default=2)
+ ap.add_argument("--no-video", action="store_true")
+ a = ap.parse_args()
+ cost = self_reported_cost()
+ os.environ["RCB_SESSION_LOG"] = "" # the verifier's own sessions are not the agent's cost
+ if not os.path.isfile(a.traj):
+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost}); return 0
+ s = None
+ try:
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the verifier's own copy of the tooling
+ import rcb_dexjoco
+ rcb_dexjoco.SESSION_LOG = ""
+ from rcb_dexjoco import Session, MAX_STEPS
+ d = np.load(a.traj, allow_pickle=False)
+ if str(d["task"]) != a.family:
+ write(False, {"success": 0, "wrong_family": 1, "grader_error": 0, **cost}); return 0
+ acts = np.asarray(d["actions"], dtype=np.float64)
+ s = Session(a.family, instance=a.instance)
+ if (acts.ndim != 2 or acts.shape[1] != s.action_dim or acts.shape[0] > MAX_STEPS
+ or not np.all(np.isfinite(acts))):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0,
+ "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0, **cost}); return 0
+ t0 = time.time()
+ outs = []
+ for _ in range(a.repeat):
+ try:
+ outs.append(s.replay(acts))
+ except (ValueError, rcb_dexjoco.PrimitiveError):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0, "n_actions": int(len(acts)), **cost}); return 0
+ all_success = all(o["success"] for o in outs)
+ deterministic = len({o["state_sha"] for o in outs}) == 1
+ instance_ok = bool(s.instance_exact)
+ ok = all_success and deterministic and instance_ok
+ out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
+ "instance_ok": int(instance_ok), "n_actions": int(len(acts)), "sim_steps": int(outs[0]["steps"]),
+ "task_failure": int(bool(outs[0]["reason"]) and not outs[0]["success"]),
+ "replay_wall_s": round(time.time() - t0, 1), "grader_error": 0, "video_rendered": 0, **cost}
+ if not a.no_video: # human-viewable replay (never affects the verdict)
+ try:
+ n = int(outs[0]["replayed_rows"])
+ s.render_video(acts[:n], os.path.join(LOG_DIR, "replay.mp4"), cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ import imageio.v2 as imageio
+ imageio.imwrite(os.path.join(LOG_DIR, "replay.last.png"), s.render_frame(s.default_camera(), (480, 640)))
+ out["video_rendered"] = int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4")))
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(ok, out)
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(False, {"success": 0, "grader_error": 1, **cost})
+ finally:
+ if s is not None:
+ s.close()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tasks/dexjoco-bimanual-photograph-i00-privileged/tests/instance.npz b/tasks/dexjoco-bimanual-photograph-i00-privileged/tests/instance.npz
new file mode 100644
index 0000000000..6e5ca5b70e
Binary files /dev/null and b/tasks/dexjoco-bimanual-photograph-i00-privileged/tests/instance.npz differ
diff --git a/tasks/dexjoco-bimanual-photograph-i00-privileged/tests/rcb_dexjoco.py b/tasks/dexjoco-bimanual-photograph-i00-privileged/tests/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-privileged/tests/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-bimanual-photograph-i00-privileged/tests/test.sh b/tasks/dexjoco-bimanual-photograph-i00-privileged/tests/test.sh
new file mode 100755
index 0000000000..6d38f6a118
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-privileged/tests/test.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in a fresh process.
+# 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/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)
+mkdir -p /logs/verifier
+python /tests/grade.py --family bimanual_photograph --instance /tests/instance.npz --traj /app/output/trajectory.npz --repeat 2 \
+ 2> /logs/verifier/grade.log
diff --git a/tasks/dexjoco-bimanual-photograph-i00-standard/README.md b/tasks/dexjoco-bimanual-photograph-i00-standard/README.md
new file mode 100644
index 0000000000..c4d23d410b
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-standard/README.md
@@ -0,0 +1,45 @@
+# dexjoco-bimanual-photograph-i00-standard
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | standard (`eai-standard/2.2`) |
+| Twin | `dexjoco-bimanual-photograph-i00-privileged` |
+| Simulator / robot | `dexjoco` / `franka-allegro-bimanual` |
+| Family / instance | `bimanual_photograph` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `bimanual_photograph` (two Franka Panda arms, each with a 16-DoF Allegro hand) on the same frozen instance as `dexjoco-bimanual-photograph-i00-privileged`: Hold the camera with the left hand in front of the logo and press its shutter with the right hand. Success, at one control step: the camera's view point is inside the target region (0.16 m radius, +-0.10 m height, 0.40 m in front of the logo along -x, i.e. about 0.3 m above the table), the camera's viewing axis is within 10 degrees of world +x, and the shutter button is touched by something other than the camera.
+Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with the robot's own
+sensors, calibrated cameras (RGB, optional depth) and the robot's kinematics.
+
+## Difficulty
+Same instance and success check as `dexjoco-bimanual-photograph-i00-privileged`. In standard mode the agent loses resets, the
+simulator and the object poses: it sees camera images and proprioception, acts in chunks of tcp-target + hand-joint rows
+(or joint targets), and gets one episode, so it has to close the loop on what the cameras show and recover from its own
+mistakes without starting over.
+
+## Reference solution
+`solution/oracle_stream.py` streams the privileged reference's rows (`solution/oracle_trajectory.npz`, 260 rows, float32-exact)
+through the client as `ee_pose` 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 260 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 260 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `photograph_demo_10_2026-03-16_14-31-13_305518` (DexJoCo-Datasets-Raw); instance sha `b8b1dbe8dba6c733` |
+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); action types `ee_pose` and `joint_position`; cameras `front`, `back`, `left`, `right`, `top0`, `handcam_rgb_right`, `handcam_rgb_left`, `cam_pos_z` (640 x 480); `/kinematics` for the arm links, the hand mount and the tcp; crash recovery class `exact` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py`, as its privileged twin.
diff --git a/tasks/dexjoco-bimanual-photograph-i00-standard/environment/Dockerfile b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/Dockerfile
new file mode 100644
index 0000000000..a778c94561
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/Dockerfile
@@ -0,0 +1,9 @@
+# Standard mode: the agent container has NO simulator and no DexJoCo 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 /app
diff --git a/tasks/dexjoco-bimanual-photograph-i00-standard/environment/client-requirements.txt b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/client-requirements.txt
new file mode 100644
index 0000000000..8aa73a968f
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-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.0
diff --git a/tasks/dexjoco-bimanual-photograph-i00-standard/environment/docker-compose.yaml b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/docker-compose.yaml
new file mode 100644
index 0000000000..66b6cf32bb
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/docker-compose.yaml
@@ -0,0 +1,24 @@
+# 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 OSMesa rendering; 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-dexjoco:0.1.2
+ 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_TASK: bimanual_photograph
+ RCB_INSTANCE: /srv/instance.npz
+ RCB_TOOL: /srv/rcb_dexjoco.py
+ RCB_DATA: /data
+ RCB_WALL_CLOCK_S: "5400"
+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in a few seconds
+ PYTHONPATH: /srv
+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction log
diff --git a/tasks/dexjoco-bimanual-photograph-i00-standard/environment/rcb1.py b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-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/dexjoco-bimanual-photograph-i00-standard/environment/rcb_client.py b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/rcb_client.py
new file mode 100644
index 0000000000..aa25b0e050
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-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/dexjoco-bimanual-photograph-i00-standard/environment/sim/finalize.sh b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/sim/finalize.sh
new file mode 100755
index 0000000000..e0cf248720
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-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_dexjoco.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:?}"; TASK="${RCB_TASK:?}"
+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 --task "$TASK" --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --repeat 1 \
+ --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"))
+PY
diff --git a/tasks/dexjoco-bimanual-photograph-i00-standard/environment/sim/instance.npz b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/sim/instance.npz
new file mode 100644
index 0000000000..6e5ca5b70e
Binary files /dev/null and b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/sim/instance.npz differ
diff --git a/tasks/dexjoco-bimanual-photograph-i00-standard/environment/sim/rcb1.py b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/sim/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-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/dexjoco-bimanual-photograph-i00-standard/environment/sim/rcb_dexjoco.py b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/sim/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/sim/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-bimanual-photograph-i00-standard/environment/sim/rcb_limited.py b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/sim/rcb_limited.py
new file mode 100644
index 0000000000..1ce1171787
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-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/dexjoco-bimanual-photograph-i00-standard/environment/sim/run.sh b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/sim/run.sh
new file mode 100755
index 0000000000..49d4d045d4
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-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; done
diff --git a/tasks/dexjoco-bimanual-photograph-i00-standard/environment/sim/server.py b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/sim/server.py
new file mode 100644
index 0000000000..ca5b61fc5c
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/sim/server.py
@@ -0,0 +1,625 @@
+"""eai-standard/2.2 sim service for DexJoCo (docs/STANDARD_MODE_2_2.md): the adapter of the shared layer rcb_limited.py;
+the simulator is rcb_dexjoco.Session (DexJoCo on MuJoCo 3.4, CPU physics, OSMesa rendering).
+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to
+/data/episode.jsonl.
+
+The robot is a Franka Panda with a 16-DoF Allegro hand, or two of them side by side (right arm first). One control step
+= 1/50 s (10 physics substeps of 2 ms). Two action types:
+ ee_pose DexJoCo's own row, per arm: the tcp target pose (xyz m, quaternion wxyz, world frame) that its
+ operational-space controller tracks + 16 Allegro joint targets (rad);
+ joint_position per arm: 7 arm joint targets + 16 Allegro joint targets; the arm's targets are turned into a tcp target
+ by forward kinematics (the controller tracks the tcp pose, not the joints).
+Either way, the executed (journaled, recorded) row is DexJoCo's own row, so the recorded trajectory replays in the
+privileged tooling unchanged. As in DexJoCo's evaluation the episode ends at the first success or task failure;
+otherwise when the agent's time is over (the collect hook's SIGUSR1).
+
+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 instance 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")
+TASK = os.environ.get("RCB_TASK", "water_plant")
+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.npz"))
+TASK_TEXT_FILE = os.environ.get("RCB_TASK_TEXT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "task_text.txt"))
+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "5400"))
+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 = 640, 480
+CTRL_HZ = 50.0
+DT = 1.0 / CTRL_HZ
+SUBSTEPS = 10
+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"] = "" # the sidecar's Session is not the agent's interaction log
+import rcb_dexjoco as M # noqa: E402
+import mujoco # noqa: E402
+
+M.SESSION_LOG = ""
+BIM = TASK.startswith("bimanual_")
+ADIM = 46 if BIM else 23
+EP = L.Episode(DATA, dim=ADIM, resume="exact")
+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()
+S = M.Session(TASK, instance=INSTANCE, image_size=(CAM_H, CAM_W))
+MD, D = S.model, S.data
+ARMS = S.arms()
+SFX = {a: (f"_{a}" if BIM else "") for a in ARMS}
+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz
+
+# ------------------------------------------------------------------------------------------------- the robot
+ARM_JOINTS = {a: [f"joint{i}{SFX[a]}" for i in range(1, 8)] for a in ARMS}
+HAND_CTRL = {a: np.asarray(S._hand_ctrl_ids(a)) for a in ARMS}
+HAND_JOINTS = {a: [MD.joint(int(MD.actuator_trnid[i, 0])).name for i in HAND_CTRL[a]] for a in ARMS} # action order
+ARM_CTRL = {a: [MD.actuator(f"actuator{i}{SFX[a]}").id for i in range(1, 8)] for a in ARMS}
+JOINTS = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]] # kinematics q = proprio joint_pos columns
+QADR = np.array([MD.jnt_qposadr[MD.joint(j).id] for j in JOINTS])
+VADR = np.array([MD.jnt_dofadr[MD.joint(j).id] for j in JOINTS])
+EFF_ACT = np.array([i for a in ARMS for i in list(ARM_CTRL[a]) + list(HAND_CTRL[a])])
+TCP_SITE = {a: MD.site(f"attachment_site{SFX[a]}").id for a in ARMS}
+TCP = {a: f"tcp{SFX[a]}" for a in ARMS}
+MOUNT_BODY = {a: f"attachment{SFX[a]}" for a in ARMS}
+LINKS = {a: [f"link{i}{SFX[a]}" for i in range(0, 8) if mujoco.mj_name2id(MD, mujoco.mjtObj.mjOBJ_BODY, f"link{i}{SFX[a]}") >= 0]
+ + [MOUNT_BODY[a]] for a in ARMS}
+KIN_LINKS = [n for a in ARMS for n in LINKS[a] + [TCP[a]]]
+JLIM = {j: MD.jnt_range[MD.joint(j).id].astype(float).tolist() for j in JOINTS}
+HLIM = {a: S.hand_limits(a) for a in ARMS} # actuator ctrlrange, action order
+ALIM = {} # joint_position limits (inside the joint ranges)
+for a in ARMS:
+ for j in ARM_JOINTS[a]:
+ ALIM[j] = JLIM[j]
+ for j, (lo, hi) in zip(HAND_JOINTS[a], HLIM[a]):
+ ALIM[j] = [max(float(lo), JLIM[j][0]), min(float(hi), JLIM[j][1])]
+POSE = ["x", "y", "z", "qw", "qx", "qy", "qz"]
+EE_LAYOUT = [] # per arm, right first
+for a in ARMS:
+ EE_LAYOUT += [f"{TCP[a]}_target_{k}" for k in POSE] + [f"{j}_target" for j in HAND_JOINTS[a]]
+JP_LAYOUT = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]]
+
+GROUPS = [
+ ("joint_pos", JOINTS, "measured joint positions (rad): per arm (right first) the 7 Panda joints, then the 16 Allegro "
+ "joints in the action's order"),
+ ("joint_vel", [f"{j}_vel" for j in JOINTS], "measured joint velocities (rad/s)"),
+ ("joint_effort", [f"{j}_effort" for j in JOINTS], "actuator efforts (N m): the arm's operational-space torques and the "
+ "hand's position-actuator forces"),
+ ("gripper_opening", [], "none: a 16-DoF Allegro hand, its finger joints are in joint_pos"),
+ ("tcp_pose", [f"{TCP[a]}_{k}" for a in ARMS for k in POSE], "measured tcp pose per arm (x y z m, quaternion wxyz, world)"),
+ ("tcp_target", [f"{TCP[a]}_target_{k}" for a in ARMS for k in POSE], "the tcp target the controller tracks now (the "
+ "ee_pose part of the last executed row)"),
+ ("hand_target", [f"{j}_target" for a in ARMS for j in HAND_JOINTS[a]], "the Allegro joint targets now (rad)"),
+]
+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)
+
+
+def _quat(xmat) -> np.ndarray:
+ q = np.zeros(4)
+ mujoco.mju_mat2Quat(q, np.asarray(xmat, dtype=np.float64).reshape(9))
+ return q
+
+
+# ------------------------------------------------------------------------------------------------- cameras
+CAMS = S.cameras()
+HAND_CAMS = [c for c in CAMS if c.startswith("handcam")]
+DEFAULT_CAMS = [S.default_camera()]
+GL2CV = np.diag([1.0, -1.0, -1.0, 1.0])
+
+
+def _intrinsic(cam: str) -> list:
+ fovy = math.radians(float(MD.cam_fovy[MD.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 _cam2world_gl(cam: str) -> np.ndarray:
+ i = MD.camera(cam).id
+ T = np.eye(4)
+ T[:3, :3] = D.cam_xmat[i].reshape(3, 3) # MuJoCo camera axes: OpenGL (x right, y up, z back)
+ T[:3, 3] = D.cam_xpos[i]
+ return T
+
+
+def _extrinsic(cam: str) -> np.ndarray:
+ return np.linalg.inv(_cam2world_gl(cam) @ GL2CV)[:3, :]
+
+
+def camera_info(cam: str) -> dict:
+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist(),
+ "image_size": [CAM_W, CAM_H]}
+
+
+def _mount(cam: str) -> dict:
+ i = MD.camera(cam).id
+ body = MD.body(int(MD.cam_bodyid[i])).name
+ if int(MD.cam_bodyid[i]) == 0:
+ return {"type": "static", "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist()}
+ T = np.eye(4) # body -> camera (OpenGL axes), then to OpenCV axes
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.cam_quat[i])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.cam_pos[i]
+ return {"type": "link", "parent_link": body, "link_T_cam_cv": (T @ GL2CV).tolist()}
+
+
+def _mounted(cam: str) -> str:
+ if cam.startswith("handcam"):
+ side = "the right" if cam.endswith("_right") else "the left" if cam.endswith("_left") else "the"
+ return f"on {side} hand's mount (moves with the hand)"
+ return {"front": "static, across the table, facing the robot", "back": "static, behind the robot, looking over the table",
+ "left": "static, at the robot's left", "right": "static, at the robot's right",
+ "top0": "static, above the table, looking down"}.get(cam, "static")
+
+
+# ------------------------------------------------------------------------------------------------- kinematics
+KD = mujoco.MjData(MD) # kinematics only: never stepped; the robot's joints are set, everything else stays put
+ARM_QI = {a: [JOINTS.index(j) for j in ARM_JOINTS[a]] for a in ARMS}
+
+
+def _fk(q) -> None:
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR] = np.asarray(q, dtype=np.float64)
+ mujoco.mj_kinematics(MD, KD)
+
+
+def _link_pose(name: str) -> list:
+ for a in ARMS:
+ if name == TCP[a]:
+ s = TCP_SITE[a]
+ return [*KD.site_xpos[s].tolist(), *_quat(KD.site_xmat[s]).tolist()]
+ b = MD.body(name).id
+ return [*KD.xpos[b].tolist(), *KD.xquat[b].tolist()]
+
+
+def tcp_from_arm_joints(a: str, q7) -> np.ndarray:
+ """The tcp pose (xyz + wxyz) of arm `a` with its 7 joints at q7 (the joint_position action's tcp target)."""
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR[ARM_QI[a]]] = q7
+ mujoco.mj_kinematics(MD, KD)
+ s = TCP_SITE[a]
+ return np.concatenate([KD.site_xpos[s], _quat(KD.site_xmat[s])])
+
+
+def do_kinematics(req: dict) -> dict:
+ """World frame. FK: every link of spec kinematics.links for q. IK: per tcp target, damped least squares over that
+ arm's 7 joints (position and orientation), within the joint ranges; the hand joints are taken from the seed."""
+ if req["op"] == "fk":
+ _fk(req["q"])
+ return L.fk_response({n: _link_pose(n) for n in req["links"]}, "world")
+ q = np.array(req["seed"] if req["seed"] is not None else D.qpos[QADR], dtype=np.float64)
+ errors = {}
+ jp, jr = np.zeros((3, MD.nv)), np.zeros((3, MD.nv))
+ for frame, pose in req["targets"].items():
+ a = next(x for x in ARMS if TCP[x] == frame)
+ idx = ARM_QI[a]
+ dofs = VADR[idx]
+ tp, tq = np.asarray(pose[:3]), np.asarray(pose[3:7])
+ lo = np.array([JLIM[JOINTS[i]][0] for i in idx]); hi = np.array([JLIM[JOINTS[i]][1] for i in idx])
+ for _ in range(req["max_iters"]):
+ _fk(q)
+ mujoco.mj_comPos(MD, KD) # the Jacobian needs cdof, which mj_kinematics alone leaves stale
+ s = TCP_SITE[a]
+ ep = tp - KD.site_xpos[s]
+ cq = _quat(KD.site_xmat[s])
+ dq = np.zeros(4); neg = np.zeros(4); er = np.zeros(3)
+ mujoco.mju_negQuat(neg, cq); mujoco.mju_mulQuat(dq, tq, neg); mujoco.mju_quat2Vel(er, dq, 1.0)
+ if np.linalg.norm(ep) < req["tol_pos_m"] and np.linalg.norm(er) < req["tol_rot_rad"]:
+ break
+ mujoco.mj_jacSite(MD, KD, jp, jr, s)
+ J = np.vstack([jp[:, dofs], jr[:, dofs]])
+ err = np.concatenate([ep, er])
+ step = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), err)
+ q[idx] = np.clip(q[idx] + step, lo, hi)
+ _fk(q)
+ s = TCP_SITE[a]
+ errors[frame] = (float(np.linalg.norm(tp - KD.site_xpos[s])), L.quat_angle(_quat(KD.site_xmat[s]), tq / np.linalg.norm(tq)))
+ ok = all(e[0] <= req["tol_pos_m"] and e[1] <= req["tol_rot_rad"] for e in errors.values())
+ return L.ik_response(q, ok, errors, "world", note="the tcp (attachment_site) of each arm; the hand joints are the seed's")
+
+
+# ------------------------------------------------------------------------------------------------- spec
+def _joint_spec(a: str) -> list:
+ out = []
+ for j, ai in zip(ARM_JOINTS[a], ARM_CTRL[a]):
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_ctrlrange[ai][1]), "group": f"{a}_arm"})
+ for j, ai in zip(HAND_JOINTS[a], HAND_CTRL[a]):
+ fl = bool(MD.actuator_forcelimited[ai]) and float(MD.actuator_forcerange[ai][1]) > 0
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_forcerange[ai][1]) if fl else None, "group": f"{a}_hand"})
+ return out
+
+
+def _tcp_spec(a: str) -> dict:
+ s = TCP_SITE[a]
+ T = np.eye(4)
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.site_quat[s])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.site_pos[s]
+ return {"parent_link": MD.body(int(MD.site_bodyid[s])).name, "link_T_frame": T.tolist(),
+ "definition": "DexJoCo's attachment_site: the flange where the Allegro hand is mounted, the point its "
+ "operational-space controller drives to the ee_pose target (not the fingertips)"}
+
+
+def _base(a: str) -> list:
+ b = D.body(f"link0{SFX[a]}")
+ return [*np.round(b.xpos, 6).tolist(), *np.round(b.xquat, 6).tolist()]
+
+
+GAINS = {}
+for _a in ARMS:
+ for _j, _ai in zip(HAND_JOINTS[_a], HAND_CTRL[_a]):
+ GAINS[_j] = {"stiffness": float(MD.actuator_gainprm[_ai][0]), "damping": float(MD.dof_damping[MD.jnt_dofadr[MD.joint(_j).id]])}
+ROBOT_NAME = "franka-allegro-bimanual" if BIM else "franka-allegro"
+try:
+ TASK_TEXT = open(TASK_TEXT_FILE).read().strip()
+except OSError:
+ TASK_TEXT = f"DexJoCo {TASK}"
+SPEC = {
+ "protocol": L.PROTOCOL,
+ "protocol_compat": list(L.COMPAT),
+ "simulator": "DexJoCo @ 8d23b0f on MuJoCo 3.4.0 (CPU physics, OSMesa rendering)",
+ "robot": ROBOT_NAME,
+ "task_text": TASK_TEXT,
+ "control_hz": CTRL_HZ,
+ "physics_substeps": SUBSTEPS,
+ "physics_hz": CTRL_HZ * SUBSTEPS,
+ "max_chunk_s": MAX_CHUNK_S,
+ "max_watch_s": MAX_WATCH_S,
+ "cameras": {c: {"rgb": True, "depth": True, "mounted": _mounted(c), "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),
+ "mount": _mount(c)} for c in CAMS},
+ "default_cameras": DEFAULT_CAMS,
+ "action_types": {
+ "ee_pose": {
+ "dim": ADIM, "layout": EE_LAYOUT,
+ "units": "per arm (right first): tcp target position (m, world frame), tcp target orientation (quaternion wxyz), "
+ "16 Allegro joint targets (rad)",
+ "frame": "world", "quaternion_order": "wxyz", "ee_frames": [TCP[a] for a in ARMS],
+ "hand_limits": {j: ALIM[j] for a in ARMS for j in HAND_JOINTS[a]},
+ "semantics": "DexJoCo's own action row. The arm tracks the tcp target through DexJoCo's operational-space "
+ "controller (it lags a moving target and stops where contact blocks it); the hand joints are "
+ "position-controlled. Rows are `dt` apart (a whole multiple of 1/50 s, at most 0.5 s); between rows "
+ "positions and joints move linearly and orientations by slerp (`linear`) or jump (`hold`); a row's "
+ "own values land exactly on its last control step. Hand targets outside the ranges are clamped by "
+ "the simulator and reported in `clipped`; a zero quaternion is a 400.",
+ },
+ "joint_position": {
+ "dim": ADIM, "layout": JP_LAYOUT, "units": "rad", "limits": {j: ALIM[j] for j in JP_LAYOUT},
+ "semantics": "per arm (right first): 7 Panda joint targets, then the 16 Allegro joint targets. The arm's "
+ "targets are turned into a tcp target by forward kinematics (as POST /kinematics fk) and the arm "
+ "tracks that pose through the same operational-space controller as ee_pose, whose null space "
+ "pulls towards DexJoCo's home posture: the tcp reaches FK(q), the measured joints may differ from q "
+ "in the arm's redundant direction. Rows `dt` apart, `linear` (in joint space) or `hold`; values "
+ "outside the limits are clipped and reported.",
+ },
+ "not_yet": ["joint_delta", "joint_velocity", "ee_delta", "joint_torque"],
+ },
+ "proprio_layout": PROPRIO_LAYOUT,
+ "proprio_groups": PROPRIO_GROUPS,
+ "static": {},
+ "world": {"frame": "DexJoCo's world frame: z up, metres; the robot" + ("s stand" if BIM else " stands")
+ + " at low x and reach" + ("" if BIM else "es") + " towards +x"
+ + (" (right arm at y < 0, left arm at y > 0)" if BIM else ""),
+ "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},
+ "episode": "one episode, no reset: it ends at the first success, at a task failure (see task_text), or when your time is over",
+ "robot_spec": {
+ "name": ROBOT_NAME,
+ "description": ("two Franka Panda arms side by side, each with a 16-DoF Allegro hand (right arm first)" if BIM
+ else "a Franka Panda arm with a 16-DoF Allegro hand"),
+ "base": {"type": "fixed", "pose": _base(ARMS[0]), **({"per_arm": {a: _base(a) for a in ARMS}} if BIM else {}),
+ "note": "pose of the arm's base link (link0), world frame, x y z + quaternion wxyz"},
+ "joints": [j for a in ARMS for j in _joint_spec(a)],
+ "grippers": {},
+ "controller": {"type": "arm: operational-space control of the tcp (torques); hand: joint position actuators",
+ "control_hz": CTRL_HZ, "physics_hz": CTRL_HZ * SUBSTEPS, "gains": GAINS,
+ "note": "arm: DexJoCo's opspace controller drives attachment_site to the tcp target (position gains "
+ "400 N/m, damping ratio 4, gravity compensation, null space towards the home posture), "
+ "torques limited to effort_limit; hand: position actuators (stiffness N m/rad) on joints "
+ "with their own damping (N m s/rad)"},
+ "tcp": {TCP[a]: _tcp_spec(a) for a in ARMS},
+ },
+ "kinematics": {"endpoint": "/kinematics", "joint_names": JOINTS, "frame": "world", "quaternion_order": "wxyz",
+ "links": KIN_LINKS, "tcp_frames": [TCP[a] for a in ARMS], "ee_frames": [TCP[a] for a in ARMS],
+ "ik_targets": [TCP[a] for a in ARMS], "ik": {"tol_pos_m": 0.001, "tol_rot_rad": 0.01, "max_iters": 300},
+ "note": "the arm links, the hand mount (the hand cameras' parent) and the tcp, world frame; ik solves "
+ "each tcp target over that arm's 7 joints"},
+ "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()
+
+
+# ------------------------------------------------------------------------------------------------- state and frames
+def ctrl_steps() -> int:
+ return int(S.steps)
+
+
+def proprio_row() -> np.ndarray:
+ tcp, tgt, hand = [], [], []
+ for a in ARMS:
+ s = TCP_SITE[a]
+ tcp += [D.site_xpos[s], _quat(D.site_xmat[s])]
+ t = S._arm_target(a)
+ tgt.append(t[:7]); hand.append(t[7:23])
+ return np.concatenate([D.qpos[QADR], D.qvel[VADR], D.actuator_force[EFF_ACT], *tcp, *tgt, *hand]).astype(np.float32)
+
+
+def grab(cams, want_depth: bool):
+ rgb, dep = {}, {}
+ for c in cams:
+ rgb[c] = S.render_frame(c, (CAM_H, CAM_W))
+ if want_depth:
+ r = S._renderer # the one renderer (a second OSMesa context reads back garbage)
+ r.enable_depth_rendering()
+ try:
+ r.update_scene(D, camera=c)
+ dep[c] = r.render().astype(np.float32).copy()
+ finally:
+ r.disable_depth_rendering()
+ return rgb, dep
+
+
+def extrinsics(cams) -> dict:
+ return {c: _extrinsic(c) for c in cams}
+
+
+def summary() -> dict:
+ n = int(E.get("episode_control_steps") or ctrl_steps())
+ 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"],
+ "task": TASK, "protocol": L.PROTOCOL, "n_actions": len(ROWS), "task_failure": int(str(E["reason"] or "").startswith("failure")),
+ **EP.final_fields()}
+
+
+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 finish(reason: str) -> None:
+ """The episode is over: record the live verdict and dump the trajectory 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()
+ E["success"] = bool(S.success)
+ 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()
+ S.save_trajectory(np.asarray(ROWS, dtype=np.float64).reshape(-1, ADIM), os.path.join(DATA, "trajectory.npz"),
+ {"source": "standard-mode episode", "reason": E["reason"]})
+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})
+ write_final()
+
+
+def ctrl_step(a, rec) -> bool:
+ """One executed control step (DexJoCo's own row), journaled. True when the call must stop here."""
+ a = np.asarray(a, dtype=np.float64)
+ running = S.step(a)
+ ROWS.append(a.copy())
+ stop = EP.journal(a)
+ rec.tick()
+ if not running:
+ finish(S.reason or "done")
+ 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 DEFAULT_CAMS
+ if not isinstance(cams, list) or any(c not in CAMS for c in cams):
+ raise ValueError(f"unknown cameras {cams}; cameras: {CAMS}")
+ return list(dict.fromkeys(cams))
+
+
+def meta_common(cams) -> dict:
+ n = ctrl_steps()
+ return {"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}}
+
+
+def _native_from_ee(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ """ee_pose rows are executed as sent (the recorded row is what the agent commanded); hand targets outside the
+ actuator ranges are clamped by MuJoCo itself (ctrllimited) and only reported."""
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ if float(np.linalg.norm(row[o + 3:o + 7])) < 1e-6:
+ raise ValueError(f"row {ri}: the {a} tcp quaternion has zero norm")
+ for j in range(16):
+ lo, hi = HLIM[a][j]
+ v = row[o + 7 + j]
+ if v < lo or v > hi:
+ clipped.append({"row": ri, "index": int(o + 7 + j), "reason": f"{EE_LAYOUT[o + 7 + j]} outside [{lo:.3f}, {hi:.3f}]: clamped by the simulator"})
+ return row
+
+
+def _clip_joints(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ lo = np.array([ALIM[j][0] for j in JP_LAYOUT]); hi = np.array([ALIM[j][1] for j in JP_LAYOUT])
+ out = np.clip(row, lo, hi)
+ for j in np.flatnonzero(out != row)[:20]:
+ clipped.append({"row": ri, "index": int(j), "reason": f"{JP_LAYOUT[j]} limit [{lo[j]:g}, {hi[j]:g}]"})
+ return out
+
+
+def _native_from_joints(q: np.ndarray) -> np.ndarray:
+ out = []
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ out += [tcp_from_arm_joints(a, q[o:o + 7]), q[o + 7:o + 23]]
+ return np.concatenate(out)
+
+
+def _check_chunk(typ: str, A: np.ndarray, dt: float, interp: str, video: str) -> int:
+ k = dt / DT
+ if A.ndim != 2 or A.shape[1] != ADIM:
+ raise ValueError(f"{typ} actions must be (T, {ADIM}), got {list(A.shape)}")
+ if A.shape[0] == 0:
+ raise ValueError("no rows")
+ 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")
+ return int(round(k))
+
+
+def do_submit(meta: dict, A: np.ndarray):
+ typ = meta.get("type")
+ if typ not in ("ee_pose", "joint_position"):
+ raise ValueError(f"type must be ee_pose or joint_position (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)
+ n = _check_chunk(typ, A, dt, interp, video)
+ clipped: list = []
+ if typ == "ee_pose":
+ A = np.stack([_native_from_ee(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ else:
+ A = np.stack([_clip_joints(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ rec = recorder(cams, fps, meta)
+ E["calls"] += 1
+ step0, before = E["step"], ctrl_steps()
+ rec.tick(force=True)
+ if typ == "ee_pose":
+ prev = np.asarray(S.hold_action(), dtype=np.float64)
+ else:
+ prev = np.concatenate([np.concatenate([D.qpos[QADR[ARM_QI[a]]], S._arm_target(a)[7:23]]) for a in ARMS])
+ for row in A:
+ E["step"] += 1
+ stop = False
+ for s in range(1, n + 1):
+ if interp == "hold" or s == n:
+ target = row # a row's own values land exactly on its last control step
+ else:
+ target = prev + (row - prev) * (s / n)
+ if typ == "ee_pose":
+ for k in range(len(ARMS)):
+ o = 23 * k
+ target[o + 3:o + 7] = M.quat_slerp(prev[o + 3:o + 7], row[o + 3:o + 7], s / n)
+ native = target if typ == "ee_pose" else _native_from_joints(target)
+ if ctrl_step(native, rec):
+ stop = True
+ break
+ prev = row
+ 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"], "type": typ, "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 = np.asarray(S.hold_action(), dtype=np.float64)
+ 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={"task": TASK, "instance_sha": S.instance_sha, "instance_ok": bool(S.instance_exact), "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} DexJoCo sim ready ({TASK}; 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/dexjoco-bimanual-photograph-i00-standard/environment/sim/task_text.txt b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/sim/task_text.txt
new file mode 100644
index 0000000000..f1df42f451
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-standard/environment/sim/task_text.txt
@@ -0,0 +1,3 @@
+Hold the camera with the left hand in front of the logo and press its shutter with the right hand. Success, at one control step: the camera's view point is inside the target region (0.16 m radius, +-0.10 m height, 0.40 m in front of the logo along -x, i.e. about 0.3 m above the table), the camera's viewing axis is within 10 degrees of world +x, and the shutter button is touched by something other than the camera.
+
+The camera lies on the table between the robots; the logo disk stands at the far side of the table.
diff --git a/tasks/dexjoco-bimanual-photograph-i00-standard/instruction.md b/tasks/dexjoco-bimanual-photograph-i00-standard/instruction.md
new file mode 100644
index 0000000000..9e56ff5ef8
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-standard/instruction.md
@@ -0,0 +1,68 @@
+# DexJoCo · bimanual_photograph — STANDARD MODE (robot as a service, eai-standard/2.2)
+
+You control two Franka Panda arms, each with a 16-DoF Allegro hand, **as if it were real hardware**: the simulator runs in a service you cannot open. You get
+one client and one episode. **Task:** Hold the camera with the left hand in front of the logo and press its shutter with the right hand. Success, at one control step: the camera's view point is inside the target region (0.16 m radius, +-0.10 m height, 0.40 m in front of the logo along -x, i.e. about 0.3 m above the table), the camera's viewing axis is within 10 degrees of world +x, and the shutter button is touched by something other than the camera.
+
+The camera lies on the table between the robots; the logo disk stands at the far side of the table.
+
+## Rules (real-robot rules)
+- **No reset.** The episode starts when the service comes up and ends on success, on a task failure (see the task), when
+ your time is up, or on a simulator error. Knocked-over objects stay knocked over.
+- **No privileged state.** You see what the cameras see (RGB, and depth on request, with each camera's calibration) plus
+ the robot's own proprioception (joints, tcp poses, the current targets). No object poses, no success check:
+ `meta["done"]` / `meta["reason"]` tell you when the episode is over and why.
+- Steps are unlimited; your wall-clock budget (90 minutes) is the limit (`meta["time_left_s"]`). Actions and
+ simulated time are reported as cost. Do not stop before the task is solved.
+- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
+ `/app/output/gen.py` for the record (save it early, update it as you go).
+- **Nothing is put into your context automatically.** Images and videos come back as arrays/bytes in a Python object;
+ what you look at and where you store it is your code's decision.
+
+## Client (`/opt/tools/rcb_client.py`, protocol `eai-standard/2.2`)
+```python
+from rcb_client import Robot
+r = Robot() # connects (waits while the service starts)
+spec = r.spec() # action types, cameras (+ calibration), proprio layout, robot_spec, kinematics, budget
+obs = r.get_obs() # current frames of spec["default_cameras"]: obs.last[cam] -> uint8 (480, 640, 3)
+obs = r.get_obs(cameras=["front", "handcam_rgb_right"], depth=True) # + obs.last_depth[cam] -> float32 (480, 640) z-depth (m)
+obs.meta["proprio"] # {"layout": [...], "now": [...]}; obs.group("tcp_pose", now=True)
+obs.meta["cameras"] # per camera intrinsic_cv / extrinsic_cv / cam2world_gl for these frames
+obs = r.get_obs(seconds=2.0, video="mp4") # hold the current targets and watch for 2 s (max 30): obs.video[cam] = mp4 bytes
+
+res = r.submit("ee_pose", rows, dt=0.1) # rows: (T, 46) targets dt seconds apart, executed at 50 Hz with interpolation
+res = r.submit("joint_position", q_rows, dt=0.1) # (T, 46) joint targets instead (see below)
+res.meta["done"], res.meta["reason"], res.meta["clipped"], res.meta["control_steps_chunk"]
+res.video["front"]; res.last["front"]; res.proprio # mp4 of the chunk, last frame, float32 (N, P) proprio per frame
+res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, proprio.npy, ...
+r.fk(q); r.ik({"tcp_right": pose}, seed=q) # kinematics of the robot (stateless: no physics, no time)
+r.status() # calls, control steps, done, reason, elapsed time
+```
+Cameras: `front`, `back`, `left`, `right`, `top0`, `cam_pos_z` (static), `handcam_rgb_right`, `handcam_rgb_left` (on the hand mounts; they move,
+so use the calibration that comes with each response; `spec["cameras"][cam]["mount"]` gives the static pose or the mount
+link). Resolution 640x480. Rendering runs on the CPU: ask only for the cameras you need; `video="none"` makes a chunk
+fastest. If a call fails with a connection error the service may have crashed: it resumes the same episode;
+`r.wait_ready()`, then check `r.status()` (`spec["on_service_error"]`).
+
+### Action type `ee_pose` (46) — DexJoCo's own action
+Per arm, right first: tcp target position (3, metres, world frame), tcp target orientation (4, quaternion wxyz), 16
+Allegro joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+target and stops where contact blocks it); the hand joints are position-controlled. Rows are `dt` apart (a whole multiple
+of 1/50 s, at most 0.5 s); between rows positions and joints move linearly and orientations by slerp
+(`interpolate="linear"`) or jump (`"hold"`); a chunk may cover at most 10 s. Hand targets outside the ranges
+(`spec["action_types"]["ee_pose"]["hand_limits"]`) are clamped by the simulator and listed in `meta["clipped"]`. Build
+the next row from the `tcp_target` and `hand_target` proprio groups to move smoothly.
+
+### Action type `joint_position` (46)
+Per arm, right first: 7 Panda joint targets, then the 16 Allegro joint targets (rad). The service turns the arm's targets
+into a tcp target by forward kinematics and the same controller tracks it: the tcp reaches FK(q), but the measured arm
+joints may differ from q in the arm's redundant direction (the controller's null space pulls towards a home posture).
+Out-of-limit values are clipped and reported.
+
+## Conventions
+- World frame, metres, z up; the robots stand at low x and reach towards +x (right arm at y < 0, left arm at y > 0); each
+ arm's base pose is in `spec["robot_spec"]["base"]`. No other world coordinates are given (D7: the cameras are
+ calibrated, depth is available). Quaternions are **WXYZ**.
+- The tcp (`tcp_right`, `tcp_left`) is the hand's mounting flange (`spec["robot_spec"]["tcp"]`), not the fingertips. Allegro joint
+ order (right hand): index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger = spread, 1-3 = flexion
+ from the knuckle out; thumb 12 = opposition). The LEFT hand's 16 values are mirrored: ring 0-3, middle 4-7, index 8-11, thumb 12-15 (the joint names in `spec["proprio_layout"]` say which).
+- Control runs at 50 Hz (10 physics substeps of 2 ms). There is no step budget: your wall-clock time is the limit.
diff --git a/tasks/dexjoco-bimanual-photograph-i00-standard/solution/oracle_stream.py b/tasks/dexjoco-bimanual-photograph-i00-standard/solution/oracle_stream.py
new file mode 100644
index 0000000000..19877300c1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-standard/solution/oracle_stream.py
@@ -0,0 +1,43 @@
+"""Oracle (standard mode): streams the reference rows (the human demonstration's own actions, one per 1/50 s control step,
+float32-exact) as `ee_pose` 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
+
+A = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle_trajectory.npz"))["actions"].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(A), flush=True)
+t0, i = time.time(), 0
+while i < len(A):
+ chunk = A[i:i + per_chunk]
+ try:
+ res = r.submit("ee_pose", chunk, dt=dt, interpolate="hold", 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/dexjoco-bimanual-photograph-i00-standard/solution/oracle_trajectory.npz b/tasks/dexjoco-bimanual-photograph-i00-standard/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..7468c2f0df
Binary files /dev/null and b/tasks/dexjoco-bimanual-photograph-i00-standard/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-bimanual-photograph-i00-standard/solution/solve.sh b/tasks/dexjoco-bimanual-photograph-i00-standard/solution/solve.sh
new file mode 100755
index 0000000000..1bd55d898f
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-standard/solution/solve.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+# Oracle (standard mode): streams the reference trajectory's rows (solution/oracle_trajectory.npz, one row per control
+# step) as `ee_pose` chunks through the client. Uses no privileged information at run time (only the pre-recorded rows);
+# the service's recorded trajectory is then exactly the privileged reference.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_stream.py /app/output/gen.py
+python /solution/oracle_stream.py
diff --git a/tasks/dexjoco-bimanual-photograph-i00-standard/task.toml b/tasks/dexjoco-bimanual-photograph-i00-standard/task.toml
new file mode 100644
index 0000000000..a243de4b67
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-standard/task.toml
@@ -0,0 +1,52 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator 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/dexjoco-bimanual-photograph-i00-standard"
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): DexJoCo bimanual_photograph (two Franka Panda arms, each with a 16-DoF Allegro hand) on the same frozen instance as dexjoco-bimanual-photograph-i00-privileged. Hold the camera with the left hand in front of the logo and press its shutter with the right hand. The agent only gets a client: calibrated cameras (RGB, optional depth), the robot's joints and tcp poses, tcp-target + hand-joint chunks at 50 Hz, the robot's kinematics; one episode, no reset, no object state; the sim service records the episode, replays it in fresh processes and grades it."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "standard-mode", "robot-as-a-service", "bimanual_photograph"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro-bimanual"
+family = "bimanual_photograph"
+mode = "standard"
+protocol = "eai-standard/2.2"
+oracle = "full"
+expert_time_estimate_hours = 2.5
+
+[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 = 3600
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
diff --git a/tasks/dexjoco-bimanual-photograph-i00-standard/tests/Dockerfile b/tasks/dexjoco-bimanual-photograph-i00-standard/tests/Dockerfile
new file mode 100644
index 0000000000..26bc699ebe
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-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.sh
diff --git a/tasks/dexjoco-bimanual-photograph-i00-standard/tests/grade.py b/tasks/dexjoco-bimanual-photograph-i00-standard/tests/grade.py
new file mode 100644
index 0000000000..003b933315
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-standard/tests/grade.py
@@ -0,0 +1,60 @@
+"""Standard-mode verifier (DexJoCo): 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 frozen 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"))),
+ "task_failure": int(bool(d.get("task_failure"))),
+ "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),
+ "calls": int(d.get("calls") or 0),
+ "elapsed_s": float(d.get("elapsed_s") or 0),
+ "video_rendered": int(bool(d.get("video"))),
+ # 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 frozen 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/dexjoco-bimanual-photograph-i00-standard/tests/test.sh b/tasks/dexjoco-bimanual-photograph-i00-standard/tests/test.sh
new file mode 100755
index 0000000000..bc608aa8b9
--- /dev/null
+++ b/tasks/dexjoco-bimanual-photograph-i00-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
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/README.md b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/README.md
new file mode 100644
index 0000000000..ac8bdc113c
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/README.md
@@ -0,0 +1,49 @@
+# dexjoco-bimanual-unlock-ipad-i00-privileged
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | privileged |
+| Twin | `dexjoco-bimanual-unlock-ipad-i00-standard` |
+| Simulator / robot | `dexjoco` / `franka-allegro-bimanual` |
+| Family / instance | `bimanual_unlock_ipad` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `bimanual_unlock_ipad` (two Franka Panda arms, each with a 16-DoF Allegro hand): Pick up the iPad and enter the passcode 1-2-3 on its screen. A digit is pressed when a FINGERTIP touches its button; pressing any other digit than the next one of 1-2-3 ends the episode as a failure. Success: the screen is unlocked (1, 2, 3 in order) and stays unlocked for 10 consecutive control steps.
+Privileged mode: the agent works in the simulator's container with live object poses, unlimited resets and thin motion
+primitives, and hands in one trajectory replayed open-loop from the frozen instance.
+
+## Difficulty
+First-pass rating: hard. Dexterous manipulation with two 16-DoF hands on two arms (46 action values per control step);
+the primitives only move tcp and hand-joint targets, so grasping, pressing and every other skill is the agent's. The
+reference (the human teleoperator's demonstration) takes 392 control steps (7.8 s at 50 Hz).
+
+## Reference solution
+`solution/oracle_trajectory.npz` = the human demonstration's own actions, rounded to float32 (the standard client's
+precision; the rounded rows still succeed) and replayed from the frozen instance until the episode ends in success
+(392 rows). The demonstration is public (DexJoCo-Datasets-Raw on Hugging Face), so agent egress is
+limited to the model APIs.
+
+## Verification
+Open-loop replay of `/app/output/trajectory.npz` from `tests/instance.npz`, twice in a fresh process in the verifier's own
+sandbox (no network); pass iff both episodes end in success, their final-state hashes agree and the rebuilt instance
+matches its recorded hash (`tests/grade.py`); plus `/logs/verifier/replay.mp4`. Oracle: success after 392 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `ipad_unlock_demo_10_2026-03-22_13-59-49_595064` (DexJoCo-Datasets-Raw), restored with DexJoCo's own state restorer; instance sha `d38c827ac3bb030e` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Tooling notes
+DexJoCo's reset samples object poses from the global RNG and its state restorer edits the MuJoCo model (table height,
+fixed bodies), so `instance.npz` stores the full physics state (`mjSTATE_INTEGRATION`), the mocap targets, the controls,
+every numeric model array a task can change, and the env's Python-side task state. Its per-step camera rendering,
+real-time sleep, episode cap and hanoi's wall-clock auto-reset are disabled in the tooling (`rcb_dexjoco.py`).
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py` from `scripts/dexjoco/instances/bimanual_unlock_ipad/` (`make_instances.py`).
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/environment/Dockerfile b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/environment/Dockerfile
new file mode 100644
index 0000000000..d736fe8a7d
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/environment/Dockerfile
@@ -0,0 +1,7 @@
+# Base image = DexJoCo on MuJoCo 3.4.0 (images/dexjoco/). Everything task-specific is copied here. CPU only.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY instance.npz /app/instance.npz
+COPY rcb_dexjoco.py /opt/tools/rcb_dexjoco.py
+ENV PYTHONPATH=/opt/tools
+RUN mkdir -p /app/output
+WORKDIR /app
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/environment/instance.npz b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/environment/instance.npz
new file mode 100644
index 0000000000..8bc4e3d0c4
Binary files /dev/null and b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/environment/instance.npz differ
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/environment/rcb_dexjoco.py b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/environment/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/environment/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/instruction.md b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/instruction.md
new file mode 100644
index 0000000000..17ce09e365
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/instruction.md
@@ -0,0 +1,72 @@
+# DexJoCo · bimanual_unlock_ipad — frozen instance
+
+You control two Franka Panda arms, each with a 16-DoF Allegro hand (DexJoCo on MuJoCo 3.4) via Python. **Task:** Pick up the iPad and enter the passcode 1-2-3 on its screen. A digit is pressed when a FINGERTIP touches its button; pressing any other digit than the next one of 1-2-3 ends the episode as a failure. Success: the screen is unlocked (1, 2, 3 in order) and stays unlocked for 10 consecutive control steps.
+
+The iPad rests on a stand on the table, screen facing the robots; its keypad shows the digits. `s.objects()` gives the live poses of the task objects (`ipad`, `ipad_screen`, `stand`, `table_top`). DexJoCo's success code (from
+`/opt/dexjoco/dexjoco/dexjoco/sim/envs/panda_bimanual_unlock_ipad_env.py`; `step()` ends the episode on success or on a task failure):
+```python
+def _compute_success(self):
+ if self._unlock_failed:
+ return False
+
+ if self._screen_unlocked:
+ self._success_trigger_count += 1
+ else:
+ self._success_trigger_count = 0
+
+ return self._success_trigger_count >= self._success_trigger_target
+
+ # if self._screen_geom_id >= 0 and self._mat_screen_unlocked_id >= 0:
+ # return int(self._model.geom_matid[self._screen_geom_id]) == self._mat_screen_unlocked_id
+ # return False
+```
+
+This is a *fixed scene instance*: object poses, the table height and the robot's start pose never change between
+resets. You may reset and retry as many times as you want. Your deliverable is **one replayable trajectory**, not a
+general policy.
+
+## Deliverable
+Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
+open-loop from the same initial state in a fresh process and scored 1 if its episode ends in success, else 0. Also
+leave the script that produced it at `/app/output/gen.py`. You have 90 minutes of wall clock: save a
+first trajectory early, improve it, and do not stop before the task is solved.
+
+## Tooling (already installed; run `python` from any directory)
+```python
+from rcb_dexjoco import Session
+s = Session("bimanual_unlock_ipad", instance="/app/instance.npz") # ~1 s: builds the env and loads the frozen state
+s.reset() # back to the frozen initial state (as often as you like; an exact snapshot restore)
+s.objects() # live task objects: name -> pos, quat_wxyz (bodies) / pos (sites) / qpos (joints)
+s.state() # DexJoCo's state dict: tcp_pose, gripper_pose (hand joints), INITIAL object poses, table height
+p = s.primitives() # thin wrappers of the low-level action; each has a docstring: help(p["move_ee"])
+p["move_ee"]("right", pos, quat_wxyz) # straight-line + slerp motion of an arm's tcp target, then settle
+p["set_hand"]("right", q16) # interpolate the 16 Allegro joint targets
+p["hold"](10); p["set_targets"](row, steps) # keep every target / send one raw action row
+p["get_ee_pose"]("right"); p["get_ee_target"]("right"); p["get_hand"]("right"); p["get_body_pose"](name)
+s.render_frame("back") # RGB uint8 (480, 640, 3); cameras: ['back', 'handcam_rgb_right', 'handcam_rgb_left']; s.render_grid()
+s.step(action) # one control step (46 values, below) = 1/50 s; returns False once the episode is over
+s.record_start(); ...; actions = s.record_stop() # (T, 46) actions, one row per control step
+s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+s.replay(actions) # resets, replays open-loop until the episode ends, returns status -> self-check
+s.save_trajectory(actions, "/app/output/trajectory.npz")
+s.render_video(actions, "/app/output/check.mp4", cameras=["back"]) # replays from the frozen state into a video
+```
+The primitives are deliberately thin (tcp target moves, hand joint targets, hold): grasping, pressing, striking and
+every other skill are yours to build from them. `s.bodies()` lists every MuJoCo body for `p["get_body_pose"]`.
+
+CLI equivalent of the grader:
+`python /opt/tools/rcb_dexjoco.py replay --task bimanual_unlock_ipad --instance /app/instance.npz --traj /app/output/trajectory.npz`
+
+## Conventions
+- World frame, metres; z up; the robots stand at low x and reach towards +x. The table top is at z = 0.970. Arm base (`link0`): link0_right [-0.75, -0.4, 0.924], link0_left [-0.75, 0.4, 0.924]. The right arm works at y < 0, the left arm at y > 0. Quaternions are **WXYZ**.
+- Action (46): per arm, right first: tcp target position (3), tcp target orientation (4, wxyz), 16 Allegro
+ joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+ target and stops where contact blocks it); the hand joints are position-controlled. `s.hold_action()` is the no-op.
+ At the start the tcp target is right [-0.443, -0.4, 1.517] / [0.0, 1.0, 0.0, 0.0], left [-0.443, 0.4, 1.517] / [0.0, 1.0, 0.0, 0.0].
+- Allegro joint order (right hand): index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger =
+ spread, 1-3 = flexion from the knuckle out; thumb 12 = opposition). The LEFT hand's 16 values are mirrored: ring 0-3, middle 4-7, index 8-11, thumb 12-15.
+ Target ranges (rad, same for every finger slot, thumb last): low [-0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, 0.26, -0.1, -0.19, -0.16], high [0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 1.4, 1.16, 1.64, 1.72]; the simulator clamps
+ targets to them.
+- Control runs at 50 Hz (10 physics substeps of 2 ms). DexJoCo's own episode cap and real-time pacing are lifted: there
+ is no step budget, your wall-clock time is the limit (~190 control steps/s here). An episode ends at the
+ first success or task failure; `s.step` then refuses further actions until `s.reset()`.
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/solution/gen.py b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/solution/gen.py
new file mode 100644
index 0000000000..0e1f7e3bc7
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/solution/gen.py
@@ -0,0 +1,4 @@
+# How solution/oracle_trajectory.npz was made (scripts/dexjoco/make_instances.py): the DexJoCo human demonstration's
+# own actions (replay.zarr data/action), rounded to float32, replayed from the frozen instance with Session.replay until
+# the episode ended in success (holding the last row a few steps where the rounded rows ended short of a hold count),
+# truncated there and saved with Session.save_trajectory.
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/solution/oracle_trajectory.npz b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..f860a6ee35
Binary files /dev/null and b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/solution/solve.sh b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/solution/solve.sh
new file mode 100755
index 0000000000..7909c90cb8
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/solution/solve.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+# Reference solution: the human demonstration's actions (float32), replayed through the task tooling until success.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_trajectory.npz /app/output/trajectory.npz
+cp /solution/gen.py /app/output/gen.py
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/task.toml b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/task.toml
new file mode 100644
index 0000000000..0c217c7a3e
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/task.toml
@@ -0,0 +1,37 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator or the instance, not this.
+schema_version = "1.3"
+artifacts = ["/app/output/"]
+
+[task]
+name = "robot-coding-bench/dexjoco-bimanual-unlock-ipad-i00-privileged"
+description = "DexJoCo bimanual_unlock_ipad (two Franka Panda arms, each with a 16-DoF Allegro hand, MuJoCo): produce one replayable trajectory. Pick up the iPad and enter the passcode 1-2-3 on its screen. Frozen scene instance (the initial state of a DexJoCo human demonstration)."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "code-as-policy", "trajectory", "bimanual_unlock_ipad"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro-bimanual"
+family = "bimanual_unlock_ipad"
+mode = "privileged"
+oracle = "full"
+expert_time_estimate_hours = 2.5
+
+[verifier]
+timeout_sec = 1800.0
+environment_mode = "separate" # the verifier runs in its own sandbox (tests/Dockerfile); the agent container is gone by then
+network_mode = "no-network"
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
+
+[verifier.environment]
+build_timeout_sec = 1800.0
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/tests/Dockerfile b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/tests/Dockerfile
new file mode 100644
index 0000000000..a2620a4da8
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/tests/Dockerfile
@@ -0,0 +1,8 @@
+# Separate verifier sandbox (PROTOCOL §2.6): the same simulator image with the verifier's own copies of the tooling and
+# the frozen instance baked in. Nothing the agent did in its container reaches this one: Harbor uploads only the declared
+# artifacts (/app/output/), so a patched success check in the agent container cannot count.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY grade.py instance.npz rcb_dexjoco.py test.sh /tests/
+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
+ENV PYTHONPATH=/tests
+WORKDIR /tests
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/tests/grade.py b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/tests/grade.py
new file mode 100644
index 0000000000..ad916e8bb9
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/tests/grade.py
@@ -0,0 +1,109 @@
+"""Verifier entry point for the privileged DexJoCo tasks: replay /app/output/trajectory.npz from the frozen instance and
+write Harbor rewards.
+
+ python /tests/grade.py --family water_plant --instance /tests/instance.npz --traj /app/output/trajectory.npz
+
+Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only; Harbor rejects strings), a replay video
+/logs/verifier/replay.mp4 (front camera + wrist camera) and replay.last.png. Replays `--repeat` times in this fresh
+process; success requires every replay to end its episode in success (DexJoCo's own rule: the episode ends at the first
+success or task failure) AND all final-state hashes to agree (MuJoCo on the CPU is bit-deterministic), and the frozen
+instance rebuilt here from tests/instance.npz must match its recorded hash.
+"""
+from __future__ import annotations
+import argparse, json, os, sys, time, traceback
+import numpy as np
+
+LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")
+
+
+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 self_reported_cost() -> dict:
+ # From the tooling's append-only log in the agent's container: SELF-REPORTED accounting, never evidence.
+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_records": 0, "agent_replays": 0,
+ "agent_cost_self_reported": 1}
+ try:
+ with open("/app/output/rcb_session_log.jsonl") 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 == "session_end": cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)
+ elif ev == "record": cost["agent_records"] += 1
+ elif ev == "replay": cost["agent_replays"] += 1
+ except Exception: # noqa: BLE001 — one bad line must not sink the verdict
+ continue
+ except Exception: # noqa: BLE001
+ pass
+ return cost
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--family", required=True); ap.add_argument("--instance", required=True)
+ ap.add_argument("--traj", default="/app/output/trajectory.npz"); ap.add_argument("--repeat", type=int, default=2)
+ ap.add_argument("--no-video", action="store_true")
+ a = ap.parse_args()
+ cost = self_reported_cost()
+ os.environ["RCB_SESSION_LOG"] = "" # the verifier's own sessions are not the agent's cost
+ if not os.path.isfile(a.traj):
+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost}); return 0
+ s = None
+ try:
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the verifier's own copy of the tooling
+ import rcb_dexjoco
+ rcb_dexjoco.SESSION_LOG = ""
+ from rcb_dexjoco import Session, MAX_STEPS
+ d = np.load(a.traj, allow_pickle=False)
+ if str(d["task"]) != a.family:
+ write(False, {"success": 0, "wrong_family": 1, "grader_error": 0, **cost}); return 0
+ acts = np.asarray(d["actions"], dtype=np.float64)
+ s = Session(a.family, instance=a.instance)
+ if (acts.ndim != 2 or acts.shape[1] != s.action_dim or acts.shape[0] > MAX_STEPS
+ or not np.all(np.isfinite(acts))):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0,
+ "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0, **cost}); return 0
+ t0 = time.time()
+ outs = []
+ for _ in range(a.repeat):
+ try:
+ outs.append(s.replay(acts))
+ except (ValueError, rcb_dexjoco.PrimitiveError):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0, "n_actions": int(len(acts)), **cost}); return 0
+ all_success = all(o["success"] for o in outs)
+ deterministic = len({o["state_sha"] for o in outs}) == 1
+ instance_ok = bool(s.instance_exact)
+ ok = all_success and deterministic and instance_ok
+ out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
+ "instance_ok": int(instance_ok), "n_actions": int(len(acts)), "sim_steps": int(outs[0]["steps"]),
+ "task_failure": int(bool(outs[0]["reason"]) and not outs[0]["success"]),
+ "replay_wall_s": round(time.time() - t0, 1), "grader_error": 0, "video_rendered": 0, **cost}
+ if not a.no_video: # human-viewable replay (never affects the verdict)
+ try:
+ n = int(outs[0]["replayed_rows"])
+ s.render_video(acts[:n], os.path.join(LOG_DIR, "replay.mp4"), cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ import imageio.v2 as imageio
+ imageio.imwrite(os.path.join(LOG_DIR, "replay.last.png"), s.render_frame(s.default_camera(), (480, 640)))
+ out["video_rendered"] = int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4")))
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(ok, out)
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(False, {"success": 0, "grader_error": 1, **cost})
+ finally:
+ if s is not None:
+ s.close()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/tests/instance.npz b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/tests/instance.npz
new file mode 100644
index 0000000000..8bc4e3d0c4
Binary files /dev/null and b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/tests/instance.npz differ
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/tests/rcb_dexjoco.py b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/tests/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/tests/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/tests/test.sh b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/tests/test.sh
new file mode 100755
index 0000000000..35051f1270
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-privileged/tests/test.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in a fresh process.
+# 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/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)
+mkdir -p /logs/verifier
+python /tests/grade.py --family bimanual_unlock_ipad --instance /tests/instance.npz --traj /app/output/trajectory.npz --repeat 2 \
+ 2> /logs/verifier/grade.log
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/README.md b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/README.md
new file mode 100644
index 0000000000..f4286d65e1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/README.md
@@ -0,0 +1,45 @@
+# dexjoco-bimanual-unlock-ipad-i00-standard
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | standard (`eai-standard/2.2`) |
+| Twin | `dexjoco-bimanual-unlock-ipad-i00-privileged` |
+| Simulator / robot | `dexjoco` / `franka-allegro-bimanual` |
+| Family / instance | `bimanual_unlock_ipad` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `bimanual_unlock_ipad` (two Franka Panda arms, each with a 16-DoF Allegro hand) on the same frozen instance as `dexjoco-bimanual-unlock-ipad-i00-privileged`: Pick up the iPad and enter the passcode 1-2-3 on its screen. A digit is pressed when a FINGERTIP touches its button; pressing any other digit than the next one of 1-2-3 ends the episode as a failure. Success: the screen is unlocked (1, 2, 3 in order) and stays unlocked for 10 consecutive control steps.
+Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with the robot's own
+sensors, calibrated cameras (RGB, optional depth) and the robot's kinematics.
+
+## Difficulty
+Same instance and success check as `dexjoco-bimanual-unlock-ipad-i00-privileged`. In standard mode the agent loses resets, the
+simulator and the object poses: it sees camera images and proprioception, acts in chunks of tcp-target + hand-joint rows
+(or joint targets), and gets one episode, so it has to close the loop on what the cameras show and recover from its own
+mistakes without starting over.
+
+## Reference solution
+`solution/oracle_stream.py` streams the privileged reference's rows (`solution/oracle_trajectory.npz`, 392 rows, float32-exact)
+through the client as `ee_pose` 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 392 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 392 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `ipad_unlock_demo_10_2026-03-22_13-59-49_595064` (DexJoCo-Datasets-Raw); instance sha `d38c827ac3bb030e` |
+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); action types `ee_pose` and `joint_position`; cameras `back`, `handcam_rgb_right`, `handcam_rgb_left` (640 x 480); `/kinematics` for the arm links, the hand mount and the tcp; crash recovery class `exact` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py`, as its privileged twin.
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/Dockerfile b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/Dockerfile
new file mode 100644
index 0000000000..a778c94561
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/Dockerfile
@@ -0,0 +1,9 @@
+# Standard mode: the agent container has NO simulator and no DexJoCo 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 /app
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/client-requirements.txt b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/client-requirements.txt
new file mode 100644
index 0000000000..8aa73a968f
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-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.0
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/docker-compose.yaml b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/docker-compose.yaml
new file mode 100644
index 0000000000..fdcc4fb06d
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/docker-compose.yaml
@@ -0,0 +1,24 @@
+# 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 OSMesa rendering; 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-dexjoco:0.1.2
+ 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_TASK: bimanual_unlock_ipad
+ RCB_INSTANCE: /srv/instance.npz
+ RCB_TOOL: /srv/rcb_dexjoco.py
+ RCB_DATA: /data
+ RCB_WALL_CLOCK_S: "5400"
+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in a few seconds
+ PYTHONPATH: /srv
+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction log
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/rcb1.py b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-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/dexjoco-bimanual-unlock-ipad-i00-standard/environment/rcb_client.py b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/rcb_client.py
new file mode 100644
index 0000000000..aa25b0e050
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-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/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/finalize.sh b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/finalize.sh
new file mode 100755
index 0000000000..e0cf248720
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-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_dexjoco.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:?}"; TASK="${RCB_TASK:?}"
+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 --task "$TASK" --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --repeat 1 \
+ --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"))
+PY
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/instance.npz b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/instance.npz
new file mode 100644
index 0000000000..8bc4e3d0c4
Binary files /dev/null and b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/instance.npz differ
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/rcb1.py b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-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/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/rcb_dexjoco.py b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/rcb_limited.py b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/rcb_limited.py
new file mode 100644
index 0000000000..1ce1171787
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-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/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/run.sh b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/run.sh
new file mode 100755
index 0000000000..49d4d045d4
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-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; done
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/server.py b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/server.py
new file mode 100644
index 0000000000..ca5b61fc5c
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/server.py
@@ -0,0 +1,625 @@
+"""eai-standard/2.2 sim service for DexJoCo (docs/STANDARD_MODE_2_2.md): the adapter of the shared layer rcb_limited.py;
+the simulator is rcb_dexjoco.Session (DexJoCo on MuJoCo 3.4, CPU physics, OSMesa rendering).
+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to
+/data/episode.jsonl.
+
+The robot is a Franka Panda with a 16-DoF Allegro hand, or two of them side by side (right arm first). One control step
+= 1/50 s (10 physics substeps of 2 ms). Two action types:
+ ee_pose DexJoCo's own row, per arm: the tcp target pose (xyz m, quaternion wxyz, world frame) that its
+ operational-space controller tracks + 16 Allegro joint targets (rad);
+ joint_position per arm: 7 arm joint targets + 16 Allegro joint targets; the arm's targets are turned into a tcp target
+ by forward kinematics (the controller tracks the tcp pose, not the joints).
+Either way, the executed (journaled, recorded) row is DexJoCo's own row, so the recorded trajectory replays in the
+privileged tooling unchanged. As in DexJoCo's evaluation the episode ends at the first success or task failure;
+otherwise when the agent's time is over (the collect hook's SIGUSR1).
+
+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 instance 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")
+TASK = os.environ.get("RCB_TASK", "water_plant")
+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.npz"))
+TASK_TEXT_FILE = os.environ.get("RCB_TASK_TEXT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "task_text.txt"))
+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "5400"))
+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 = 640, 480
+CTRL_HZ = 50.0
+DT = 1.0 / CTRL_HZ
+SUBSTEPS = 10
+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"] = "" # the sidecar's Session is not the agent's interaction log
+import rcb_dexjoco as M # noqa: E402
+import mujoco # noqa: E402
+
+M.SESSION_LOG = ""
+BIM = TASK.startswith("bimanual_")
+ADIM = 46 if BIM else 23
+EP = L.Episode(DATA, dim=ADIM, resume="exact")
+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()
+S = M.Session(TASK, instance=INSTANCE, image_size=(CAM_H, CAM_W))
+MD, D = S.model, S.data
+ARMS = S.arms()
+SFX = {a: (f"_{a}" if BIM else "") for a in ARMS}
+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz
+
+# ------------------------------------------------------------------------------------------------- the robot
+ARM_JOINTS = {a: [f"joint{i}{SFX[a]}" for i in range(1, 8)] for a in ARMS}
+HAND_CTRL = {a: np.asarray(S._hand_ctrl_ids(a)) for a in ARMS}
+HAND_JOINTS = {a: [MD.joint(int(MD.actuator_trnid[i, 0])).name for i in HAND_CTRL[a]] for a in ARMS} # action order
+ARM_CTRL = {a: [MD.actuator(f"actuator{i}{SFX[a]}").id for i in range(1, 8)] for a in ARMS}
+JOINTS = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]] # kinematics q = proprio joint_pos columns
+QADR = np.array([MD.jnt_qposadr[MD.joint(j).id] for j in JOINTS])
+VADR = np.array([MD.jnt_dofadr[MD.joint(j).id] for j in JOINTS])
+EFF_ACT = np.array([i for a in ARMS for i in list(ARM_CTRL[a]) + list(HAND_CTRL[a])])
+TCP_SITE = {a: MD.site(f"attachment_site{SFX[a]}").id for a in ARMS}
+TCP = {a: f"tcp{SFX[a]}" for a in ARMS}
+MOUNT_BODY = {a: f"attachment{SFX[a]}" for a in ARMS}
+LINKS = {a: [f"link{i}{SFX[a]}" for i in range(0, 8) if mujoco.mj_name2id(MD, mujoco.mjtObj.mjOBJ_BODY, f"link{i}{SFX[a]}") >= 0]
+ + [MOUNT_BODY[a]] for a in ARMS}
+KIN_LINKS = [n for a in ARMS for n in LINKS[a] + [TCP[a]]]
+JLIM = {j: MD.jnt_range[MD.joint(j).id].astype(float).tolist() for j in JOINTS}
+HLIM = {a: S.hand_limits(a) for a in ARMS} # actuator ctrlrange, action order
+ALIM = {} # joint_position limits (inside the joint ranges)
+for a in ARMS:
+ for j in ARM_JOINTS[a]:
+ ALIM[j] = JLIM[j]
+ for j, (lo, hi) in zip(HAND_JOINTS[a], HLIM[a]):
+ ALIM[j] = [max(float(lo), JLIM[j][0]), min(float(hi), JLIM[j][1])]
+POSE = ["x", "y", "z", "qw", "qx", "qy", "qz"]
+EE_LAYOUT = [] # per arm, right first
+for a in ARMS:
+ EE_LAYOUT += [f"{TCP[a]}_target_{k}" for k in POSE] + [f"{j}_target" for j in HAND_JOINTS[a]]
+JP_LAYOUT = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]]
+
+GROUPS = [
+ ("joint_pos", JOINTS, "measured joint positions (rad): per arm (right first) the 7 Panda joints, then the 16 Allegro "
+ "joints in the action's order"),
+ ("joint_vel", [f"{j}_vel" for j in JOINTS], "measured joint velocities (rad/s)"),
+ ("joint_effort", [f"{j}_effort" for j in JOINTS], "actuator efforts (N m): the arm's operational-space torques and the "
+ "hand's position-actuator forces"),
+ ("gripper_opening", [], "none: a 16-DoF Allegro hand, its finger joints are in joint_pos"),
+ ("tcp_pose", [f"{TCP[a]}_{k}" for a in ARMS for k in POSE], "measured tcp pose per arm (x y z m, quaternion wxyz, world)"),
+ ("tcp_target", [f"{TCP[a]}_target_{k}" for a in ARMS for k in POSE], "the tcp target the controller tracks now (the "
+ "ee_pose part of the last executed row)"),
+ ("hand_target", [f"{j}_target" for a in ARMS for j in HAND_JOINTS[a]], "the Allegro joint targets now (rad)"),
+]
+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)
+
+
+def _quat(xmat) -> np.ndarray:
+ q = np.zeros(4)
+ mujoco.mju_mat2Quat(q, np.asarray(xmat, dtype=np.float64).reshape(9))
+ return q
+
+
+# ------------------------------------------------------------------------------------------------- cameras
+CAMS = S.cameras()
+HAND_CAMS = [c for c in CAMS if c.startswith("handcam")]
+DEFAULT_CAMS = [S.default_camera()]
+GL2CV = np.diag([1.0, -1.0, -1.0, 1.0])
+
+
+def _intrinsic(cam: str) -> list:
+ fovy = math.radians(float(MD.cam_fovy[MD.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 _cam2world_gl(cam: str) -> np.ndarray:
+ i = MD.camera(cam).id
+ T = np.eye(4)
+ T[:3, :3] = D.cam_xmat[i].reshape(3, 3) # MuJoCo camera axes: OpenGL (x right, y up, z back)
+ T[:3, 3] = D.cam_xpos[i]
+ return T
+
+
+def _extrinsic(cam: str) -> np.ndarray:
+ return np.linalg.inv(_cam2world_gl(cam) @ GL2CV)[:3, :]
+
+
+def camera_info(cam: str) -> dict:
+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist(),
+ "image_size": [CAM_W, CAM_H]}
+
+
+def _mount(cam: str) -> dict:
+ i = MD.camera(cam).id
+ body = MD.body(int(MD.cam_bodyid[i])).name
+ if int(MD.cam_bodyid[i]) == 0:
+ return {"type": "static", "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist()}
+ T = np.eye(4) # body -> camera (OpenGL axes), then to OpenCV axes
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.cam_quat[i])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.cam_pos[i]
+ return {"type": "link", "parent_link": body, "link_T_cam_cv": (T @ GL2CV).tolist()}
+
+
+def _mounted(cam: str) -> str:
+ if cam.startswith("handcam"):
+ side = "the right" if cam.endswith("_right") else "the left" if cam.endswith("_left") else "the"
+ return f"on {side} hand's mount (moves with the hand)"
+ return {"front": "static, across the table, facing the robot", "back": "static, behind the robot, looking over the table",
+ "left": "static, at the robot's left", "right": "static, at the robot's right",
+ "top0": "static, above the table, looking down"}.get(cam, "static")
+
+
+# ------------------------------------------------------------------------------------------------- kinematics
+KD = mujoco.MjData(MD) # kinematics only: never stepped; the robot's joints are set, everything else stays put
+ARM_QI = {a: [JOINTS.index(j) for j in ARM_JOINTS[a]] for a in ARMS}
+
+
+def _fk(q) -> None:
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR] = np.asarray(q, dtype=np.float64)
+ mujoco.mj_kinematics(MD, KD)
+
+
+def _link_pose(name: str) -> list:
+ for a in ARMS:
+ if name == TCP[a]:
+ s = TCP_SITE[a]
+ return [*KD.site_xpos[s].tolist(), *_quat(KD.site_xmat[s]).tolist()]
+ b = MD.body(name).id
+ return [*KD.xpos[b].tolist(), *KD.xquat[b].tolist()]
+
+
+def tcp_from_arm_joints(a: str, q7) -> np.ndarray:
+ """The tcp pose (xyz + wxyz) of arm `a` with its 7 joints at q7 (the joint_position action's tcp target)."""
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR[ARM_QI[a]]] = q7
+ mujoco.mj_kinematics(MD, KD)
+ s = TCP_SITE[a]
+ return np.concatenate([KD.site_xpos[s], _quat(KD.site_xmat[s])])
+
+
+def do_kinematics(req: dict) -> dict:
+ """World frame. FK: every link of spec kinematics.links for q. IK: per tcp target, damped least squares over that
+ arm's 7 joints (position and orientation), within the joint ranges; the hand joints are taken from the seed."""
+ if req["op"] == "fk":
+ _fk(req["q"])
+ return L.fk_response({n: _link_pose(n) for n in req["links"]}, "world")
+ q = np.array(req["seed"] if req["seed"] is not None else D.qpos[QADR], dtype=np.float64)
+ errors = {}
+ jp, jr = np.zeros((3, MD.nv)), np.zeros((3, MD.nv))
+ for frame, pose in req["targets"].items():
+ a = next(x for x in ARMS if TCP[x] == frame)
+ idx = ARM_QI[a]
+ dofs = VADR[idx]
+ tp, tq = np.asarray(pose[:3]), np.asarray(pose[3:7])
+ lo = np.array([JLIM[JOINTS[i]][0] for i in idx]); hi = np.array([JLIM[JOINTS[i]][1] for i in idx])
+ for _ in range(req["max_iters"]):
+ _fk(q)
+ mujoco.mj_comPos(MD, KD) # the Jacobian needs cdof, which mj_kinematics alone leaves stale
+ s = TCP_SITE[a]
+ ep = tp - KD.site_xpos[s]
+ cq = _quat(KD.site_xmat[s])
+ dq = np.zeros(4); neg = np.zeros(4); er = np.zeros(3)
+ mujoco.mju_negQuat(neg, cq); mujoco.mju_mulQuat(dq, tq, neg); mujoco.mju_quat2Vel(er, dq, 1.0)
+ if np.linalg.norm(ep) < req["tol_pos_m"] and np.linalg.norm(er) < req["tol_rot_rad"]:
+ break
+ mujoco.mj_jacSite(MD, KD, jp, jr, s)
+ J = np.vstack([jp[:, dofs], jr[:, dofs]])
+ err = np.concatenate([ep, er])
+ step = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), err)
+ q[idx] = np.clip(q[idx] + step, lo, hi)
+ _fk(q)
+ s = TCP_SITE[a]
+ errors[frame] = (float(np.linalg.norm(tp - KD.site_xpos[s])), L.quat_angle(_quat(KD.site_xmat[s]), tq / np.linalg.norm(tq)))
+ ok = all(e[0] <= req["tol_pos_m"] and e[1] <= req["tol_rot_rad"] for e in errors.values())
+ return L.ik_response(q, ok, errors, "world", note="the tcp (attachment_site) of each arm; the hand joints are the seed's")
+
+
+# ------------------------------------------------------------------------------------------------- spec
+def _joint_spec(a: str) -> list:
+ out = []
+ for j, ai in zip(ARM_JOINTS[a], ARM_CTRL[a]):
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_ctrlrange[ai][1]), "group": f"{a}_arm"})
+ for j, ai in zip(HAND_JOINTS[a], HAND_CTRL[a]):
+ fl = bool(MD.actuator_forcelimited[ai]) and float(MD.actuator_forcerange[ai][1]) > 0
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_forcerange[ai][1]) if fl else None, "group": f"{a}_hand"})
+ return out
+
+
+def _tcp_spec(a: str) -> dict:
+ s = TCP_SITE[a]
+ T = np.eye(4)
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.site_quat[s])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.site_pos[s]
+ return {"parent_link": MD.body(int(MD.site_bodyid[s])).name, "link_T_frame": T.tolist(),
+ "definition": "DexJoCo's attachment_site: the flange where the Allegro hand is mounted, the point its "
+ "operational-space controller drives to the ee_pose target (not the fingertips)"}
+
+
+def _base(a: str) -> list:
+ b = D.body(f"link0{SFX[a]}")
+ return [*np.round(b.xpos, 6).tolist(), *np.round(b.xquat, 6).tolist()]
+
+
+GAINS = {}
+for _a in ARMS:
+ for _j, _ai in zip(HAND_JOINTS[_a], HAND_CTRL[_a]):
+ GAINS[_j] = {"stiffness": float(MD.actuator_gainprm[_ai][0]), "damping": float(MD.dof_damping[MD.jnt_dofadr[MD.joint(_j).id]])}
+ROBOT_NAME = "franka-allegro-bimanual" if BIM else "franka-allegro"
+try:
+ TASK_TEXT = open(TASK_TEXT_FILE).read().strip()
+except OSError:
+ TASK_TEXT = f"DexJoCo {TASK}"
+SPEC = {
+ "protocol": L.PROTOCOL,
+ "protocol_compat": list(L.COMPAT),
+ "simulator": "DexJoCo @ 8d23b0f on MuJoCo 3.4.0 (CPU physics, OSMesa rendering)",
+ "robot": ROBOT_NAME,
+ "task_text": TASK_TEXT,
+ "control_hz": CTRL_HZ,
+ "physics_substeps": SUBSTEPS,
+ "physics_hz": CTRL_HZ * SUBSTEPS,
+ "max_chunk_s": MAX_CHUNK_S,
+ "max_watch_s": MAX_WATCH_S,
+ "cameras": {c: {"rgb": True, "depth": True, "mounted": _mounted(c), "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),
+ "mount": _mount(c)} for c in CAMS},
+ "default_cameras": DEFAULT_CAMS,
+ "action_types": {
+ "ee_pose": {
+ "dim": ADIM, "layout": EE_LAYOUT,
+ "units": "per arm (right first): tcp target position (m, world frame), tcp target orientation (quaternion wxyz), "
+ "16 Allegro joint targets (rad)",
+ "frame": "world", "quaternion_order": "wxyz", "ee_frames": [TCP[a] for a in ARMS],
+ "hand_limits": {j: ALIM[j] for a in ARMS for j in HAND_JOINTS[a]},
+ "semantics": "DexJoCo's own action row. The arm tracks the tcp target through DexJoCo's operational-space "
+ "controller (it lags a moving target and stops where contact blocks it); the hand joints are "
+ "position-controlled. Rows are `dt` apart (a whole multiple of 1/50 s, at most 0.5 s); between rows "
+ "positions and joints move linearly and orientations by slerp (`linear`) or jump (`hold`); a row's "
+ "own values land exactly on its last control step. Hand targets outside the ranges are clamped by "
+ "the simulator and reported in `clipped`; a zero quaternion is a 400.",
+ },
+ "joint_position": {
+ "dim": ADIM, "layout": JP_LAYOUT, "units": "rad", "limits": {j: ALIM[j] for j in JP_LAYOUT},
+ "semantics": "per arm (right first): 7 Panda joint targets, then the 16 Allegro joint targets. The arm's "
+ "targets are turned into a tcp target by forward kinematics (as POST /kinematics fk) and the arm "
+ "tracks that pose through the same operational-space controller as ee_pose, whose null space "
+ "pulls towards DexJoCo's home posture: the tcp reaches FK(q), the measured joints may differ from q "
+ "in the arm's redundant direction. Rows `dt` apart, `linear` (in joint space) or `hold`; values "
+ "outside the limits are clipped and reported.",
+ },
+ "not_yet": ["joint_delta", "joint_velocity", "ee_delta", "joint_torque"],
+ },
+ "proprio_layout": PROPRIO_LAYOUT,
+ "proprio_groups": PROPRIO_GROUPS,
+ "static": {},
+ "world": {"frame": "DexJoCo's world frame: z up, metres; the robot" + ("s stand" if BIM else " stands")
+ + " at low x and reach" + ("" if BIM else "es") + " towards +x"
+ + (" (right arm at y < 0, left arm at y > 0)" if BIM else ""),
+ "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},
+ "episode": "one episode, no reset: it ends at the first success, at a task failure (see task_text), or when your time is over",
+ "robot_spec": {
+ "name": ROBOT_NAME,
+ "description": ("two Franka Panda arms side by side, each with a 16-DoF Allegro hand (right arm first)" if BIM
+ else "a Franka Panda arm with a 16-DoF Allegro hand"),
+ "base": {"type": "fixed", "pose": _base(ARMS[0]), **({"per_arm": {a: _base(a) for a in ARMS}} if BIM else {}),
+ "note": "pose of the arm's base link (link0), world frame, x y z + quaternion wxyz"},
+ "joints": [j for a in ARMS for j in _joint_spec(a)],
+ "grippers": {},
+ "controller": {"type": "arm: operational-space control of the tcp (torques); hand: joint position actuators",
+ "control_hz": CTRL_HZ, "physics_hz": CTRL_HZ * SUBSTEPS, "gains": GAINS,
+ "note": "arm: DexJoCo's opspace controller drives attachment_site to the tcp target (position gains "
+ "400 N/m, damping ratio 4, gravity compensation, null space towards the home posture), "
+ "torques limited to effort_limit; hand: position actuators (stiffness N m/rad) on joints "
+ "with their own damping (N m s/rad)"},
+ "tcp": {TCP[a]: _tcp_spec(a) for a in ARMS},
+ },
+ "kinematics": {"endpoint": "/kinematics", "joint_names": JOINTS, "frame": "world", "quaternion_order": "wxyz",
+ "links": KIN_LINKS, "tcp_frames": [TCP[a] for a in ARMS], "ee_frames": [TCP[a] for a in ARMS],
+ "ik_targets": [TCP[a] for a in ARMS], "ik": {"tol_pos_m": 0.001, "tol_rot_rad": 0.01, "max_iters": 300},
+ "note": "the arm links, the hand mount (the hand cameras' parent) and the tcp, world frame; ik solves "
+ "each tcp target over that arm's 7 joints"},
+ "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()
+
+
+# ------------------------------------------------------------------------------------------------- state and frames
+def ctrl_steps() -> int:
+ return int(S.steps)
+
+
+def proprio_row() -> np.ndarray:
+ tcp, tgt, hand = [], [], []
+ for a in ARMS:
+ s = TCP_SITE[a]
+ tcp += [D.site_xpos[s], _quat(D.site_xmat[s])]
+ t = S._arm_target(a)
+ tgt.append(t[:7]); hand.append(t[7:23])
+ return np.concatenate([D.qpos[QADR], D.qvel[VADR], D.actuator_force[EFF_ACT], *tcp, *tgt, *hand]).astype(np.float32)
+
+
+def grab(cams, want_depth: bool):
+ rgb, dep = {}, {}
+ for c in cams:
+ rgb[c] = S.render_frame(c, (CAM_H, CAM_W))
+ if want_depth:
+ r = S._renderer # the one renderer (a second OSMesa context reads back garbage)
+ r.enable_depth_rendering()
+ try:
+ r.update_scene(D, camera=c)
+ dep[c] = r.render().astype(np.float32).copy()
+ finally:
+ r.disable_depth_rendering()
+ return rgb, dep
+
+
+def extrinsics(cams) -> dict:
+ return {c: _extrinsic(c) for c in cams}
+
+
+def summary() -> dict:
+ n = int(E.get("episode_control_steps") or ctrl_steps())
+ 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"],
+ "task": TASK, "protocol": L.PROTOCOL, "n_actions": len(ROWS), "task_failure": int(str(E["reason"] or "").startswith("failure")),
+ **EP.final_fields()}
+
+
+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 finish(reason: str) -> None:
+ """The episode is over: record the live verdict and dump the trajectory 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()
+ E["success"] = bool(S.success)
+ 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()
+ S.save_trajectory(np.asarray(ROWS, dtype=np.float64).reshape(-1, ADIM), os.path.join(DATA, "trajectory.npz"),
+ {"source": "standard-mode episode", "reason": E["reason"]})
+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})
+ write_final()
+
+
+def ctrl_step(a, rec) -> bool:
+ """One executed control step (DexJoCo's own row), journaled. True when the call must stop here."""
+ a = np.asarray(a, dtype=np.float64)
+ running = S.step(a)
+ ROWS.append(a.copy())
+ stop = EP.journal(a)
+ rec.tick()
+ if not running:
+ finish(S.reason or "done")
+ 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 DEFAULT_CAMS
+ if not isinstance(cams, list) or any(c not in CAMS for c in cams):
+ raise ValueError(f"unknown cameras {cams}; cameras: {CAMS}")
+ return list(dict.fromkeys(cams))
+
+
+def meta_common(cams) -> dict:
+ n = ctrl_steps()
+ return {"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}}
+
+
+def _native_from_ee(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ """ee_pose rows are executed as sent (the recorded row is what the agent commanded); hand targets outside the
+ actuator ranges are clamped by MuJoCo itself (ctrllimited) and only reported."""
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ if float(np.linalg.norm(row[o + 3:o + 7])) < 1e-6:
+ raise ValueError(f"row {ri}: the {a} tcp quaternion has zero norm")
+ for j in range(16):
+ lo, hi = HLIM[a][j]
+ v = row[o + 7 + j]
+ if v < lo or v > hi:
+ clipped.append({"row": ri, "index": int(o + 7 + j), "reason": f"{EE_LAYOUT[o + 7 + j]} outside [{lo:.3f}, {hi:.3f}]: clamped by the simulator"})
+ return row
+
+
+def _clip_joints(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ lo = np.array([ALIM[j][0] for j in JP_LAYOUT]); hi = np.array([ALIM[j][1] for j in JP_LAYOUT])
+ out = np.clip(row, lo, hi)
+ for j in np.flatnonzero(out != row)[:20]:
+ clipped.append({"row": ri, "index": int(j), "reason": f"{JP_LAYOUT[j]} limit [{lo[j]:g}, {hi[j]:g}]"})
+ return out
+
+
+def _native_from_joints(q: np.ndarray) -> np.ndarray:
+ out = []
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ out += [tcp_from_arm_joints(a, q[o:o + 7]), q[o + 7:o + 23]]
+ return np.concatenate(out)
+
+
+def _check_chunk(typ: str, A: np.ndarray, dt: float, interp: str, video: str) -> int:
+ k = dt / DT
+ if A.ndim != 2 or A.shape[1] != ADIM:
+ raise ValueError(f"{typ} actions must be (T, {ADIM}), got {list(A.shape)}")
+ if A.shape[0] == 0:
+ raise ValueError("no rows")
+ 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")
+ return int(round(k))
+
+
+def do_submit(meta: dict, A: np.ndarray):
+ typ = meta.get("type")
+ if typ not in ("ee_pose", "joint_position"):
+ raise ValueError(f"type must be ee_pose or joint_position (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)
+ n = _check_chunk(typ, A, dt, interp, video)
+ clipped: list = []
+ if typ == "ee_pose":
+ A = np.stack([_native_from_ee(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ else:
+ A = np.stack([_clip_joints(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ rec = recorder(cams, fps, meta)
+ E["calls"] += 1
+ step0, before = E["step"], ctrl_steps()
+ rec.tick(force=True)
+ if typ == "ee_pose":
+ prev = np.asarray(S.hold_action(), dtype=np.float64)
+ else:
+ prev = np.concatenate([np.concatenate([D.qpos[QADR[ARM_QI[a]]], S._arm_target(a)[7:23]]) for a in ARMS])
+ for row in A:
+ E["step"] += 1
+ stop = False
+ for s in range(1, n + 1):
+ if interp == "hold" or s == n:
+ target = row # a row's own values land exactly on its last control step
+ else:
+ target = prev + (row - prev) * (s / n)
+ if typ == "ee_pose":
+ for k in range(len(ARMS)):
+ o = 23 * k
+ target[o + 3:o + 7] = M.quat_slerp(prev[o + 3:o + 7], row[o + 3:o + 7], s / n)
+ native = target if typ == "ee_pose" else _native_from_joints(target)
+ if ctrl_step(native, rec):
+ stop = True
+ break
+ prev = row
+ 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"], "type": typ, "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 = np.asarray(S.hold_action(), dtype=np.float64)
+ 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={"task": TASK, "instance_sha": S.instance_sha, "instance_ok": bool(S.instance_exact), "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} DexJoCo sim ready ({TASK}; 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/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/task_text.txt b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/task_text.txt
new file mode 100644
index 0000000000..be41dde800
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/environment/sim/task_text.txt
@@ -0,0 +1,3 @@
+Pick up the iPad and enter the passcode 1-2-3 on its screen. A digit is pressed when a FINGERTIP touches its button; pressing any other digit than the next one of 1-2-3 ends the episode as a failure. Success: the screen is unlocked (1, 2, 3 in order) and stays unlocked for 10 consecutive control steps.
+
+The iPad rests on a stand on the table, screen facing the robots; its keypad shows the digits.
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/instruction.md b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/instruction.md
new file mode 100644
index 0000000000..24037ce04c
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/instruction.md
@@ -0,0 +1,68 @@
+# DexJoCo · bimanual_unlock_ipad — STANDARD MODE (robot as a service, eai-standard/2.2)
+
+You control two Franka Panda arms, each with a 16-DoF Allegro hand, **as if it were real hardware**: the simulator runs in a service you cannot open. You get
+one client and one episode. **Task:** Pick up the iPad and enter the passcode 1-2-3 on its screen. A digit is pressed when a FINGERTIP touches its button; pressing any other digit than the next one of 1-2-3 ends the episode as a failure. Success: the screen is unlocked (1, 2, 3 in order) and stays unlocked for 10 consecutive control steps.
+
+The iPad rests on a stand on the table, screen facing the robots; its keypad shows the digits.
+
+## Rules (real-robot rules)
+- **No reset.** The episode starts when the service comes up and ends on success, on a task failure (see the task), when
+ your time is up, or on a simulator error. Knocked-over objects stay knocked over.
+- **No privileged state.** You see what the cameras see (RGB, and depth on request, with each camera's calibration) plus
+ the robot's own proprioception (joints, tcp poses, the current targets). No object poses, no success check:
+ `meta["done"]` / `meta["reason"]` tell you when the episode is over and why.
+- Steps are unlimited; your wall-clock budget (90 minutes) is the limit (`meta["time_left_s"]`). Actions and
+ simulated time are reported as cost. Do not stop before the task is solved.
+- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
+ `/app/output/gen.py` for the record (save it early, update it as you go).
+- **Nothing is put into your context automatically.** Images and videos come back as arrays/bytes in a Python object;
+ what you look at and where you store it is your code's decision.
+
+## Client (`/opt/tools/rcb_client.py`, protocol `eai-standard/2.2`)
+```python
+from rcb_client import Robot
+r = Robot() # connects (waits while the service starts)
+spec = r.spec() # action types, cameras (+ calibration), proprio layout, robot_spec, kinematics, budget
+obs = r.get_obs() # current frames of spec["default_cameras"]: obs.last[cam] -> uint8 (480, 640, 3)
+obs = r.get_obs(cameras=["back", "handcam_rgb_right"], depth=True) # + obs.last_depth[cam] -> float32 (480, 640) z-depth (m)
+obs.meta["proprio"] # {"layout": [...], "now": [...]}; obs.group("tcp_pose", now=True)
+obs.meta["cameras"] # per camera intrinsic_cv / extrinsic_cv / cam2world_gl for these frames
+obs = r.get_obs(seconds=2.0, video="mp4") # hold the current targets and watch for 2 s (max 30): obs.video[cam] = mp4 bytes
+
+res = r.submit("ee_pose", rows, dt=0.1) # rows: (T, 46) targets dt seconds apart, executed at 50 Hz with interpolation
+res = r.submit("joint_position", q_rows, dt=0.1) # (T, 46) joint targets instead (see below)
+res.meta["done"], res.meta["reason"], res.meta["clipped"], res.meta["control_steps_chunk"]
+res.video["back"]; res.last["back"]; res.proprio # mp4 of the chunk, last frame, float32 (N, P) proprio per frame
+res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, proprio.npy, ...
+r.fk(q); r.ik({"tcp_right": pose}, seed=q) # kinematics of the robot (stateless: no physics, no time)
+r.status() # calls, control steps, done, reason, elapsed time
+```
+Cameras: `back` (static), `handcam_rgb_right`, `handcam_rgb_left` (on the hand mounts; they move,
+so use the calibration that comes with each response; `spec["cameras"][cam]["mount"]` gives the static pose or the mount
+link). Resolution 640x480. Rendering runs on the CPU: ask only for the cameras you need; `video="none"` makes a chunk
+fastest. If a call fails with a connection error the service may have crashed: it resumes the same episode;
+`r.wait_ready()`, then check `r.status()` (`spec["on_service_error"]`).
+
+### Action type `ee_pose` (46) — DexJoCo's own action
+Per arm, right first: tcp target position (3, metres, world frame), tcp target orientation (4, quaternion wxyz), 16
+Allegro joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+target and stops where contact blocks it); the hand joints are position-controlled. Rows are `dt` apart (a whole multiple
+of 1/50 s, at most 0.5 s); between rows positions and joints move linearly and orientations by slerp
+(`interpolate="linear"`) or jump (`"hold"`); a chunk may cover at most 10 s. Hand targets outside the ranges
+(`spec["action_types"]["ee_pose"]["hand_limits"]`) are clamped by the simulator and listed in `meta["clipped"]`. Build
+the next row from the `tcp_target` and `hand_target` proprio groups to move smoothly.
+
+### Action type `joint_position` (46)
+Per arm, right first: 7 Panda joint targets, then the 16 Allegro joint targets (rad). The service turns the arm's targets
+into a tcp target by forward kinematics and the same controller tracks it: the tcp reaches FK(q), but the measured arm
+joints may differ from q in the arm's redundant direction (the controller's null space pulls towards a home posture).
+Out-of-limit values are clipped and reported.
+
+## Conventions
+- World frame, metres, z up; the robots stand at low x and reach towards +x (right arm at y < 0, left arm at y > 0); each
+ arm's base pose is in `spec["robot_spec"]["base"]`. No other world coordinates are given (D7: the cameras are
+ calibrated, depth is available). Quaternions are **WXYZ**.
+- The tcp (`tcp_right`, `tcp_left`) is the hand's mounting flange (`spec["robot_spec"]["tcp"]`), not the fingertips. Allegro joint
+ order (right hand): index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger = spread, 1-3 = flexion
+ from the knuckle out; thumb 12 = opposition). The LEFT hand's 16 values are mirrored: ring 0-3, middle 4-7, index 8-11, thumb 12-15 (the joint names in `spec["proprio_layout"]` say which).
+- Control runs at 50 Hz (10 physics substeps of 2 ms). There is no step budget: your wall-clock time is the limit.
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/solution/oracle_stream.py b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/solution/oracle_stream.py
new file mode 100644
index 0000000000..19877300c1
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/solution/oracle_stream.py
@@ -0,0 +1,43 @@
+"""Oracle (standard mode): streams the reference rows (the human demonstration's own actions, one per 1/50 s control step,
+float32-exact) as `ee_pose` 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
+
+A = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle_trajectory.npz"))["actions"].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(A), flush=True)
+t0, i = time.time(), 0
+while i < len(A):
+ chunk = A[i:i + per_chunk]
+ try:
+ res = r.submit("ee_pose", chunk, dt=dt, interpolate="hold", 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/dexjoco-bimanual-unlock-ipad-i00-standard/solution/oracle_trajectory.npz b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..f860a6ee35
Binary files /dev/null and b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/solution/solve.sh b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/solution/solve.sh
new file mode 100755
index 0000000000..1bd55d898f
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/solution/solve.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+# Oracle (standard mode): streams the reference trajectory's rows (solution/oracle_trajectory.npz, one row per control
+# step) as `ee_pose` chunks through the client. Uses no privileged information at run time (only the pre-recorded rows);
+# the service's recorded trajectory is then exactly the privileged reference.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_stream.py /app/output/gen.py
+python /solution/oracle_stream.py
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/task.toml b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/task.toml
new file mode 100644
index 0000000000..1eab073a13
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/task.toml
@@ -0,0 +1,52 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator 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/dexjoco-bimanual-unlock-ipad-i00-standard"
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): DexJoCo bimanual_unlock_ipad (two Franka Panda arms, each with a 16-DoF Allegro hand) on the same frozen instance as dexjoco-bimanual-unlock-ipad-i00-privileged. Pick up the iPad and enter the passcode 1-2-3 on its screen. The agent only gets a client: calibrated cameras (RGB, optional depth), the robot's joints and tcp poses, tcp-target + hand-joint chunks at 50 Hz, the robot's kinematics; one episode, no reset, no object state; the sim service records the episode, replays it in fresh processes and grades it."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "standard-mode", "robot-as-a-service", "bimanual_unlock_ipad"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro-bimanual"
+family = "bimanual_unlock_ipad"
+mode = "standard"
+protocol = "eai-standard/2.2"
+oracle = "full"
+expert_time_estimate_hours = 2.5
+
+[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 = 3600
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/tests/Dockerfile b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/tests/Dockerfile
new file mode 100644
index 0000000000..26bc699ebe
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-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.sh
diff --git a/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/tests/grade.py b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/tests/grade.py
new file mode 100644
index 0000000000..003b933315
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/tests/grade.py
@@ -0,0 +1,60 @@
+"""Standard-mode verifier (DexJoCo): 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 frozen 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"))),
+ "task_failure": int(bool(d.get("task_failure"))),
+ "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),
+ "calls": int(d.get("calls") or 0),
+ "elapsed_s": float(d.get("elapsed_s") or 0),
+ "video_rendered": int(bool(d.get("video"))),
+ # 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 frozen 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/dexjoco-bimanual-unlock-ipad-i00-standard/tests/test.sh b/tasks/dexjoco-bimanual-unlock-ipad-i00-standard/tests/test.sh
new file mode 100755
index 0000000000..bc608aa8b9
--- /dev/null
+++ b/tasks/dexjoco-bimanual-unlock-ipad-i00-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
diff --git a/tasks/dexjoco-click-mouse-i00-privileged/README.md b/tasks/dexjoco-click-mouse-i00-privileged/README.md
new file mode 100644
index 0000000000..08c9d6f5a3
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-privileged/README.md
@@ -0,0 +1,49 @@
+# dexjoco-click-mouse-i00-privileged
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | privileged |
+| Twin | `dexjoco-click-mouse-i00-standard` |
+| Simulator / robot | `dexjoco` / `franka-allegro` |
+| Family / instance | `click_mouse` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `click_mouse` (a Franka Panda arm with a 16-DoF Allegro hand): Put the computer mouse on the magenta mousepad and click its button. Success: the mouse is on the pad (its centre within the pad's 0.15 m radius horizontally and within 0.05 m of the pad's height), the button has been pressed while the mouse was on the pad (button joint more than 0.001 rad past its rest angle), which turns the monitor blue, and the mouse then stays on the pad for 10 consecutive control steps. A click while the mouse is off the pad does nothing.
+Privileged mode: the agent works in the simulator's container with live object poses, unlimited resets and thin motion
+primitives, and hands in one trajectory replayed open-loop from the frozen instance.
+
+## Difficulty
+First-pass rating: medium. Dexterous manipulation with a 16-DoF hand on a 7-DoF arm (23 action values per control step);
+the primitives only move tcp and hand-joint targets, so grasping, pressing and every other skill is the agent's. The
+reference (the human teleoperator's demonstration) takes 560 control steps (11.2 s at 50 Hz).
+
+## Reference solution
+`solution/oracle_trajectory.npz` = the human demonstration's own actions, rounded to float32 (the standard client's
+precision; the rounded rows still succeed) and replayed from the frozen instance until the episode ends in success
+(560 rows). The demonstration is public (DexJoCo-Datasets-Raw on Hugging Face), so agent egress is
+limited to the model APIs.
+
+## Verification
+Open-loop replay of `/app/output/trajectory.npz` from `tests/instance.npz`, twice in a fresh process in the verifier's own
+sandbox (no network); pass iff both episodes end in success, their final-state hashes agree and the rebuilt instance
+matches its recorded hash (`tests/grade.py`); plus `/logs/verifier/replay.mp4`. Oracle: success after 560 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `monitor_mousepad_demo_10_2026-03-10_20-07-29_950914` (DexJoCo-Datasets-Raw), restored with DexJoCo's own state restorer; instance sha `ad73bedaf42257f0` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Tooling notes
+DexJoCo's reset samples object poses from the global RNG and its state restorer edits the MuJoCo model (table height,
+fixed bodies), so `instance.npz` stores the full physics state (`mjSTATE_INTEGRATION`), the mocap targets, the controls,
+every numeric model array a task can change, and the env's Python-side task state. Its per-step camera rendering,
+real-time sleep, episode cap and hanoi's wall-clock auto-reset are disabled in the tooling (`rcb_dexjoco.py`).
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py` from `scripts/dexjoco/instances/click_mouse/` (`make_instances.py`).
diff --git a/tasks/dexjoco-click-mouse-i00-privileged/environment/Dockerfile b/tasks/dexjoco-click-mouse-i00-privileged/environment/Dockerfile
new file mode 100644
index 0000000000..d736fe8a7d
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-privileged/environment/Dockerfile
@@ -0,0 +1,7 @@
+# Base image = DexJoCo on MuJoCo 3.4.0 (images/dexjoco/). Everything task-specific is copied here. CPU only.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY instance.npz /app/instance.npz
+COPY rcb_dexjoco.py /opt/tools/rcb_dexjoco.py
+ENV PYTHONPATH=/opt/tools
+RUN mkdir -p /app/output
+WORKDIR /app
diff --git a/tasks/dexjoco-click-mouse-i00-privileged/environment/instance.npz b/tasks/dexjoco-click-mouse-i00-privileged/environment/instance.npz
new file mode 100644
index 0000000000..274a4b7352
Binary files /dev/null and b/tasks/dexjoco-click-mouse-i00-privileged/environment/instance.npz differ
diff --git a/tasks/dexjoco-click-mouse-i00-privileged/environment/rcb_dexjoco.py b/tasks/dexjoco-click-mouse-i00-privileged/environment/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-privileged/environment/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-click-mouse-i00-privileged/instruction.md b/tasks/dexjoco-click-mouse-i00-privileged/instruction.md
new file mode 100644
index 0000000000..a14f798ae2
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-privileged/instruction.md
@@ -0,0 +1,88 @@
+# DexJoCo · click_mouse — frozen instance
+
+You control a Franka Panda arm with a 16-DoF Allegro hand (DexJoCo on MuJoCo 3.4) via Python. **Task:** Put the computer mouse on the magenta mousepad and click its button. Success: the mouse is on the pad (its centre within the pad's 0.15 m radius horizontally and within 0.05 m of the pad's height), the button has been pressed while the mouse was on the pad (button joint more than 0.001 rad past its rest angle), which turns the monitor blue, and the mouse then stays on the pad for 10 consecutive control steps. A click while the mouse is off the pad does nothing.
+
+The mouse lies on the table in front of the monitor; the round magenta mousepad is next to it at lower y. The button is a hinge on the mouse's front half. `s.objects()` gives the live poses of the task objects (`mouse`, `mouse_button`, `mousepad`, `monitor`, `table_top`). DexJoCo's success code (from
+`/opt/dexjoco/dexjoco/dexjoco/sim/envs/panda_click_mouse_env.py`; `step()` ends the episode on success or on a task failure):
+```python
+def _compute_success(self) -> bool:
+ # print("mouse_in_mousepad", self._mouse_in_mousepad())
+ trigger_active = self._mouse_in_mousepad() and self._display_blue
+
+ if trigger_active:
+ self._success_trigger_count += 1
+ else:
+ self._success_trigger_count = 0
+
+ return self._success_trigger_count >= self._success_trigger_target
+
+def _mouse_in_mousepad(self) -> bool:
+ try:
+ mouse_pos = self._data.sensor("mouse_pos").data
+ except Exception:
+ return False
+ if self._mousepad_geom_id < 0 or self._mousepad_radius is None:
+ return False
+ pad_center = self._data.geom_xpos[self._mousepad_geom_id]
+ dx, dy, dz = mouse_pos - pad_center
+ in_xy = (dx * dx + dy * dy) <= (self._mousepad_radius * self._mousepad_radius)
+ in_z = abs(dz) <= _MOUSEPAD_Z_TOL
+ return in_xy and in_z
+
+def _detect_click(self) -> bool:
+ try:
+ joint0 = float(self._data.sensor("mouse_joint0_pos").data)
+ except Exception:
+ return False
+ return (joint0 - self._mouse_joint0_init) > _CLICK_THRESHOLD
+```
+
+This is a *fixed scene instance*: object poses, the table height and the robot's start pose never change between
+resets. You may reset and retry as many times as you want. Your deliverable is **one replayable trajectory**, not a
+general policy.
+
+## Deliverable
+Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
+open-loop from the same initial state in a fresh process and scored 1 if its episode ends in success, else 0. Also
+leave the script that produced it at `/app/output/gen.py`. You have 90 minutes of wall clock: save a
+first trajectory early, improve it, and do not stop before the task is solved.
+
+## Tooling (already installed; run `python` from any directory)
+```python
+from rcb_dexjoco import Session
+s = Session("click_mouse", instance="/app/instance.npz") # ~1 s: builds the env and loads the frozen state
+s.reset() # back to the frozen initial state (as often as you like; an exact snapshot restore)
+s.objects() # live task objects: name -> pos, quat_wxyz (bodies) / pos (sites) / qpos (joints)
+s.state() # DexJoCo's state dict: tcp_pose, gripper_pose (hand joints), INITIAL object poses, table height
+p = s.primitives() # thin wrappers of the low-level action; each has a docstring: help(p["move_ee"])
+p["move_ee"]("right", pos, quat_wxyz) # straight-line + slerp motion of an arm's tcp target, then settle
+p["set_hand"]("right", q16) # interpolate the 16 Allegro joint targets
+p["hold"](10); p["set_targets"](row, steps) # keep every target / send one raw action row
+p["get_ee_pose"]("right"); p["get_ee_target"]("right"); p["get_hand"]("right"); p["get_body_pose"](name)
+s.render_frame("front") # RGB uint8 (480, 640, 3); cameras: ['front', 'back', 'left', 'right', 'top0', 'handcam_rgb']; s.render_grid()
+s.step(action) # one control step (23 values, below) = 1/50 s; returns False once the episode is over
+s.record_start(); ...; actions = s.record_stop() # (T, 23) actions, one row per control step
+s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+s.replay(actions) # resets, replays open-loop until the episode ends, returns status -> self-check
+s.save_trajectory(actions, "/app/output/trajectory.npz")
+s.render_video(actions, "/app/output/check.mp4", cameras=["front"]) # replays from the frozen state into a video
+```
+The primitives are deliberately thin (tcp target moves, hand joint targets, hold): grasping, pressing, striking and
+every other skill are yours to build from them. `s.bodies()` lists every MuJoCo body for `p["get_body_pose"]`.
+
+CLI equivalent of the grader:
+`python /opt/tools/rcb_dexjoco.py replay --task click_mouse --instance /app/instance.npz --traj /app/output/trajectory.npz`
+
+## Conventions
+- World frame, metres; z up; the robot stands at low x and reaches towards +x. The table top is at z = 0.927. Arm base (`link0`): link0 [-0.75, 0.0, 0.924]. Quaternions are **WXYZ**.
+- Action (23): tcp target position (3), tcp target orientation (4, wxyz), 16 Allegro
+ joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+ target and stops where contact blocks it); the hand joints are position-controlled. `s.hold_action()` is the no-op.
+ At the start the tcp target is [-0.443, -0.0, 1.517] / [0.0, 1.0, 0.0, 0.0].
+- Allegro joint order: index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger =
+ spread, 1-3 = flexion from the knuckle out; thumb 12 = opposition).
+ Target ranges (rad, same for every finger slot, thumb last): low [-0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, 0.26, -0.1, -0.19, -0.16], high [0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 1.4, 1.16, 1.64, 1.72]; the simulator clamps
+ targets to them.
+- Control runs at 50 Hz (10 physics substeps of 2 ms). DexJoCo's own episode cap and real-time pacing are lifted: there
+ is no step budget, your wall-clock time is the limit (~330 control steps/s here). An episode ends at the
+ first success or task failure; `s.step` then refuses further actions until `s.reset()`.
diff --git a/tasks/dexjoco-click-mouse-i00-privileged/solution/gen.py b/tasks/dexjoco-click-mouse-i00-privileged/solution/gen.py
new file mode 100644
index 0000000000..0e1f7e3bc7
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-privileged/solution/gen.py
@@ -0,0 +1,4 @@
+# How solution/oracle_trajectory.npz was made (scripts/dexjoco/make_instances.py): the DexJoCo human demonstration's
+# own actions (replay.zarr data/action), rounded to float32, replayed from the frozen instance with Session.replay until
+# the episode ended in success (holding the last row a few steps where the rounded rows ended short of a hold count),
+# truncated there and saved with Session.save_trajectory.
diff --git a/tasks/dexjoco-click-mouse-i00-privileged/solution/oracle_trajectory.npz b/tasks/dexjoco-click-mouse-i00-privileged/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..57a35f5ca6
Binary files /dev/null and b/tasks/dexjoco-click-mouse-i00-privileged/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-click-mouse-i00-privileged/solution/solve.sh b/tasks/dexjoco-click-mouse-i00-privileged/solution/solve.sh
new file mode 100755
index 0000000000..7909c90cb8
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-privileged/solution/solve.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+# Reference solution: the human demonstration's actions (float32), replayed through the task tooling until success.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_trajectory.npz /app/output/trajectory.npz
+cp /solution/gen.py /app/output/gen.py
diff --git a/tasks/dexjoco-click-mouse-i00-privileged/task.toml b/tasks/dexjoco-click-mouse-i00-privileged/task.toml
new file mode 100644
index 0000000000..264c6ce384
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-privileged/task.toml
@@ -0,0 +1,37 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator or the instance, not this.
+schema_version = "1.3"
+artifacts = ["/app/output/"]
+
+[task]
+name = "robot-coding-bench/dexjoco-click-mouse-i00-privileged"
+description = "DexJoCo click_mouse (a Franka Panda arm with a 16-DoF Allegro hand, MuJoCo): produce one replayable trajectory. Put the computer mouse on the magenta mousepad and click its button. Frozen scene instance (the initial state of a DexJoCo human demonstration)."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "code-as-policy", "trajectory", "click_mouse"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro"
+family = "click_mouse"
+mode = "privileged"
+oracle = "full"
+expert_time_estimate_hours = 1.5
+
+[verifier]
+timeout_sec = 1800.0
+environment_mode = "separate" # the verifier runs in its own sandbox (tests/Dockerfile); the agent container is gone by then
+network_mode = "no-network"
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
+
+[verifier.environment]
+build_timeout_sec = 1800.0
diff --git a/tasks/dexjoco-click-mouse-i00-privileged/tests/Dockerfile b/tasks/dexjoco-click-mouse-i00-privileged/tests/Dockerfile
new file mode 100644
index 0000000000..a2620a4da8
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-privileged/tests/Dockerfile
@@ -0,0 +1,8 @@
+# Separate verifier sandbox (PROTOCOL §2.6): the same simulator image with the verifier's own copies of the tooling and
+# the frozen instance baked in. Nothing the agent did in its container reaches this one: Harbor uploads only the declared
+# artifacts (/app/output/), so a patched success check in the agent container cannot count.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY grade.py instance.npz rcb_dexjoco.py test.sh /tests/
+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
+ENV PYTHONPATH=/tests
+WORKDIR /tests
diff --git a/tasks/dexjoco-click-mouse-i00-privileged/tests/grade.py b/tasks/dexjoco-click-mouse-i00-privileged/tests/grade.py
new file mode 100644
index 0000000000..ad916e8bb9
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-privileged/tests/grade.py
@@ -0,0 +1,109 @@
+"""Verifier entry point for the privileged DexJoCo tasks: replay /app/output/trajectory.npz from the frozen instance and
+write Harbor rewards.
+
+ python /tests/grade.py --family water_plant --instance /tests/instance.npz --traj /app/output/trajectory.npz
+
+Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only; Harbor rejects strings), a replay video
+/logs/verifier/replay.mp4 (front camera + wrist camera) and replay.last.png. Replays `--repeat` times in this fresh
+process; success requires every replay to end its episode in success (DexJoCo's own rule: the episode ends at the first
+success or task failure) AND all final-state hashes to agree (MuJoCo on the CPU is bit-deterministic), and the frozen
+instance rebuilt here from tests/instance.npz must match its recorded hash.
+"""
+from __future__ import annotations
+import argparse, json, os, sys, time, traceback
+import numpy as np
+
+LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")
+
+
+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 self_reported_cost() -> dict:
+ # From the tooling's append-only log in the agent's container: SELF-REPORTED accounting, never evidence.
+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_records": 0, "agent_replays": 0,
+ "agent_cost_self_reported": 1}
+ try:
+ with open("/app/output/rcb_session_log.jsonl") 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 == "session_end": cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)
+ elif ev == "record": cost["agent_records"] += 1
+ elif ev == "replay": cost["agent_replays"] += 1
+ except Exception: # noqa: BLE001 — one bad line must not sink the verdict
+ continue
+ except Exception: # noqa: BLE001
+ pass
+ return cost
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--family", required=True); ap.add_argument("--instance", required=True)
+ ap.add_argument("--traj", default="/app/output/trajectory.npz"); ap.add_argument("--repeat", type=int, default=2)
+ ap.add_argument("--no-video", action="store_true")
+ a = ap.parse_args()
+ cost = self_reported_cost()
+ os.environ["RCB_SESSION_LOG"] = "" # the verifier's own sessions are not the agent's cost
+ if not os.path.isfile(a.traj):
+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost}); return 0
+ s = None
+ try:
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the verifier's own copy of the tooling
+ import rcb_dexjoco
+ rcb_dexjoco.SESSION_LOG = ""
+ from rcb_dexjoco import Session, MAX_STEPS
+ d = np.load(a.traj, allow_pickle=False)
+ if str(d["task"]) != a.family:
+ write(False, {"success": 0, "wrong_family": 1, "grader_error": 0, **cost}); return 0
+ acts = np.asarray(d["actions"], dtype=np.float64)
+ s = Session(a.family, instance=a.instance)
+ if (acts.ndim != 2 or acts.shape[1] != s.action_dim or acts.shape[0] > MAX_STEPS
+ or not np.all(np.isfinite(acts))):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0,
+ "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0, **cost}); return 0
+ t0 = time.time()
+ outs = []
+ for _ in range(a.repeat):
+ try:
+ outs.append(s.replay(acts))
+ except (ValueError, rcb_dexjoco.PrimitiveError):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0, "n_actions": int(len(acts)), **cost}); return 0
+ all_success = all(o["success"] for o in outs)
+ deterministic = len({o["state_sha"] for o in outs}) == 1
+ instance_ok = bool(s.instance_exact)
+ ok = all_success and deterministic and instance_ok
+ out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
+ "instance_ok": int(instance_ok), "n_actions": int(len(acts)), "sim_steps": int(outs[0]["steps"]),
+ "task_failure": int(bool(outs[0]["reason"]) and not outs[0]["success"]),
+ "replay_wall_s": round(time.time() - t0, 1), "grader_error": 0, "video_rendered": 0, **cost}
+ if not a.no_video: # human-viewable replay (never affects the verdict)
+ try:
+ n = int(outs[0]["replayed_rows"])
+ s.render_video(acts[:n], os.path.join(LOG_DIR, "replay.mp4"), cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ import imageio.v2 as imageio
+ imageio.imwrite(os.path.join(LOG_DIR, "replay.last.png"), s.render_frame(s.default_camera(), (480, 640)))
+ out["video_rendered"] = int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4")))
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(ok, out)
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(False, {"success": 0, "grader_error": 1, **cost})
+ finally:
+ if s is not None:
+ s.close()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tasks/dexjoco-click-mouse-i00-privileged/tests/instance.npz b/tasks/dexjoco-click-mouse-i00-privileged/tests/instance.npz
new file mode 100644
index 0000000000..274a4b7352
Binary files /dev/null and b/tasks/dexjoco-click-mouse-i00-privileged/tests/instance.npz differ
diff --git a/tasks/dexjoco-click-mouse-i00-privileged/tests/rcb_dexjoco.py b/tasks/dexjoco-click-mouse-i00-privileged/tests/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-privileged/tests/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-click-mouse-i00-privileged/tests/test.sh b/tasks/dexjoco-click-mouse-i00-privileged/tests/test.sh
new file mode 100755
index 0000000000..75238fa6ef
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-privileged/tests/test.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in a fresh process.
+# 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/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)
+mkdir -p /logs/verifier
+python /tests/grade.py --family click_mouse --instance /tests/instance.npz --traj /app/output/trajectory.npz --repeat 2 \
+ 2> /logs/verifier/grade.log
diff --git a/tasks/dexjoco-click-mouse-i00-standard/README.md b/tasks/dexjoco-click-mouse-i00-standard/README.md
new file mode 100644
index 0000000000..9cd0c78d76
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-standard/README.md
@@ -0,0 +1,45 @@
+# dexjoco-click-mouse-i00-standard
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | standard (`eai-standard/2.2`) |
+| Twin | `dexjoco-click-mouse-i00-privileged` |
+| Simulator / robot | `dexjoco` / `franka-allegro` |
+| Family / instance | `click_mouse` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `click_mouse` (a Franka Panda arm with a 16-DoF Allegro hand) on the same frozen instance as `dexjoco-click-mouse-i00-privileged`: Put the computer mouse on the magenta mousepad and click its button. Success: the mouse is on the pad (its centre within the pad's 0.15 m radius horizontally and within 0.05 m of the pad's height), the button has been pressed while the mouse was on the pad (button joint more than 0.001 rad past its rest angle), which turns the monitor blue, and the mouse then stays on the pad for 10 consecutive control steps. A click while the mouse is off the pad does nothing.
+Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with the robot's own
+sensors, calibrated cameras (RGB, optional depth) and the robot's kinematics.
+
+## Difficulty
+Same instance and success check as `dexjoco-click-mouse-i00-privileged`. In standard mode the agent loses resets, the
+simulator and the object poses: it sees camera images and proprioception, acts in chunks of tcp-target + hand-joint rows
+(or joint targets), and gets one episode, so it has to close the loop on what the cameras show and recover from its own
+mistakes without starting over.
+
+## Reference solution
+`solution/oracle_stream.py` streams the privileged reference's rows (`solution/oracle_trajectory.npz`, 560 rows, float32-exact)
+through the client as `ee_pose` 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 560 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 560 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `monitor_mousepad_demo_10_2026-03-10_20-07-29_950914` (DexJoCo-Datasets-Raw); instance sha `ad73bedaf42257f0` |
+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); action types `ee_pose` and `joint_position`; cameras `front`, `back`, `left`, `right`, `top0`, `handcam_rgb` (640 x 480); `/kinematics` for the arm links, the hand mount and the tcp; crash recovery class `exact` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py`, as its privileged twin.
diff --git a/tasks/dexjoco-click-mouse-i00-standard/environment/Dockerfile b/tasks/dexjoco-click-mouse-i00-standard/environment/Dockerfile
new file mode 100644
index 0000000000..a778c94561
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-standard/environment/Dockerfile
@@ -0,0 +1,9 @@
+# Standard mode: the agent container has NO simulator and no DexJoCo 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 /app
diff --git a/tasks/dexjoco-click-mouse-i00-standard/environment/client-requirements.txt b/tasks/dexjoco-click-mouse-i00-standard/environment/client-requirements.txt
new file mode 100644
index 0000000000..8aa73a968f
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-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.0
diff --git a/tasks/dexjoco-click-mouse-i00-standard/environment/docker-compose.yaml b/tasks/dexjoco-click-mouse-i00-standard/environment/docker-compose.yaml
new file mode 100644
index 0000000000..e42c3a3305
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-standard/environment/docker-compose.yaml
@@ -0,0 +1,24 @@
+# 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 OSMesa rendering; 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-dexjoco:0.1.2
+ 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_TASK: click_mouse
+ RCB_INSTANCE: /srv/instance.npz
+ RCB_TOOL: /srv/rcb_dexjoco.py
+ RCB_DATA: /data
+ RCB_WALL_CLOCK_S: "5400"
+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in a few seconds
+ PYTHONPATH: /srv
+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction log
diff --git a/tasks/dexjoco-click-mouse-i00-standard/environment/rcb1.py b/tasks/dexjoco-click-mouse-i00-standard/environment/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-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/dexjoco-click-mouse-i00-standard/environment/rcb_client.py b/tasks/dexjoco-click-mouse-i00-standard/environment/rcb_client.py
new file mode 100644
index 0000000000..aa25b0e050
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-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/dexjoco-click-mouse-i00-standard/environment/sim/finalize.sh b/tasks/dexjoco-click-mouse-i00-standard/environment/sim/finalize.sh
new file mode 100755
index 0000000000..e0cf248720
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-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_dexjoco.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:?}"; TASK="${RCB_TASK:?}"
+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 --task "$TASK" --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --repeat 1 \
+ --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"))
+PY
diff --git a/tasks/dexjoco-click-mouse-i00-standard/environment/sim/instance.npz b/tasks/dexjoco-click-mouse-i00-standard/environment/sim/instance.npz
new file mode 100644
index 0000000000..274a4b7352
Binary files /dev/null and b/tasks/dexjoco-click-mouse-i00-standard/environment/sim/instance.npz differ
diff --git a/tasks/dexjoco-click-mouse-i00-standard/environment/sim/rcb1.py b/tasks/dexjoco-click-mouse-i00-standard/environment/sim/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-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/dexjoco-click-mouse-i00-standard/environment/sim/rcb_dexjoco.py b/tasks/dexjoco-click-mouse-i00-standard/environment/sim/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-standard/environment/sim/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-click-mouse-i00-standard/environment/sim/rcb_limited.py b/tasks/dexjoco-click-mouse-i00-standard/environment/sim/rcb_limited.py
new file mode 100644
index 0000000000..1ce1171787
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-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/dexjoco-click-mouse-i00-standard/environment/sim/run.sh b/tasks/dexjoco-click-mouse-i00-standard/environment/sim/run.sh
new file mode 100755
index 0000000000..49d4d045d4
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-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; done
diff --git a/tasks/dexjoco-click-mouse-i00-standard/environment/sim/server.py b/tasks/dexjoco-click-mouse-i00-standard/environment/sim/server.py
new file mode 100644
index 0000000000..ca5b61fc5c
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-standard/environment/sim/server.py
@@ -0,0 +1,625 @@
+"""eai-standard/2.2 sim service for DexJoCo (docs/STANDARD_MODE_2_2.md): the adapter of the shared layer rcb_limited.py;
+the simulator is rcb_dexjoco.Session (DexJoCo on MuJoCo 3.4, CPU physics, OSMesa rendering).
+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to
+/data/episode.jsonl.
+
+The robot is a Franka Panda with a 16-DoF Allegro hand, or two of them side by side (right arm first). One control step
+= 1/50 s (10 physics substeps of 2 ms). Two action types:
+ ee_pose DexJoCo's own row, per arm: the tcp target pose (xyz m, quaternion wxyz, world frame) that its
+ operational-space controller tracks + 16 Allegro joint targets (rad);
+ joint_position per arm: 7 arm joint targets + 16 Allegro joint targets; the arm's targets are turned into a tcp target
+ by forward kinematics (the controller tracks the tcp pose, not the joints).
+Either way, the executed (journaled, recorded) row is DexJoCo's own row, so the recorded trajectory replays in the
+privileged tooling unchanged. As in DexJoCo's evaluation the episode ends at the first success or task failure;
+otherwise when the agent's time is over (the collect hook's SIGUSR1).
+
+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 instance 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")
+TASK = os.environ.get("RCB_TASK", "water_plant")
+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.npz"))
+TASK_TEXT_FILE = os.environ.get("RCB_TASK_TEXT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "task_text.txt"))
+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "5400"))
+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 = 640, 480
+CTRL_HZ = 50.0
+DT = 1.0 / CTRL_HZ
+SUBSTEPS = 10
+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"] = "" # the sidecar's Session is not the agent's interaction log
+import rcb_dexjoco as M # noqa: E402
+import mujoco # noqa: E402
+
+M.SESSION_LOG = ""
+BIM = TASK.startswith("bimanual_")
+ADIM = 46 if BIM else 23
+EP = L.Episode(DATA, dim=ADIM, resume="exact")
+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()
+S = M.Session(TASK, instance=INSTANCE, image_size=(CAM_H, CAM_W))
+MD, D = S.model, S.data
+ARMS = S.arms()
+SFX = {a: (f"_{a}" if BIM else "") for a in ARMS}
+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz
+
+# ------------------------------------------------------------------------------------------------- the robot
+ARM_JOINTS = {a: [f"joint{i}{SFX[a]}" for i in range(1, 8)] for a in ARMS}
+HAND_CTRL = {a: np.asarray(S._hand_ctrl_ids(a)) for a in ARMS}
+HAND_JOINTS = {a: [MD.joint(int(MD.actuator_trnid[i, 0])).name for i in HAND_CTRL[a]] for a in ARMS} # action order
+ARM_CTRL = {a: [MD.actuator(f"actuator{i}{SFX[a]}").id for i in range(1, 8)] for a in ARMS}
+JOINTS = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]] # kinematics q = proprio joint_pos columns
+QADR = np.array([MD.jnt_qposadr[MD.joint(j).id] for j in JOINTS])
+VADR = np.array([MD.jnt_dofadr[MD.joint(j).id] for j in JOINTS])
+EFF_ACT = np.array([i for a in ARMS for i in list(ARM_CTRL[a]) + list(HAND_CTRL[a])])
+TCP_SITE = {a: MD.site(f"attachment_site{SFX[a]}").id for a in ARMS}
+TCP = {a: f"tcp{SFX[a]}" for a in ARMS}
+MOUNT_BODY = {a: f"attachment{SFX[a]}" for a in ARMS}
+LINKS = {a: [f"link{i}{SFX[a]}" for i in range(0, 8) if mujoco.mj_name2id(MD, mujoco.mjtObj.mjOBJ_BODY, f"link{i}{SFX[a]}") >= 0]
+ + [MOUNT_BODY[a]] for a in ARMS}
+KIN_LINKS = [n for a in ARMS for n in LINKS[a] + [TCP[a]]]
+JLIM = {j: MD.jnt_range[MD.joint(j).id].astype(float).tolist() for j in JOINTS}
+HLIM = {a: S.hand_limits(a) for a in ARMS} # actuator ctrlrange, action order
+ALIM = {} # joint_position limits (inside the joint ranges)
+for a in ARMS:
+ for j in ARM_JOINTS[a]:
+ ALIM[j] = JLIM[j]
+ for j, (lo, hi) in zip(HAND_JOINTS[a], HLIM[a]):
+ ALIM[j] = [max(float(lo), JLIM[j][0]), min(float(hi), JLIM[j][1])]
+POSE = ["x", "y", "z", "qw", "qx", "qy", "qz"]
+EE_LAYOUT = [] # per arm, right first
+for a in ARMS:
+ EE_LAYOUT += [f"{TCP[a]}_target_{k}" for k in POSE] + [f"{j}_target" for j in HAND_JOINTS[a]]
+JP_LAYOUT = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]]
+
+GROUPS = [
+ ("joint_pos", JOINTS, "measured joint positions (rad): per arm (right first) the 7 Panda joints, then the 16 Allegro "
+ "joints in the action's order"),
+ ("joint_vel", [f"{j}_vel" for j in JOINTS], "measured joint velocities (rad/s)"),
+ ("joint_effort", [f"{j}_effort" for j in JOINTS], "actuator efforts (N m): the arm's operational-space torques and the "
+ "hand's position-actuator forces"),
+ ("gripper_opening", [], "none: a 16-DoF Allegro hand, its finger joints are in joint_pos"),
+ ("tcp_pose", [f"{TCP[a]}_{k}" for a in ARMS for k in POSE], "measured tcp pose per arm (x y z m, quaternion wxyz, world)"),
+ ("tcp_target", [f"{TCP[a]}_target_{k}" for a in ARMS for k in POSE], "the tcp target the controller tracks now (the "
+ "ee_pose part of the last executed row)"),
+ ("hand_target", [f"{j}_target" for a in ARMS for j in HAND_JOINTS[a]], "the Allegro joint targets now (rad)"),
+]
+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)
+
+
+def _quat(xmat) -> np.ndarray:
+ q = np.zeros(4)
+ mujoco.mju_mat2Quat(q, np.asarray(xmat, dtype=np.float64).reshape(9))
+ return q
+
+
+# ------------------------------------------------------------------------------------------------- cameras
+CAMS = S.cameras()
+HAND_CAMS = [c for c in CAMS if c.startswith("handcam")]
+DEFAULT_CAMS = [S.default_camera()]
+GL2CV = np.diag([1.0, -1.0, -1.0, 1.0])
+
+
+def _intrinsic(cam: str) -> list:
+ fovy = math.radians(float(MD.cam_fovy[MD.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 _cam2world_gl(cam: str) -> np.ndarray:
+ i = MD.camera(cam).id
+ T = np.eye(4)
+ T[:3, :3] = D.cam_xmat[i].reshape(3, 3) # MuJoCo camera axes: OpenGL (x right, y up, z back)
+ T[:3, 3] = D.cam_xpos[i]
+ return T
+
+
+def _extrinsic(cam: str) -> np.ndarray:
+ return np.linalg.inv(_cam2world_gl(cam) @ GL2CV)[:3, :]
+
+
+def camera_info(cam: str) -> dict:
+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist(),
+ "image_size": [CAM_W, CAM_H]}
+
+
+def _mount(cam: str) -> dict:
+ i = MD.camera(cam).id
+ body = MD.body(int(MD.cam_bodyid[i])).name
+ if int(MD.cam_bodyid[i]) == 0:
+ return {"type": "static", "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist()}
+ T = np.eye(4) # body -> camera (OpenGL axes), then to OpenCV axes
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.cam_quat[i])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.cam_pos[i]
+ return {"type": "link", "parent_link": body, "link_T_cam_cv": (T @ GL2CV).tolist()}
+
+
+def _mounted(cam: str) -> str:
+ if cam.startswith("handcam"):
+ side = "the right" if cam.endswith("_right") else "the left" if cam.endswith("_left") else "the"
+ return f"on {side} hand's mount (moves with the hand)"
+ return {"front": "static, across the table, facing the robot", "back": "static, behind the robot, looking over the table",
+ "left": "static, at the robot's left", "right": "static, at the robot's right",
+ "top0": "static, above the table, looking down"}.get(cam, "static")
+
+
+# ------------------------------------------------------------------------------------------------- kinematics
+KD = mujoco.MjData(MD) # kinematics only: never stepped; the robot's joints are set, everything else stays put
+ARM_QI = {a: [JOINTS.index(j) for j in ARM_JOINTS[a]] for a in ARMS}
+
+
+def _fk(q) -> None:
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR] = np.asarray(q, dtype=np.float64)
+ mujoco.mj_kinematics(MD, KD)
+
+
+def _link_pose(name: str) -> list:
+ for a in ARMS:
+ if name == TCP[a]:
+ s = TCP_SITE[a]
+ return [*KD.site_xpos[s].tolist(), *_quat(KD.site_xmat[s]).tolist()]
+ b = MD.body(name).id
+ return [*KD.xpos[b].tolist(), *KD.xquat[b].tolist()]
+
+
+def tcp_from_arm_joints(a: str, q7) -> np.ndarray:
+ """The tcp pose (xyz + wxyz) of arm `a` with its 7 joints at q7 (the joint_position action's tcp target)."""
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR[ARM_QI[a]]] = q7
+ mujoco.mj_kinematics(MD, KD)
+ s = TCP_SITE[a]
+ return np.concatenate([KD.site_xpos[s], _quat(KD.site_xmat[s])])
+
+
+def do_kinematics(req: dict) -> dict:
+ """World frame. FK: every link of spec kinematics.links for q. IK: per tcp target, damped least squares over that
+ arm's 7 joints (position and orientation), within the joint ranges; the hand joints are taken from the seed."""
+ if req["op"] == "fk":
+ _fk(req["q"])
+ return L.fk_response({n: _link_pose(n) for n in req["links"]}, "world")
+ q = np.array(req["seed"] if req["seed"] is not None else D.qpos[QADR], dtype=np.float64)
+ errors = {}
+ jp, jr = np.zeros((3, MD.nv)), np.zeros((3, MD.nv))
+ for frame, pose in req["targets"].items():
+ a = next(x for x in ARMS if TCP[x] == frame)
+ idx = ARM_QI[a]
+ dofs = VADR[idx]
+ tp, tq = np.asarray(pose[:3]), np.asarray(pose[3:7])
+ lo = np.array([JLIM[JOINTS[i]][0] for i in idx]); hi = np.array([JLIM[JOINTS[i]][1] for i in idx])
+ for _ in range(req["max_iters"]):
+ _fk(q)
+ mujoco.mj_comPos(MD, KD) # the Jacobian needs cdof, which mj_kinematics alone leaves stale
+ s = TCP_SITE[a]
+ ep = tp - KD.site_xpos[s]
+ cq = _quat(KD.site_xmat[s])
+ dq = np.zeros(4); neg = np.zeros(4); er = np.zeros(3)
+ mujoco.mju_negQuat(neg, cq); mujoco.mju_mulQuat(dq, tq, neg); mujoco.mju_quat2Vel(er, dq, 1.0)
+ if np.linalg.norm(ep) < req["tol_pos_m"] and np.linalg.norm(er) < req["tol_rot_rad"]:
+ break
+ mujoco.mj_jacSite(MD, KD, jp, jr, s)
+ J = np.vstack([jp[:, dofs], jr[:, dofs]])
+ err = np.concatenate([ep, er])
+ step = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), err)
+ q[idx] = np.clip(q[idx] + step, lo, hi)
+ _fk(q)
+ s = TCP_SITE[a]
+ errors[frame] = (float(np.linalg.norm(tp - KD.site_xpos[s])), L.quat_angle(_quat(KD.site_xmat[s]), tq / np.linalg.norm(tq)))
+ ok = all(e[0] <= req["tol_pos_m"] and e[1] <= req["tol_rot_rad"] for e in errors.values())
+ return L.ik_response(q, ok, errors, "world", note="the tcp (attachment_site) of each arm; the hand joints are the seed's")
+
+
+# ------------------------------------------------------------------------------------------------- spec
+def _joint_spec(a: str) -> list:
+ out = []
+ for j, ai in zip(ARM_JOINTS[a], ARM_CTRL[a]):
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_ctrlrange[ai][1]), "group": f"{a}_arm"})
+ for j, ai in zip(HAND_JOINTS[a], HAND_CTRL[a]):
+ fl = bool(MD.actuator_forcelimited[ai]) and float(MD.actuator_forcerange[ai][1]) > 0
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_forcerange[ai][1]) if fl else None, "group": f"{a}_hand"})
+ return out
+
+
+def _tcp_spec(a: str) -> dict:
+ s = TCP_SITE[a]
+ T = np.eye(4)
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.site_quat[s])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.site_pos[s]
+ return {"parent_link": MD.body(int(MD.site_bodyid[s])).name, "link_T_frame": T.tolist(),
+ "definition": "DexJoCo's attachment_site: the flange where the Allegro hand is mounted, the point its "
+ "operational-space controller drives to the ee_pose target (not the fingertips)"}
+
+
+def _base(a: str) -> list:
+ b = D.body(f"link0{SFX[a]}")
+ return [*np.round(b.xpos, 6).tolist(), *np.round(b.xquat, 6).tolist()]
+
+
+GAINS = {}
+for _a in ARMS:
+ for _j, _ai in zip(HAND_JOINTS[_a], HAND_CTRL[_a]):
+ GAINS[_j] = {"stiffness": float(MD.actuator_gainprm[_ai][0]), "damping": float(MD.dof_damping[MD.jnt_dofadr[MD.joint(_j).id]])}
+ROBOT_NAME = "franka-allegro-bimanual" if BIM else "franka-allegro"
+try:
+ TASK_TEXT = open(TASK_TEXT_FILE).read().strip()
+except OSError:
+ TASK_TEXT = f"DexJoCo {TASK}"
+SPEC = {
+ "protocol": L.PROTOCOL,
+ "protocol_compat": list(L.COMPAT),
+ "simulator": "DexJoCo @ 8d23b0f on MuJoCo 3.4.0 (CPU physics, OSMesa rendering)",
+ "robot": ROBOT_NAME,
+ "task_text": TASK_TEXT,
+ "control_hz": CTRL_HZ,
+ "physics_substeps": SUBSTEPS,
+ "physics_hz": CTRL_HZ * SUBSTEPS,
+ "max_chunk_s": MAX_CHUNK_S,
+ "max_watch_s": MAX_WATCH_S,
+ "cameras": {c: {"rgb": True, "depth": True, "mounted": _mounted(c), "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),
+ "mount": _mount(c)} for c in CAMS},
+ "default_cameras": DEFAULT_CAMS,
+ "action_types": {
+ "ee_pose": {
+ "dim": ADIM, "layout": EE_LAYOUT,
+ "units": "per arm (right first): tcp target position (m, world frame), tcp target orientation (quaternion wxyz), "
+ "16 Allegro joint targets (rad)",
+ "frame": "world", "quaternion_order": "wxyz", "ee_frames": [TCP[a] for a in ARMS],
+ "hand_limits": {j: ALIM[j] for a in ARMS for j in HAND_JOINTS[a]},
+ "semantics": "DexJoCo's own action row. The arm tracks the tcp target through DexJoCo's operational-space "
+ "controller (it lags a moving target and stops where contact blocks it); the hand joints are "
+ "position-controlled. Rows are `dt` apart (a whole multiple of 1/50 s, at most 0.5 s); between rows "
+ "positions and joints move linearly and orientations by slerp (`linear`) or jump (`hold`); a row's "
+ "own values land exactly on its last control step. Hand targets outside the ranges are clamped by "
+ "the simulator and reported in `clipped`; a zero quaternion is a 400.",
+ },
+ "joint_position": {
+ "dim": ADIM, "layout": JP_LAYOUT, "units": "rad", "limits": {j: ALIM[j] for j in JP_LAYOUT},
+ "semantics": "per arm (right first): 7 Panda joint targets, then the 16 Allegro joint targets. The arm's "
+ "targets are turned into a tcp target by forward kinematics (as POST /kinematics fk) and the arm "
+ "tracks that pose through the same operational-space controller as ee_pose, whose null space "
+ "pulls towards DexJoCo's home posture: the tcp reaches FK(q), the measured joints may differ from q "
+ "in the arm's redundant direction. Rows `dt` apart, `linear` (in joint space) or `hold`; values "
+ "outside the limits are clipped and reported.",
+ },
+ "not_yet": ["joint_delta", "joint_velocity", "ee_delta", "joint_torque"],
+ },
+ "proprio_layout": PROPRIO_LAYOUT,
+ "proprio_groups": PROPRIO_GROUPS,
+ "static": {},
+ "world": {"frame": "DexJoCo's world frame: z up, metres; the robot" + ("s stand" if BIM else " stands")
+ + " at low x and reach" + ("" if BIM else "es") + " towards +x"
+ + (" (right arm at y < 0, left arm at y > 0)" if BIM else ""),
+ "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},
+ "episode": "one episode, no reset: it ends at the first success, at a task failure (see task_text), or when your time is over",
+ "robot_spec": {
+ "name": ROBOT_NAME,
+ "description": ("two Franka Panda arms side by side, each with a 16-DoF Allegro hand (right arm first)" if BIM
+ else "a Franka Panda arm with a 16-DoF Allegro hand"),
+ "base": {"type": "fixed", "pose": _base(ARMS[0]), **({"per_arm": {a: _base(a) for a in ARMS}} if BIM else {}),
+ "note": "pose of the arm's base link (link0), world frame, x y z + quaternion wxyz"},
+ "joints": [j for a in ARMS for j in _joint_spec(a)],
+ "grippers": {},
+ "controller": {"type": "arm: operational-space control of the tcp (torques); hand: joint position actuators",
+ "control_hz": CTRL_HZ, "physics_hz": CTRL_HZ * SUBSTEPS, "gains": GAINS,
+ "note": "arm: DexJoCo's opspace controller drives attachment_site to the tcp target (position gains "
+ "400 N/m, damping ratio 4, gravity compensation, null space towards the home posture), "
+ "torques limited to effort_limit; hand: position actuators (stiffness N m/rad) on joints "
+ "with their own damping (N m s/rad)"},
+ "tcp": {TCP[a]: _tcp_spec(a) for a in ARMS},
+ },
+ "kinematics": {"endpoint": "/kinematics", "joint_names": JOINTS, "frame": "world", "quaternion_order": "wxyz",
+ "links": KIN_LINKS, "tcp_frames": [TCP[a] for a in ARMS], "ee_frames": [TCP[a] for a in ARMS],
+ "ik_targets": [TCP[a] for a in ARMS], "ik": {"tol_pos_m": 0.001, "tol_rot_rad": 0.01, "max_iters": 300},
+ "note": "the arm links, the hand mount (the hand cameras' parent) and the tcp, world frame; ik solves "
+ "each tcp target over that arm's 7 joints"},
+ "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()
+
+
+# ------------------------------------------------------------------------------------------------- state and frames
+def ctrl_steps() -> int:
+ return int(S.steps)
+
+
+def proprio_row() -> np.ndarray:
+ tcp, tgt, hand = [], [], []
+ for a in ARMS:
+ s = TCP_SITE[a]
+ tcp += [D.site_xpos[s], _quat(D.site_xmat[s])]
+ t = S._arm_target(a)
+ tgt.append(t[:7]); hand.append(t[7:23])
+ return np.concatenate([D.qpos[QADR], D.qvel[VADR], D.actuator_force[EFF_ACT], *tcp, *tgt, *hand]).astype(np.float32)
+
+
+def grab(cams, want_depth: bool):
+ rgb, dep = {}, {}
+ for c in cams:
+ rgb[c] = S.render_frame(c, (CAM_H, CAM_W))
+ if want_depth:
+ r = S._renderer # the one renderer (a second OSMesa context reads back garbage)
+ r.enable_depth_rendering()
+ try:
+ r.update_scene(D, camera=c)
+ dep[c] = r.render().astype(np.float32).copy()
+ finally:
+ r.disable_depth_rendering()
+ return rgb, dep
+
+
+def extrinsics(cams) -> dict:
+ return {c: _extrinsic(c) for c in cams}
+
+
+def summary() -> dict:
+ n = int(E.get("episode_control_steps") or ctrl_steps())
+ 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"],
+ "task": TASK, "protocol": L.PROTOCOL, "n_actions": len(ROWS), "task_failure": int(str(E["reason"] or "").startswith("failure")),
+ **EP.final_fields()}
+
+
+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 finish(reason: str) -> None:
+ """The episode is over: record the live verdict and dump the trajectory 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()
+ E["success"] = bool(S.success)
+ 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()
+ S.save_trajectory(np.asarray(ROWS, dtype=np.float64).reshape(-1, ADIM), os.path.join(DATA, "trajectory.npz"),
+ {"source": "standard-mode episode", "reason": E["reason"]})
+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})
+ write_final()
+
+
+def ctrl_step(a, rec) -> bool:
+ """One executed control step (DexJoCo's own row), journaled. True when the call must stop here."""
+ a = np.asarray(a, dtype=np.float64)
+ running = S.step(a)
+ ROWS.append(a.copy())
+ stop = EP.journal(a)
+ rec.tick()
+ if not running:
+ finish(S.reason or "done")
+ 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 DEFAULT_CAMS
+ if not isinstance(cams, list) or any(c not in CAMS for c in cams):
+ raise ValueError(f"unknown cameras {cams}; cameras: {CAMS}")
+ return list(dict.fromkeys(cams))
+
+
+def meta_common(cams) -> dict:
+ n = ctrl_steps()
+ return {"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}}
+
+
+def _native_from_ee(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ """ee_pose rows are executed as sent (the recorded row is what the agent commanded); hand targets outside the
+ actuator ranges are clamped by MuJoCo itself (ctrllimited) and only reported."""
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ if float(np.linalg.norm(row[o + 3:o + 7])) < 1e-6:
+ raise ValueError(f"row {ri}: the {a} tcp quaternion has zero norm")
+ for j in range(16):
+ lo, hi = HLIM[a][j]
+ v = row[o + 7 + j]
+ if v < lo or v > hi:
+ clipped.append({"row": ri, "index": int(o + 7 + j), "reason": f"{EE_LAYOUT[o + 7 + j]} outside [{lo:.3f}, {hi:.3f}]: clamped by the simulator"})
+ return row
+
+
+def _clip_joints(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ lo = np.array([ALIM[j][0] for j in JP_LAYOUT]); hi = np.array([ALIM[j][1] for j in JP_LAYOUT])
+ out = np.clip(row, lo, hi)
+ for j in np.flatnonzero(out != row)[:20]:
+ clipped.append({"row": ri, "index": int(j), "reason": f"{JP_LAYOUT[j]} limit [{lo[j]:g}, {hi[j]:g}]"})
+ return out
+
+
+def _native_from_joints(q: np.ndarray) -> np.ndarray:
+ out = []
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ out += [tcp_from_arm_joints(a, q[o:o + 7]), q[o + 7:o + 23]]
+ return np.concatenate(out)
+
+
+def _check_chunk(typ: str, A: np.ndarray, dt: float, interp: str, video: str) -> int:
+ k = dt / DT
+ if A.ndim != 2 or A.shape[1] != ADIM:
+ raise ValueError(f"{typ} actions must be (T, {ADIM}), got {list(A.shape)}")
+ if A.shape[0] == 0:
+ raise ValueError("no rows")
+ 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")
+ return int(round(k))
+
+
+def do_submit(meta: dict, A: np.ndarray):
+ typ = meta.get("type")
+ if typ not in ("ee_pose", "joint_position"):
+ raise ValueError(f"type must be ee_pose or joint_position (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)
+ n = _check_chunk(typ, A, dt, interp, video)
+ clipped: list = []
+ if typ == "ee_pose":
+ A = np.stack([_native_from_ee(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ else:
+ A = np.stack([_clip_joints(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ rec = recorder(cams, fps, meta)
+ E["calls"] += 1
+ step0, before = E["step"], ctrl_steps()
+ rec.tick(force=True)
+ if typ == "ee_pose":
+ prev = np.asarray(S.hold_action(), dtype=np.float64)
+ else:
+ prev = np.concatenate([np.concatenate([D.qpos[QADR[ARM_QI[a]]], S._arm_target(a)[7:23]]) for a in ARMS])
+ for row in A:
+ E["step"] += 1
+ stop = False
+ for s in range(1, n + 1):
+ if interp == "hold" or s == n:
+ target = row # a row's own values land exactly on its last control step
+ else:
+ target = prev + (row - prev) * (s / n)
+ if typ == "ee_pose":
+ for k in range(len(ARMS)):
+ o = 23 * k
+ target[o + 3:o + 7] = M.quat_slerp(prev[o + 3:o + 7], row[o + 3:o + 7], s / n)
+ native = target if typ == "ee_pose" else _native_from_joints(target)
+ if ctrl_step(native, rec):
+ stop = True
+ break
+ prev = row
+ 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"], "type": typ, "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 = np.asarray(S.hold_action(), dtype=np.float64)
+ 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={"task": TASK, "instance_sha": S.instance_sha, "instance_ok": bool(S.instance_exact), "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} DexJoCo sim ready ({TASK}; 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/dexjoco-click-mouse-i00-standard/environment/sim/task_text.txt b/tasks/dexjoco-click-mouse-i00-standard/environment/sim/task_text.txt
new file mode 100644
index 0000000000..6feb4f60db
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-standard/environment/sim/task_text.txt
@@ -0,0 +1,3 @@
+Put the computer mouse on the magenta mousepad and click its button. Success: the mouse is on the pad (its centre within the pad's 0.15 m radius horizontally and within 0.05 m of the pad's height), the button has been pressed while the mouse was on the pad (button joint more than 0.001 rad past its rest angle), which turns the monitor blue, and the mouse then stays on the pad for 10 consecutive control steps. A click while the mouse is off the pad does nothing.
+
+The mouse lies on the table in front of the monitor; the round magenta mousepad is next to it at lower y. The button is a hinge on the mouse's front half.
diff --git a/tasks/dexjoco-click-mouse-i00-standard/instruction.md b/tasks/dexjoco-click-mouse-i00-standard/instruction.md
new file mode 100644
index 0000000000..0343404325
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-standard/instruction.md
@@ -0,0 +1,68 @@
+# DexJoCo · click_mouse — STANDARD MODE (robot as a service, eai-standard/2.2)
+
+You control a Franka Panda arm with a 16-DoF Allegro hand, **as if it were real hardware**: the simulator runs in a service you cannot open. You get
+one client and one episode. **Task:** Put the computer mouse on the magenta mousepad and click its button. Success: the mouse is on the pad (its centre within the pad's 0.15 m radius horizontally and within 0.05 m of the pad's height), the button has been pressed while the mouse was on the pad (button joint more than 0.001 rad past its rest angle), which turns the monitor blue, and the mouse then stays on the pad for 10 consecutive control steps. A click while the mouse is off the pad does nothing.
+
+The mouse lies on the table in front of the monitor; the round magenta mousepad is next to it at lower y. The button is a hinge on the mouse's front half.
+
+## Rules (real-robot rules)
+- **No reset.** The episode starts when the service comes up and ends on success, on a task failure (see the task), when
+ your time is up, or on a simulator error. Knocked-over objects stay knocked over.
+- **No privileged state.** You see what the cameras see (RGB, and depth on request, with each camera's calibration) plus
+ the robot's own proprioception (joints, tcp poses, the current targets). No object poses, no success check:
+ `meta["done"]` / `meta["reason"]` tell you when the episode is over and why.
+- Steps are unlimited; your wall-clock budget (90 minutes) is the limit (`meta["time_left_s"]`). Actions and
+ simulated time are reported as cost. Do not stop before the task is solved.
+- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
+ `/app/output/gen.py` for the record (save it early, update it as you go).
+- **Nothing is put into your context automatically.** Images and videos come back as arrays/bytes in a Python object;
+ what you look at and where you store it is your code's decision.
+
+## Client (`/opt/tools/rcb_client.py`, protocol `eai-standard/2.2`)
+```python
+from rcb_client import Robot
+r = Robot() # connects (waits while the service starts)
+spec = r.spec() # action types, cameras (+ calibration), proprio layout, robot_spec, kinematics, budget
+obs = r.get_obs() # current frames of spec["default_cameras"]: obs.last[cam] -> uint8 (480, 640, 3)
+obs = r.get_obs(cameras=["front", "handcam_rgb"], depth=True) # + obs.last_depth[cam] -> float32 (480, 640) z-depth (m)
+obs.meta["proprio"] # {"layout": [...], "now": [...]}; obs.group("tcp_pose", now=True)
+obs.meta["cameras"] # per camera intrinsic_cv / extrinsic_cv / cam2world_gl for these frames
+obs = r.get_obs(seconds=2.0, video="mp4") # hold the current targets and watch for 2 s (max 30): obs.video[cam] = mp4 bytes
+
+res = r.submit("ee_pose", rows, dt=0.1) # rows: (T, 23) targets dt seconds apart, executed at 50 Hz with interpolation
+res = r.submit("joint_position", q_rows, dt=0.1) # (T, 23) joint targets instead (see below)
+res.meta["done"], res.meta["reason"], res.meta["clipped"], res.meta["control_steps_chunk"]
+res.video["front"]; res.last["front"]; res.proprio # mp4 of the chunk, last frame, float32 (N, P) proprio per frame
+res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, proprio.npy, ...
+r.fk(q); r.ik({"tcp": pose}, seed=q) # kinematics of the robot (stateless: no physics, no time)
+r.status() # calls, control steps, done, reason, elapsed time
+```
+Cameras: `front`, `back`, `left`, `right`, `top0` (static), `handcam_rgb` (on the hand mount; they move,
+so use the calibration that comes with each response; `spec["cameras"][cam]["mount"]` gives the static pose or the mount
+link). Resolution 640x480. Rendering runs on the CPU: ask only for the cameras you need; `video="none"` makes a chunk
+fastest. If a call fails with a connection error the service may have crashed: it resumes the same episode;
+`r.wait_ready()`, then check `r.status()` (`spec["on_service_error"]`).
+
+### Action type `ee_pose` (23) — DexJoCo's own action
+tcp target position (3, metres, world frame), tcp target orientation (4, quaternion wxyz), 16
+Allegro joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+target and stops where contact blocks it); the hand joints are position-controlled. Rows are `dt` apart (a whole multiple
+of 1/50 s, at most 0.5 s); between rows positions and joints move linearly and orientations by slerp
+(`interpolate="linear"`) or jump (`"hold"`); a chunk may cover at most 10 s. Hand targets outside the ranges
+(`spec["action_types"]["ee_pose"]["hand_limits"]`) are clamped by the simulator and listed in `meta["clipped"]`. Build
+the next row from the `tcp_target` and `hand_target` proprio groups to move smoothly.
+
+### Action type `joint_position` (23)
+7 Panda joint targets, then the 16 Allegro joint targets (rad). The service turns the arm's targets
+into a tcp target by forward kinematics and the same controller tracks it: the tcp reaches FK(q), but the measured arm
+joints may differ from q in the arm's redundant direction (the controller's null space pulls towards a home posture).
+Out-of-limit values are clipped and reported.
+
+## Conventions
+- World frame, metres, z up; the robot stands at low x and reaches towards +x; each
+ arm's base pose is in `spec["robot_spec"]["base"]`. No other world coordinates are given (D7: the cameras are
+ calibrated, depth is available). Quaternions are **WXYZ**.
+- The tcp (`tcp`) is the hand's mounting flange (`spec["robot_spec"]["tcp"]`), not the fingertips. Allegro joint
+ order: index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger = spread, 1-3 = flexion
+ from the knuckle out; thumb 12 = opposition).
+- Control runs at 50 Hz (10 physics substeps of 2 ms). There is no step budget: your wall-clock time is the limit.
diff --git a/tasks/dexjoco-click-mouse-i00-standard/solution/oracle_stream.py b/tasks/dexjoco-click-mouse-i00-standard/solution/oracle_stream.py
new file mode 100644
index 0000000000..19877300c1
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-standard/solution/oracle_stream.py
@@ -0,0 +1,43 @@
+"""Oracle (standard mode): streams the reference rows (the human demonstration's own actions, one per 1/50 s control step,
+float32-exact) as `ee_pose` 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
+
+A = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle_trajectory.npz"))["actions"].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(A), flush=True)
+t0, i = time.time(), 0
+while i < len(A):
+ chunk = A[i:i + per_chunk]
+ try:
+ res = r.submit("ee_pose", chunk, dt=dt, interpolate="hold", 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/dexjoco-click-mouse-i00-standard/solution/oracle_trajectory.npz b/tasks/dexjoco-click-mouse-i00-standard/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..57a35f5ca6
Binary files /dev/null and b/tasks/dexjoco-click-mouse-i00-standard/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-click-mouse-i00-standard/solution/solve.sh b/tasks/dexjoco-click-mouse-i00-standard/solution/solve.sh
new file mode 100755
index 0000000000..1bd55d898f
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-standard/solution/solve.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+# Oracle (standard mode): streams the reference trajectory's rows (solution/oracle_trajectory.npz, one row per control
+# step) as `ee_pose` chunks through the client. Uses no privileged information at run time (only the pre-recorded rows);
+# the service's recorded trajectory is then exactly the privileged reference.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_stream.py /app/output/gen.py
+python /solution/oracle_stream.py
diff --git a/tasks/dexjoco-click-mouse-i00-standard/task.toml b/tasks/dexjoco-click-mouse-i00-standard/task.toml
new file mode 100644
index 0000000000..0f53c6660b
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-standard/task.toml
@@ -0,0 +1,52 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator 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/dexjoco-click-mouse-i00-standard"
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): DexJoCo click_mouse (a Franka Panda arm with a 16-DoF Allegro hand) on the same frozen instance as dexjoco-click-mouse-i00-privileged. Put the computer mouse on the magenta mousepad and click its button. The agent only gets a client: calibrated cameras (RGB, optional depth), the robot's joints and tcp poses, tcp-target + hand-joint chunks at 50 Hz, the robot's kinematics; one episode, no reset, no object state; the sim service records the episode, replays it in fresh processes and grades it."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "standard-mode", "robot-as-a-service", "click_mouse"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro"
+family = "click_mouse"
+mode = "standard"
+protocol = "eai-standard/2.2"
+oracle = "full"
+expert_time_estimate_hours = 1.5
+
+[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 = 3600
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
diff --git a/tasks/dexjoco-click-mouse-i00-standard/tests/Dockerfile b/tasks/dexjoco-click-mouse-i00-standard/tests/Dockerfile
new file mode 100644
index 0000000000..26bc699ebe
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-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.sh
diff --git a/tasks/dexjoco-click-mouse-i00-standard/tests/grade.py b/tasks/dexjoco-click-mouse-i00-standard/tests/grade.py
new file mode 100644
index 0000000000..003b933315
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-standard/tests/grade.py
@@ -0,0 +1,60 @@
+"""Standard-mode verifier (DexJoCo): 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 frozen 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"))),
+ "task_failure": int(bool(d.get("task_failure"))),
+ "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),
+ "calls": int(d.get("calls") or 0),
+ "elapsed_s": float(d.get("elapsed_s") or 0),
+ "video_rendered": int(bool(d.get("video"))),
+ # 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 frozen 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/dexjoco-click-mouse-i00-standard/tests/test.sh b/tasks/dexjoco-click-mouse-i00-standard/tests/test.sh
new file mode 100755
index 0000000000..bc608aa8b9
--- /dev/null
+++ b/tasks/dexjoco-click-mouse-i00-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
diff --git a/tasks/dexjoco-fold-glasses-i00-privileged/README.md b/tasks/dexjoco-fold-glasses-i00-privileged/README.md
new file mode 100644
index 0000000000..29207c0c49
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-privileged/README.md
@@ -0,0 +1,49 @@
+# dexjoco-fold-glasses-i00-privileged
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | privileged |
+| Twin | `dexjoco-fold-glasses-i00-standard` |
+| Simulator / robot | `dexjoco` / `franka-allegro` |
+| Family / instance | `fold_glasses` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `fold_glasses` (a Franka Panda arm with a 16-DoF Allegro hand): Fold both temples of the glasses and put the glasses into the open case. Success: both temple hinges past 1.1 rad AND the glasses' centre inside the case (within 0.145 m of the case centre in x and y, between 0.045 m below and 0.0275 m above it), held for 50 consecutive control steps.
+Privileged mode: the agent works in the simulator's container with live object poses, unlimited resets and thin motion
+primitives, and hands in one trajectory replayed open-loop from the frozen instance.
+
+## Difficulty
+First-pass rating: hard. Dexterous manipulation with a 16-DoF hand on a 7-DoF arm (23 action values per control step);
+the primitives only move tcp and hand-joint targets, so grasping, pressing and every other skill is the agent's. The
+reference (the human teleoperator's demonstration) takes 612 control steps (12.2 s at 50 Hz).
+
+## Reference solution
+`solution/oracle_trajectory.npz` = the human demonstration's own actions, rounded to float32 (the standard client's
+precision; the rounded rows still succeed) and replayed from the frozen instance until the episode ends in success
+(612 rows). The demonstration is public (DexJoCo-Datasets-Raw on Hugging Face), so agent egress is
+limited to the model APIs.
+
+## Verification
+Open-loop replay of `/app/output/trajectory.npz` from `tests/instance.npz`, twice in a fresh process in the verifier's own
+sandbox (no network); pass iff both episodes end in success, their final-state hashes agree and the rebuilt instance
+matches its recorded hash (`tests/grade.py`); plus `/logs/verifier/replay.mp4`. Oracle: success after 612 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `glass_fold_demo_10_2026-03-11_20-33-55_671576` (DexJoCo-Datasets-Raw), restored with DexJoCo's own state restorer; instance sha `35849caecf4a0f6d` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Tooling notes
+DexJoCo's reset samples object poses from the global RNG and its state restorer edits the MuJoCo model (table height,
+fixed bodies), so `instance.npz` stores the full physics state (`mjSTATE_INTEGRATION`), the mocap targets, the controls,
+every numeric model array a task can change, and the env's Python-side task state. Its per-step camera rendering,
+real-time sleep, episode cap and hanoi's wall-clock auto-reset are disabled in the tooling (`rcb_dexjoco.py`).
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py` from `scripts/dexjoco/instances/fold_glasses/` (`make_instances.py`).
diff --git a/tasks/dexjoco-fold-glasses-i00-privileged/environment/Dockerfile b/tasks/dexjoco-fold-glasses-i00-privileged/environment/Dockerfile
new file mode 100644
index 0000000000..d736fe8a7d
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-privileged/environment/Dockerfile
@@ -0,0 +1,7 @@
+# Base image = DexJoCo on MuJoCo 3.4.0 (images/dexjoco/). Everything task-specific is copied here. CPU only.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY instance.npz /app/instance.npz
+COPY rcb_dexjoco.py /opt/tools/rcb_dexjoco.py
+ENV PYTHONPATH=/opt/tools
+RUN mkdir -p /app/output
+WORKDIR /app
diff --git a/tasks/dexjoco-fold-glasses-i00-privileged/environment/instance.npz b/tasks/dexjoco-fold-glasses-i00-privileged/environment/instance.npz
new file mode 100644
index 0000000000..ac1baebfb1
Binary files /dev/null and b/tasks/dexjoco-fold-glasses-i00-privileged/environment/instance.npz differ
diff --git a/tasks/dexjoco-fold-glasses-i00-privileged/environment/rcb_dexjoco.py b/tasks/dexjoco-fold-glasses-i00-privileged/environment/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-privileged/environment/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-fold-glasses-i00-privileged/instruction.md b/tasks/dexjoco-fold-glasses-i00-privileged/instruction.md
new file mode 100644
index 0000000000..db80672719
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-privileged/instruction.md
@@ -0,0 +1,111 @@
+# DexJoCo · fold_glasses — frozen instance
+
+You control a Franka Panda arm with a 16-DoF Allegro hand (DexJoCo on MuJoCo 3.4) via Python. **Task:** Fold both temples of the glasses and put the glasses into the open case. Success: both temple hinges past 1.1 rad AND the glasses' centre inside the case (within 0.145 m of the case centre in x and y, between 0.045 m below and 0.0275 m above it), held for 50 consecutive control steps.
+
+Open glasses lie on the table; the open case is next to them. Each temple is a hinge (`temple_0`, `temple_1`). `s.objects()` gives the live poses of the task objects (`glasses`, `temple_0`, `temple_1`, `case`, `table_top`). DexJoCo's success code (from
+`/opt/dexjoco/dexjoco/dexjoco/sim/envs/panda_fold_glasses_env.py`; `step()` ends the episode on success or on a task failure):
+```python
+def _compute_success(self):
+ # Read the glass position in world coordinates
+ glass_pos_world = np.array(self._data.sensor("glass_pos").data, dtype=np.float64)
+
+ glass_body_id = self._model.body("glass").id
+ glass_pos_world_2 = np.array(self._model.body_pos[glass_body_id], dtype=np.float64)
+ # print("Debug: glass_pos_world (sensor):", glass_pos_world)
+ glass_quat_world = np.array(self._data.sensor("glass_quat").data, dtype=np.float64)
+ # print("Debug: glass_quat_world (sensor):", glass_quat_world)
+
+ # Read the world position of the open_box (assuming no rotation)
+ box_pos_world = None
+ body_id = self._model.body("open_box").id
+ box_pos_world = np.array(self._model.body_pos[body_id], dtype=np.float64)
+
+ # Transform from world coordinates to box-local coordinates
+ glass_local = glass_pos_world - box_pos_world
+
+ # Inner cavity bounds of the box (derived from the XML, assuming `size` is half-extent)
+ x_half = 0.145 # = 0.1475 - 0.0025
+ y_half = 0.145
+ z_min = -0.045
+ z_max = 0.0475
+ inside_x = (-x_half <= glass_local[0] <= x_half)
+ inside_y = (-y_half <= glass_local[1] <= y_half)
+ inside_z = (z_min <= glass_local[2] <= z_max - 0.02)
+
+ # Original joint angle conditions
+ glass_joint_0_pos = self._data.sensor("glass_joint_0_pos").data
+ glass_joint_1_pos = self._data.sensor("glass_joint_1_pos").data
+ j0 = float(glass_joint_0_pos[0])
+ j1 = float(glass_joint_1_pos[0])
+
+ if j0 > 1.1 and j1 > 1.1:
+ pass
+ # print("-----Glass folded!-----")
+ trigger_active = (
+ (j0 > 1.1)
+ and (j1 > 1.1)
+ and inside_x
+ and inside_y
+ and inside_z
+ )
+
+ if trigger_active:
+ # Increment counter if the condition is met
+ self._success_trigger_count += 1
+ else:
+ # Reset counter if the condition is not met
+ self._success_trigger_count = 0
+
+ # Return success if the condition has been met 10 times consecutively
+ return self._success_trigger_count >= self._success_trigger_target
+```
+
+This is a *fixed scene instance*: object poses, the table height and the robot's start pose never change between
+resets. You may reset and retry as many times as you want. Your deliverable is **one replayable trajectory**, not a
+general policy.
+
+## Deliverable
+Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
+open-loop from the same initial state in a fresh process and scored 1 if its episode ends in success, else 0. Also
+leave the script that produced it at `/app/output/gen.py`. You have 90 minutes of wall clock: save a
+first trajectory early, improve it, and do not stop before the task is solved.
+
+## Tooling (already installed; run `python` from any directory)
+```python
+from rcb_dexjoco import Session
+s = Session("fold_glasses", instance="/app/instance.npz") # ~1 s: builds the env and loads the frozen state
+s.reset() # back to the frozen initial state (as often as you like; an exact snapshot restore)
+s.objects() # live task objects: name -> pos, quat_wxyz (bodies) / pos (sites) / qpos (joints)
+s.state() # DexJoCo's state dict: tcp_pose, gripper_pose (hand joints), INITIAL object poses, table height
+p = s.primitives() # thin wrappers of the low-level action; each has a docstring: help(p["move_ee"])
+p["move_ee"]("right", pos, quat_wxyz) # straight-line + slerp motion of an arm's tcp target, then settle
+p["set_hand"]("right", q16) # interpolate the 16 Allegro joint targets
+p["hold"](10); p["set_targets"](row, steps) # keep every target / send one raw action row
+p["get_ee_pose"]("right"); p["get_ee_target"]("right"); p["get_hand"]("right"); p["get_body_pose"](name)
+s.render_frame("front") # RGB uint8 (480, 640, 3); cameras: ['front', 'back', 'left', 'right', 'top0', 'handcam_rgb']; s.render_grid()
+s.step(action) # one control step (23 values, below) = 1/50 s; returns False once the episode is over
+s.record_start(); ...; actions = s.record_stop() # (T, 23) actions, one row per control step
+s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+s.replay(actions) # resets, replays open-loop until the episode ends, returns status -> self-check
+s.save_trajectory(actions, "/app/output/trajectory.npz")
+s.render_video(actions, "/app/output/check.mp4", cameras=["front"]) # replays from the frozen state into a video
+```
+The primitives are deliberately thin (tcp target moves, hand joint targets, hold): grasping, pressing, striking and
+every other skill are yours to build from them. `s.bodies()` lists every MuJoCo body for `p["get_body_pose"]`.
+
+CLI equivalent of the grader:
+`python /opt/tools/rcb_dexjoco.py replay --task fold_glasses --instance /app/instance.npz --traj /app/output/trajectory.npz`
+
+## Conventions
+- World frame, metres; z up; the robot stands at low x and reaches towards +x. The table top is at z = 0.962. Arm base (`link0`): link0 [-0.75, 0.0, 0.924]. Quaternions are **WXYZ**.
+- Action (23): tcp target position (3), tcp target orientation (4, wxyz), 16 Allegro
+ joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+ target and stops where contact blocks it); the hand joints are position-controlled. `s.hold_action()` is the no-op.
+ At the start the tcp target is [-0.443, -0.0, 1.517] / [0.0, 1.0, 0.0, 0.0].
+- Allegro joint order: index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger =
+ spread, 1-3 = flexion from the knuckle out; thumb 12 = opposition).
+ Target ranges (rad, same for every finger slot, thumb last): low [-0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, 0.26, -0.1, -0.19, -0.16], high [0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 1.4, 1.16, 1.64, 1.72]; the simulator clamps
+ targets to them.
+- Control runs at 50 Hz (10 physics substeps of 2 ms). DexJoCo's own episode cap and real-time pacing are lifted: there
+ is no step budget, your wall-clock time is the limit (~380 control steps/s here). An episode ends at the
+ first success or task failure; `s.step` then refuses further actions until `s.reset()`.
diff --git a/tasks/dexjoco-fold-glasses-i00-privileged/solution/gen.py b/tasks/dexjoco-fold-glasses-i00-privileged/solution/gen.py
new file mode 100644
index 0000000000..0e1f7e3bc7
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-privileged/solution/gen.py
@@ -0,0 +1,4 @@
+# How solution/oracle_trajectory.npz was made (scripts/dexjoco/make_instances.py): the DexJoCo human demonstration's
+# own actions (replay.zarr data/action), rounded to float32, replayed from the frozen instance with Session.replay until
+# the episode ended in success (holding the last row a few steps where the rounded rows ended short of a hold count),
+# truncated there and saved with Session.save_trajectory.
diff --git a/tasks/dexjoco-fold-glasses-i00-privileged/solution/oracle_trajectory.npz b/tasks/dexjoco-fold-glasses-i00-privileged/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..721e4675b4
Binary files /dev/null and b/tasks/dexjoco-fold-glasses-i00-privileged/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-fold-glasses-i00-privileged/solution/solve.sh b/tasks/dexjoco-fold-glasses-i00-privileged/solution/solve.sh
new file mode 100755
index 0000000000..7909c90cb8
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-privileged/solution/solve.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+# Reference solution: the human demonstration's actions (float32), replayed through the task tooling until success.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_trajectory.npz /app/output/trajectory.npz
+cp /solution/gen.py /app/output/gen.py
diff --git a/tasks/dexjoco-fold-glasses-i00-privileged/task.toml b/tasks/dexjoco-fold-glasses-i00-privileged/task.toml
new file mode 100644
index 0000000000..9c70ad5987
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-privileged/task.toml
@@ -0,0 +1,37 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator or the instance, not this.
+schema_version = "1.3"
+artifacts = ["/app/output/"]
+
+[task]
+name = "robot-coding-bench/dexjoco-fold-glasses-i00-privileged"
+description = "DexJoCo fold_glasses (a Franka Panda arm with a 16-DoF Allegro hand, MuJoCo): produce one replayable trajectory. Fold both temples of the glasses and put the glasses into the open case. Frozen scene instance (the initial state of a DexJoCo human demonstration)."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "code-as-policy", "trajectory", "fold_glasses"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro"
+family = "fold_glasses"
+mode = "privileged"
+oracle = "full"
+expert_time_estimate_hours = 2.5
+
+[verifier]
+timeout_sec = 1800.0
+environment_mode = "separate" # the verifier runs in its own sandbox (tests/Dockerfile); the agent container is gone by then
+network_mode = "no-network"
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
+
+[verifier.environment]
+build_timeout_sec = 1800.0
diff --git a/tasks/dexjoco-fold-glasses-i00-privileged/tests/Dockerfile b/tasks/dexjoco-fold-glasses-i00-privileged/tests/Dockerfile
new file mode 100644
index 0000000000..a2620a4da8
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-privileged/tests/Dockerfile
@@ -0,0 +1,8 @@
+# Separate verifier sandbox (PROTOCOL §2.6): the same simulator image with the verifier's own copies of the tooling and
+# the frozen instance baked in. Nothing the agent did in its container reaches this one: Harbor uploads only the declared
+# artifacts (/app/output/), so a patched success check in the agent container cannot count.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY grade.py instance.npz rcb_dexjoco.py test.sh /tests/
+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
+ENV PYTHONPATH=/tests
+WORKDIR /tests
diff --git a/tasks/dexjoco-fold-glasses-i00-privileged/tests/grade.py b/tasks/dexjoco-fold-glasses-i00-privileged/tests/grade.py
new file mode 100644
index 0000000000..ad916e8bb9
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-privileged/tests/grade.py
@@ -0,0 +1,109 @@
+"""Verifier entry point for the privileged DexJoCo tasks: replay /app/output/trajectory.npz from the frozen instance and
+write Harbor rewards.
+
+ python /tests/grade.py --family water_plant --instance /tests/instance.npz --traj /app/output/trajectory.npz
+
+Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only; Harbor rejects strings), a replay video
+/logs/verifier/replay.mp4 (front camera + wrist camera) and replay.last.png. Replays `--repeat` times in this fresh
+process; success requires every replay to end its episode in success (DexJoCo's own rule: the episode ends at the first
+success or task failure) AND all final-state hashes to agree (MuJoCo on the CPU is bit-deterministic), and the frozen
+instance rebuilt here from tests/instance.npz must match its recorded hash.
+"""
+from __future__ import annotations
+import argparse, json, os, sys, time, traceback
+import numpy as np
+
+LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")
+
+
+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 self_reported_cost() -> dict:
+ # From the tooling's append-only log in the agent's container: SELF-REPORTED accounting, never evidence.
+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_records": 0, "agent_replays": 0,
+ "agent_cost_self_reported": 1}
+ try:
+ with open("/app/output/rcb_session_log.jsonl") 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 == "session_end": cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)
+ elif ev == "record": cost["agent_records"] += 1
+ elif ev == "replay": cost["agent_replays"] += 1
+ except Exception: # noqa: BLE001 — one bad line must not sink the verdict
+ continue
+ except Exception: # noqa: BLE001
+ pass
+ return cost
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--family", required=True); ap.add_argument("--instance", required=True)
+ ap.add_argument("--traj", default="/app/output/trajectory.npz"); ap.add_argument("--repeat", type=int, default=2)
+ ap.add_argument("--no-video", action="store_true")
+ a = ap.parse_args()
+ cost = self_reported_cost()
+ os.environ["RCB_SESSION_LOG"] = "" # the verifier's own sessions are not the agent's cost
+ if not os.path.isfile(a.traj):
+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost}); return 0
+ s = None
+ try:
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the verifier's own copy of the tooling
+ import rcb_dexjoco
+ rcb_dexjoco.SESSION_LOG = ""
+ from rcb_dexjoco import Session, MAX_STEPS
+ d = np.load(a.traj, allow_pickle=False)
+ if str(d["task"]) != a.family:
+ write(False, {"success": 0, "wrong_family": 1, "grader_error": 0, **cost}); return 0
+ acts = np.asarray(d["actions"], dtype=np.float64)
+ s = Session(a.family, instance=a.instance)
+ if (acts.ndim != 2 or acts.shape[1] != s.action_dim or acts.shape[0] > MAX_STEPS
+ or not np.all(np.isfinite(acts))):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0,
+ "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0, **cost}); return 0
+ t0 = time.time()
+ outs = []
+ for _ in range(a.repeat):
+ try:
+ outs.append(s.replay(acts))
+ except (ValueError, rcb_dexjoco.PrimitiveError):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0, "n_actions": int(len(acts)), **cost}); return 0
+ all_success = all(o["success"] for o in outs)
+ deterministic = len({o["state_sha"] for o in outs}) == 1
+ instance_ok = bool(s.instance_exact)
+ ok = all_success and deterministic and instance_ok
+ out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
+ "instance_ok": int(instance_ok), "n_actions": int(len(acts)), "sim_steps": int(outs[0]["steps"]),
+ "task_failure": int(bool(outs[0]["reason"]) and not outs[0]["success"]),
+ "replay_wall_s": round(time.time() - t0, 1), "grader_error": 0, "video_rendered": 0, **cost}
+ if not a.no_video: # human-viewable replay (never affects the verdict)
+ try:
+ n = int(outs[0]["replayed_rows"])
+ s.render_video(acts[:n], os.path.join(LOG_DIR, "replay.mp4"), cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ import imageio.v2 as imageio
+ imageio.imwrite(os.path.join(LOG_DIR, "replay.last.png"), s.render_frame(s.default_camera(), (480, 640)))
+ out["video_rendered"] = int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4")))
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(ok, out)
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(False, {"success": 0, "grader_error": 1, **cost})
+ finally:
+ if s is not None:
+ s.close()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tasks/dexjoco-fold-glasses-i00-privileged/tests/instance.npz b/tasks/dexjoco-fold-glasses-i00-privileged/tests/instance.npz
new file mode 100644
index 0000000000..ac1baebfb1
Binary files /dev/null and b/tasks/dexjoco-fold-glasses-i00-privileged/tests/instance.npz differ
diff --git a/tasks/dexjoco-fold-glasses-i00-privileged/tests/rcb_dexjoco.py b/tasks/dexjoco-fold-glasses-i00-privileged/tests/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-privileged/tests/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-fold-glasses-i00-privileged/tests/test.sh b/tasks/dexjoco-fold-glasses-i00-privileged/tests/test.sh
new file mode 100755
index 0000000000..c0a7f7949e
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-privileged/tests/test.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in a fresh process.
+# 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/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)
+mkdir -p /logs/verifier
+python /tests/grade.py --family fold_glasses --instance /tests/instance.npz --traj /app/output/trajectory.npz --repeat 2 \
+ 2> /logs/verifier/grade.log
diff --git a/tasks/dexjoco-fold-glasses-i00-standard/README.md b/tasks/dexjoco-fold-glasses-i00-standard/README.md
new file mode 100644
index 0000000000..d20adc88d6
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-standard/README.md
@@ -0,0 +1,45 @@
+# dexjoco-fold-glasses-i00-standard
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | standard (`eai-standard/2.2`) |
+| Twin | `dexjoco-fold-glasses-i00-privileged` |
+| Simulator / robot | `dexjoco` / `franka-allegro` |
+| Family / instance | `fold_glasses` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `fold_glasses` (a Franka Panda arm with a 16-DoF Allegro hand) on the same frozen instance as `dexjoco-fold-glasses-i00-privileged`: Fold both temples of the glasses and put the glasses into the open case. Success: both temple hinges past 1.1 rad AND the glasses' centre inside the case (within 0.145 m of the case centre in x and y, between 0.045 m below and 0.0275 m above it), held for 50 consecutive control steps.
+Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with the robot's own
+sensors, calibrated cameras (RGB, optional depth) and the robot's kinematics.
+
+## Difficulty
+Same instance and success check as `dexjoco-fold-glasses-i00-privileged`. In standard mode the agent loses resets, the
+simulator and the object poses: it sees camera images and proprioception, acts in chunks of tcp-target + hand-joint rows
+(or joint targets), and gets one episode, so it has to close the loop on what the cameras show and recover from its own
+mistakes without starting over.
+
+## Reference solution
+`solution/oracle_stream.py` streams the privileged reference's rows (`solution/oracle_trajectory.npz`, 612 rows, float32-exact)
+through the client as `ee_pose` 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 612 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 612 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `glass_fold_demo_10_2026-03-11_20-33-55_671576` (DexJoCo-Datasets-Raw); instance sha `35849caecf4a0f6d` |
+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); action types `ee_pose` and `joint_position`; cameras `front`, `back`, `left`, `right`, `top0`, `handcam_rgb` (640 x 480); `/kinematics` for the arm links, the hand mount and the tcp; crash recovery class `exact` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py`, as its privileged twin.
diff --git a/tasks/dexjoco-fold-glasses-i00-standard/environment/Dockerfile b/tasks/dexjoco-fold-glasses-i00-standard/environment/Dockerfile
new file mode 100644
index 0000000000..a778c94561
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-standard/environment/Dockerfile
@@ -0,0 +1,9 @@
+# Standard mode: the agent container has NO simulator and no DexJoCo 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 /app
diff --git a/tasks/dexjoco-fold-glasses-i00-standard/environment/client-requirements.txt b/tasks/dexjoco-fold-glasses-i00-standard/environment/client-requirements.txt
new file mode 100644
index 0000000000..8aa73a968f
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-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.0
diff --git a/tasks/dexjoco-fold-glasses-i00-standard/environment/docker-compose.yaml b/tasks/dexjoco-fold-glasses-i00-standard/environment/docker-compose.yaml
new file mode 100644
index 0000000000..1ca09bcdf1
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-standard/environment/docker-compose.yaml
@@ -0,0 +1,24 @@
+# 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 OSMesa rendering; 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-dexjoco:0.1.2
+ 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_TASK: fold_glasses
+ RCB_INSTANCE: /srv/instance.npz
+ RCB_TOOL: /srv/rcb_dexjoco.py
+ RCB_DATA: /data
+ RCB_WALL_CLOCK_S: "5400"
+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in a few seconds
+ PYTHONPATH: /srv
+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction log
diff --git a/tasks/dexjoco-fold-glasses-i00-standard/environment/rcb1.py b/tasks/dexjoco-fold-glasses-i00-standard/environment/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-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/dexjoco-fold-glasses-i00-standard/environment/rcb_client.py b/tasks/dexjoco-fold-glasses-i00-standard/environment/rcb_client.py
new file mode 100644
index 0000000000..aa25b0e050
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-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/dexjoco-fold-glasses-i00-standard/environment/sim/finalize.sh b/tasks/dexjoco-fold-glasses-i00-standard/environment/sim/finalize.sh
new file mode 100755
index 0000000000..e0cf248720
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-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_dexjoco.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:?}"; TASK="${RCB_TASK:?}"
+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 --task "$TASK" --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --repeat 1 \
+ --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"))
+PY
diff --git a/tasks/dexjoco-fold-glasses-i00-standard/environment/sim/instance.npz b/tasks/dexjoco-fold-glasses-i00-standard/environment/sim/instance.npz
new file mode 100644
index 0000000000..ac1baebfb1
Binary files /dev/null and b/tasks/dexjoco-fold-glasses-i00-standard/environment/sim/instance.npz differ
diff --git a/tasks/dexjoco-fold-glasses-i00-standard/environment/sim/rcb1.py b/tasks/dexjoco-fold-glasses-i00-standard/environment/sim/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-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/dexjoco-fold-glasses-i00-standard/environment/sim/rcb_dexjoco.py b/tasks/dexjoco-fold-glasses-i00-standard/environment/sim/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-standard/environment/sim/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-fold-glasses-i00-standard/environment/sim/rcb_limited.py b/tasks/dexjoco-fold-glasses-i00-standard/environment/sim/rcb_limited.py
new file mode 100644
index 0000000000..1ce1171787
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-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/dexjoco-fold-glasses-i00-standard/environment/sim/run.sh b/tasks/dexjoco-fold-glasses-i00-standard/environment/sim/run.sh
new file mode 100755
index 0000000000..49d4d045d4
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-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; done
diff --git a/tasks/dexjoco-fold-glasses-i00-standard/environment/sim/server.py b/tasks/dexjoco-fold-glasses-i00-standard/environment/sim/server.py
new file mode 100644
index 0000000000..ca5b61fc5c
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-standard/environment/sim/server.py
@@ -0,0 +1,625 @@
+"""eai-standard/2.2 sim service for DexJoCo (docs/STANDARD_MODE_2_2.md): the adapter of the shared layer rcb_limited.py;
+the simulator is rcb_dexjoco.Session (DexJoCo on MuJoCo 3.4, CPU physics, OSMesa rendering).
+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to
+/data/episode.jsonl.
+
+The robot is a Franka Panda with a 16-DoF Allegro hand, or two of them side by side (right arm first). One control step
+= 1/50 s (10 physics substeps of 2 ms). Two action types:
+ ee_pose DexJoCo's own row, per arm: the tcp target pose (xyz m, quaternion wxyz, world frame) that its
+ operational-space controller tracks + 16 Allegro joint targets (rad);
+ joint_position per arm: 7 arm joint targets + 16 Allegro joint targets; the arm's targets are turned into a tcp target
+ by forward kinematics (the controller tracks the tcp pose, not the joints).
+Either way, the executed (journaled, recorded) row is DexJoCo's own row, so the recorded trajectory replays in the
+privileged tooling unchanged. As in DexJoCo's evaluation the episode ends at the first success or task failure;
+otherwise when the agent's time is over (the collect hook's SIGUSR1).
+
+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 instance 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")
+TASK = os.environ.get("RCB_TASK", "water_plant")
+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.npz"))
+TASK_TEXT_FILE = os.environ.get("RCB_TASK_TEXT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "task_text.txt"))
+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "5400"))
+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 = 640, 480
+CTRL_HZ = 50.0
+DT = 1.0 / CTRL_HZ
+SUBSTEPS = 10
+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"] = "" # the sidecar's Session is not the agent's interaction log
+import rcb_dexjoco as M # noqa: E402
+import mujoco # noqa: E402
+
+M.SESSION_LOG = ""
+BIM = TASK.startswith("bimanual_")
+ADIM = 46 if BIM else 23
+EP = L.Episode(DATA, dim=ADIM, resume="exact")
+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()
+S = M.Session(TASK, instance=INSTANCE, image_size=(CAM_H, CAM_W))
+MD, D = S.model, S.data
+ARMS = S.arms()
+SFX = {a: (f"_{a}" if BIM else "") for a in ARMS}
+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz
+
+# ------------------------------------------------------------------------------------------------- the robot
+ARM_JOINTS = {a: [f"joint{i}{SFX[a]}" for i in range(1, 8)] for a in ARMS}
+HAND_CTRL = {a: np.asarray(S._hand_ctrl_ids(a)) for a in ARMS}
+HAND_JOINTS = {a: [MD.joint(int(MD.actuator_trnid[i, 0])).name for i in HAND_CTRL[a]] for a in ARMS} # action order
+ARM_CTRL = {a: [MD.actuator(f"actuator{i}{SFX[a]}").id for i in range(1, 8)] for a in ARMS}
+JOINTS = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]] # kinematics q = proprio joint_pos columns
+QADR = np.array([MD.jnt_qposadr[MD.joint(j).id] for j in JOINTS])
+VADR = np.array([MD.jnt_dofadr[MD.joint(j).id] for j in JOINTS])
+EFF_ACT = np.array([i for a in ARMS for i in list(ARM_CTRL[a]) + list(HAND_CTRL[a])])
+TCP_SITE = {a: MD.site(f"attachment_site{SFX[a]}").id for a in ARMS}
+TCP = {a: f"tcp{SFX[a]}" for a in ARMS}
+MOUNT_BODY = {a: f"attachment{SFX[a]}" for a in ARMS}
+LINKS = {a: [f"link{i}{SFX[a]}" for i in range(0, 8) if mujoco.mj_name2id(MD, mujoco.mjtObj.mjOBJ_BODY, f"link{i}{SFX[a]}") >= 0]
+ + [MOUNT_BODY[a]] for a in ARMS}
+KIN_LINKS = [n for a in ARMS for n in LINKS[a] + [TCP[a]]]
+JLIM = {j: MD.jnt_range[MD.joint(j).id].astype(float).tolist() for j in JOINTS}
+HLIM = {a: S.hand_limits(a) for a in ARMS} # actuator ctrlrange, action order
+ALIM = {} # joint_position limits (inside the joint ranges)
+for a in ARMS:
+ for j in ARM_JOINTS[a]:
+ ALIM[j] = JLIM[j]
+ for j, (lo, hi) in zip(HAND_JOINTS[a], HLIM[a]):
+ ALIM[j] = [max(float(lo), JLIM[j][0]), min(float(hi), JLIM[j][1])]
+POSE = ["x", "y", "z", "qw", "qx", "qy", "qz"]
+EE_LAYOUT = [] # per arm, right first
+for a in ARMS:
+ EE_LAYOUT += [f"{TCP[a]}_target_{k}" for k in POSE] + [f"{j}_target" for j in HAND_JOINTS[a]]
+JP_LAYOUT = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]]
+
+GROUPS = [
+ ("joint_pos", JOINTS, "measured joint positions (rad): per arm (right first) the 7 Panda joints, then the 16 Allegro "
+ "joints in the action's order"),
+ ("joint_vel", [f"{j}_vel" for j in JOINTS], "measured joint velocities (rad/s)"),
+ ("joint_effort", [f"{j}_effort" for j in JOINTS], "actuator efforts (N m): the arm's operational-space torques and the "
+ "hand's position-actuator forces"),
+ ("gripper_opening", [], "none: a 16-DoF Allegro hand, its finger joints are in joint_pos"),
+ ("tcp_pose", [f"{TCP[a]}_{k}" for a in ARMS for k in POSE], "measured tcp pose per arm (x y z m, quaternion wxyz, world)"),
+ ("tcp_target", [f"{TCP[a]}_target_{k}" for a in ARMS for k in POSE], "the tcp target the controller tracks now (the "
+ "ee_pose part of the last executed row)"),
+ ("hand_target", [f"{j}_target" for a in ARMS for j in HAND_JOINTS[a]], "the Allegro joint targets now (rad)"),
+]
+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)
+
+
+def _quat(xmat) -> np.ndarray:
+ q = np.zeros(4)
+ mujoco.mju_mat2Quat(q, np.asarray(xmat, dtype=np.float64).reshape(9))
+ return q
+
+
+# ------------------------------------------------------------------------------------------------- cameras
+CAMS = S.cameras()
+HAND_CAMS = [c for c in CAMS if c.startswith("handcam")]
+DEFAULT_CAMS = [S.default_camera()]
+GL2CV = np.diag([1.0, -1.0, -1.0, 1.0])
+
+
+def _intrinsic(cam: str) -> list:
+ fovy = math.radians(float(MD.cam_fovy[MD.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 _cam2world_gl(cam: str) -> np.ndarray:
+ i = MD.camera(cam).id
+ T = np.eye(4)
+ T[:3, :3] = D.cam_xmat[i].reshape(3, 3) # MuJoCo camera axes: OpenGL (x right, y up, z back)
+ T[:3, 3] = D.cam_xpos[i]
+ return T
+
+
+def _extrinsic(cam: str) -> np.ndarray:
+ return np.linalg.inv(_cam2world_gl(cam) @ GL2CV)[:3, :]
+
+
+def camera_info(cam: str) -> dict:
+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist(),
+ "image_size": [CAM_W, CAM_H]}
+
+
+def _mount(cam: str) -> dict:
+ i = MD.camera(cam).id
+ body = MD.body(int(MD.cam_bodyid[i])).name
+ if int(MD.cam_bodyid[i]) == 0:
+ return {"type": "static", "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist()}
+ T = np.eye(4) # body -> camera (OpenGL axes), then to OpenCV axes
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.cam_quat[i])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.cam_pos[i]
+ return {"type": "link", "parent_link": body, "link_T_cam_cv": (T @ GL2CV).tolist()}
+
+
+def _mounted(cam: str) -> str:
+ if cam.startswith("handcam"):
+ side = "the right" if cam.endswith("_right") else "the left" if cam.endswith("_left") else "the"
+ return f"on {side} hand's mount (moves with the hand)"
+ return {"front": "static, across the table, facing the robot", "back": "static, behind the robot, looking over the table",
+ "left": "static, at the robot's left", "right": "static, at the robot's right",
+ "top0": "static, above the table, looking down"}.get(cam, "static")
+
+
+# ------------------------------------------------------------------------------------------------- kinematics
+KD = mujoco.MjData(MD) # kinematics only: never stepped; the robot's joints are set, everything else stays put
+ARM_QI = {a: [JOINTS.index(j) for j in ARM_JOINTS[a]] for a in ARMS}
+
+
+def _fk(q) -> None:
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR] = np.asarray(q, dtype=np.float64)
+ mujoco.mj_kinematics(MD, KD)
+
+
+def _link_pose(name: str) -> list:
+ for a in ARMS:
+ if name == TCP[a]:
+ s = TCP_SITE[a]
+ return [*KD.site_xpos[s].tolist(), *_quat(KD.site_xmat[s]).tolist()]
+ b = MD.body(name).id
+ return [*KD.xpos[b].tolist(), *KD.xquat[b].tolist()]
+
+
+def tcp_from_arm_joints(a: str, q7) -> np.ndarray:
+ """The tcp pose (xyz + wxyz) of arm `a` with its 7 joints at q7 (the joint_position action's tcp target)."""
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR[ARM_QI[a]]] = q7
+ mujoco.mj_kinematics(MD, KD)
+ s = TCP_SITE[a]
+ return np.concatenate([KD.site_xpos[s], _quat(KD.site_xmat[s])])
+
+
+def do_kinematics(req: dict) -> dict:
+ """World frame. FK: every link of spec kinematics.links for q. IK: per tcp target, damped least squares over that
+ arm's 7 joints (position and orientation), within the joint ranges; the hand joints are taken from the seed."""
+ if req["op"] == "fk":
+ _fk(req["q"])
+ return L.fk_response({n: _link_pose(n) for n in req["links"]}, "world")
+ q = np.array(req["seed"] if req["seed"] is not None else D.qpos[QADR], dtype=np.float64)
+ errors = {}
+ jp, jr = np.zeros((3, MD.nv)), np.zeros((3, MD.nv))
+ for frame, pose in req["targets"].items():
+ a = next(x for x in ARMS if TCP[x] == frame)
+ idx = ARM_QI[a]
+ dofs = VADR[idx]
+ tp, tq = np.asarray(pose[:3]), np.asarray(pose[3:7])
+ lo = np.array([JLIM[JOINTS[i]][0] for i in idx]); hi = np.array([JLIM[JOINTS[i]][1] for i in idx])
+ for _ in range(req["max_iters"]):
+ _fk(q)
+ mujoco.mj_comPos(MD, KD) # the Jacobian needs cdof, which mj_kinematics alone leaves stale
+ s = TCP_SITE[a]
+ ep = tp - KD.site_xpos[s]
+ cq = _quat(KD.site_xmat[s])
+ dq = np.zeros(4); neg = np.zeros(4); er = np.zeros(3)
+ mujoco.mju_negQuat(neg, cq); mujoco.mju_mulQuat(dq, tq, neg); mujoco.mju_quat2Vel(er, dq, 1.0)
+ if np.linalg.norm(ep) < req["tol_pos_m"] and np.linalg.norm(er) < req["tol_rot_rad"]:
+ break
+ mujoco.mj_jacSite(MD, KD, jp, jr, s)
+ J = np.vstack([jp[:, dofs], jr[:, dofs]])
+ err = np.concatenate([ep, er])
+ step = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), err)
+ q[idx] = np.clip(q[idx] + step, lo, hi)
+ _fk(q)
+ s = TCP_SITE[a]
+ errors[frame] = (float(np.linalg.norm(tp - KD.site_xpos[s])), L.quat_angle(_quat(KD.site_xmat[s]), tq / np.linalg.norm(tq)))
+ ok = all(e[0] <= req["tol_pos_m"] and e[1] <= req["tol_rot_rad"] for e in errors.values())
+ return L.ik_response(q, ok, errors, "world", note="the tcp (attachment_site) of each arm; the hand joints are the seed's")
+
+
+# ------------------------------------------------------------------------------------------------- spec
+def _joint_spec(a: str) -> list:
+ out = []
+ for j, ai in zip(ARM_JOINTS[a], ARM_CTRL[a]):
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_ctrlrange[ai][1]), "group": f"{a}_arm"})
+ for j, ai in zip(HAND_JOINTS[a], HAND_CTRL[a]):
+ fl = bool(MD.actuator_forcelimited[ai]) and float(MD.actuator_forcerange[ai][1]) > 0
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_forcerange[ai][1]) if fl else None, "group": f"{a}_hand"})
+ return out
+
+
+def _tcp_spec(a: str) -> dict:
+ s = TCP_SITE[a]
+ T = np.eye(4)
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.site_quat[s])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.site_pos[s]
+ return {"parent_link": MD.body(int(MD.site_bodyid[s])).name, "link_T_frame": T.tolist(),
+ "definition": "DexJoCo's attachment_site: the flange where the Allegro hand is mounted, the point its "
+ "operational-space controller drives to the ee_pose target (not the fingertips)"}
+
+
+def _base(a: str) -> list:
+ b = D.body(f"link0{SFX[a]}")
+ return [*np.round(b.xpos, 6).tolist(), *np.round(b.xquat, 6).tolist()]
+
+
+GAINS = {}
+for _a in ARMS:
+ for _j, _ai in zip(HAND_JOINTS[_a], HAND_CTRL[_a]):
+ GAINS[_j] = {"stiffness": float(MD.actuator_gainprm[_ai][0]), "damping": float(MD.dof_damping[MD.jnt_dofadr[MD.joint(_j).id]])}
+ROBOT_NAME = "franka-allegro-bimanual" if BIM else "franka-allegro"
+try:
+ TASK_TEXT = open(TASK_TEXT_FILE).read().strip()
+except OSError:
+ TASK_TEXT = f"DexJoCo {TASK}"
+SPEC = {
+ "protocol": L.PROTOCOL,
+ "protocol_compat": list(L.COMPAT),
+ "simulator": "DexJoCo @ 8d23b0f on MuJoCo 3.4.0 (CPU physics, OSMesa rendering)",
+ "robot": ROBOT_NAME,
+ "task_text": TASK_TEXT,
+ "control_hz": CTRL_HZ,
+ "physics_substeps": SUBSTEPS,
+ "physics_hz": CTRL_HZ * SUBSTEPS,
+ "max_chunk_s": MAX_CHUNK_S,
+ "max_watch_s": MAX_WATCH_S,
+ "cameras": {c: {"rgb": True, "depth": True, "mounted": _mounted(c), "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),
+ "mount": _mount(c)} for c in CAMS},
+ "default_cameras": DEFAULT_CAMS,
+ "action_types": {
+ "ee_pose": {
+ "dim": ADIM, "layout": EE_LAYOUT,
+ "units": "per arm (right first): tcp target position (m, world frame), tcp target orientation (quaternion wxyz), "
+ "16 Allegro joint targets (rad)",
+ "frame": "world", "quaternion_order": "wxyz", "ee_frames": [TCP[a] for a in ARMS],
+ "hand_limits": {j: ALIM[j] for a in ARMS for j in HAND_JOINTS[a]},
+ "semantics": "DexJoCo's own action row. The arm tracks the tcp target through DexJoCo's operational-space "
+ "controller (it lags a moving target and stops where contact blocks it); the hand joints are "
+ "position-controlled. Rows are `dt` apart (a whole multiple of 1/50 s, at most 0.5 s); between rows "
+ "positions and joints move linearly and orientations by slerp (`linear`) or jump (`hold`); a row's "
+ "own values land exactly on its last control step. Hand targets outside the ranges are clamped by "
+ "the simulator and reported in `clipped`; a zero quaternion is a 400.",
+ },
+ "joint_position": {
+ "dim": ADIM, "layout": JP_LAYOUT, "units": "rad", "limits": {j: ALIM[j] for j in JP_LAYOUT},
+ "semantics": "per arm (right first): 7 Panda joint targets, then the 16 Allegro joint targets. The arm's "
+ "targets are turned into a tcp target by forward kinematics (as POST /kinematics fk) and the arm "
+ "tracks that pose through the same operational-space controller as ee_pose, whose null space "
+ "pulls towards DexJoCo's home posture: the tcp reaches FK(q), the measured joints may differ from q "
+ "in the arm's redundant direction. Rows `dt` apart, `linear` (in joint space) or `hold`; values "
+ "outside the limits are clipped and reported.",
+ },
+ "not_yet": ["joint_delta", "joint_velocity", "ee_delta", "joint_torque"],
+ },
+ "proprio_layout": PROPRIO_LAYOUT,
+ "proprio_groups": PROPRIO_GROUPS,
+ "static": {},
+ "world": {"frame": "DexJoCo's world frame: z up, metres; the robot" + ("s stand" if BIM else " stands")
+ + " at low x and reach" + ("" if BIM else "es") + " towards +x"
+ + (" (right arm at y < 0, left arm at y > 0)" if BIM else ""),
+ "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},
+ "episode": "one episode, no reset: it ends at the first success, at a task failure (see task_text), or when your time is over",
+ "robot_spec": {
+ "name": ROBOT_NAME,
+ "description": ("two Franka Panda arms side by side, each with a 16-DoF Allegro hand (right arm first)" if BIM
+ else "a Franka Panda arm with a 16-DoF Allegro hand"),
+ "base": {"type": "fixed", "pose": _base(ARMS[0]), **({"per_arm": {a: _base(a) for a in ARMS}} if BIM else {}),
+ "note": "pose of the arm's base link (link0), world frame, x y z + quaternion wxyz"},
+ "joints": [j for a in ARMS for j in _joint_spec(a)],
+ "grippers": {},
+ "controller": {"type": "arm: operational-space control of the tcp (torques); hand: joint position actuators",
+ "control_hz": CTRL_HZ, "physics_hz": CTRL_HZ * SUBSTEPS, "gains": GAINS,
+ "note": "arm: DexJoCo's opspace controller drives attachment_site to the tcp target (position gains "
+ "400 N/m, damping ratio 4, gravity compensation, null space towards the home posture), "
+ "torques limited to effort_limit; hand: position actuators (stiffness N m/rad) on joints "
+ "with their own damping (N m s/rad)"},
+ "tcp": {TCP[a]: _tcp_spec(a) for a in ARMS},
+ },
+ "kinematics": {"endpoint": "/kinematics", "joint_names": JOINTS, "frame": "world", "quaternion_order": "wxyz",
+ "links": KIN_LINKS, "tcp_frames": [TCP[a] for a in ARMS], "ee_frames": [TCP[a] for a in ARMS],
+ "ik_targets": [TCP[a] for a in ARMS], "ik": {"tol_pos_m": 0.001, "tol_rot_rad": 0.01, "max_iters": 300},
+ "note": "the arm links, the hand mount (the hand cameras' parent) and the tcp, world frame; ik solves "
+ "each tcp target over that arm's 7 joints"},
+ "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()
+
+
+# ------------------------------------------------------------------------------------------------- state and frames
+def ctrl_steps() -> int:
+ return int(S.steps)
+
+
+def proprio_row() -> np.ndarray:
+ tcp, tgt, hand = [], [], []
+ for a in ARMS:
+ s = TCP_SITE[a]
+ tcp += [D.site_xpos[s], _quat(D.site_xmat[s])]
+ t = S._arm_target(a)
+ tgt.append(t[:7]); hand.append(t[7:23])
+ return np.concatenate([D.qpos[QADR], D.qvel[VADR], D.actuator_force[EFF_ACT], *tcp, *tgt, *hand]).astype(np.float32)
+
+
+def grab(cams, want_depth: bool):
+ rgb, dep = {}, {}
+ for c in cams:
+ rgb[c] = S.render_frame(c, (CAM_H, CAM_W))
+ if want_depth:
+ r = S._renderer # the one renderer (a second OSMesa context reads back garbage)
+ r.enable_depth_rendering()
+ try:
+ r.update_scene(D, camera=c)
+ dep[c] = r.render().astype(np.float32).copy()
+ finally:
+ r.disable_depth_rendering()
+ return rgb, dep
+
+
+def extrinsics(cams) -> dict:
+ return {c: _extrinsic(c) for c in cams}
+
+
+def summary() -> dict:
+ n = int(E.get("episode_control_steps") or ctrl_steps())
+ 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"],
+ "task": TASK, "protocol": L.PROTOCOL, "n_actions": len(ROWS), "task_failure": int(str(E["reason"] or "").startswith("failure")),
+ **EP.final_fields()}
+
+
+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 finish(reason: str) -> None:
+ """The episode is over: record the live verdict and dump the trajectory 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()
+ E["success"] = bool(S.success)
+ 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()
+ S.save_trajectory(np.asarray(ROWS, dtype=np.float64).reshape(-1, ADIM), os.path.join(DATA, "trajectory.npz"),
+ {"source": "standard-mode episode", "reason": E["reason"]})
+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})
+ write_final()
+
+
+def ctrl_step(a, rec) -> bool:
+ """One executed control step (DexJoCo's own row), journaled. True when the call must stop here."""
+ a = np.asarray(a, dtype=np.float64)
+ running = S.step(a)
+ ROWS.append(a.copy())
+ stop = EP.journal(a)
+ rec.tick()
+ if not running:
+ finish(S.reason or "done")
+ 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 DEFAULT_CAMS
+ if not isinstance(cams, list) or any(c not in CAMS for c in cams):
+ raise ValueError(f"unknown cameras {cams}; cameras: {CAMS}")
+ return list(dict.fromkeys(cams))
+
+
+def meta_common(cams) -> dict:
+ n = ctrl_steps()
+ return {"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}}
+
+
+def _native_from_ee(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ """ee_pose rows are executed as sent (the recorded row is what the agent commanded); hand targets outside the
+ actuator ranges are clamped by MuJoCo itself (ctrllimited) and only reported."""
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ if float(np.linalg.norm(row[o + 3:o + 7])) < 1e-6:
+ raise ValueError(f"row {ri}: the {a} tcp quaternion has zero norm")
+ for j in range(16):
+ lo, hi = HLIM[a][j]
+ v = row[o + 7 + j]
+ if v < lo or v > hi:
+ clipped.append({"row": ri, "index": int(o + 7 + j), "reason": f"{EE_LAYOUT[o + 7 + j]} outside [{lo:.3f}, {hi:.3f}]: clamped by the simulator"})
+ return row
+
+
+def _clip_joints(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ lo = np.array([ALIM[j][0] for j in JP_LAYOUT]); hi = np.array([ALIM[j][1] for j in JP_LAYOUT])
+ out = np.clip(row, lo, hi)
+ for j in np.flatnonzero(out != row)[:20]:
+ clipped.append({"row": ri, "index": int(j), "reason": f"{JP_LAYOUT[j]} limit [{lo[j]:g}, {hi[j]:g}]"})
+ return out
+
+
+def _native_from_joints(q: np.ndarray) -> np.ndarray:
+ out = []
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ out += [tcp_from_arm_joints(a, q[o:o + 7]), q[o + 7:o + 23]]
+ return np.concatenate(out)
+
+
+def _check_chunk(typ: str, A: np.ndarray, dt: float, interp: str, video: str) -> int:
+ k = dt / DT
+ if A.ndim != 2 or A.shape[1] != ADIM:
+ raise ValueError(f"{typ} actions must be (T, {ADIM}), got {list(A.shape)}")
+ if A.shape[0] == 0:
+ raise ValueError("no rows")
+ 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")
+ return int(round(k))
+
+
+def do_submit(meta: dict, A: np.ndarray):
+ typ = meta.get("type")
+ if typ not in ("ee_pose", "joint_position"):
+ raise ValueError(f"type must be ee_pose or joint_position (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)
+ n = _check_chunk(typ, A, dt, interp, video)
+ clipped: list = []
+ if typ == "ee_pose":
+ A = np.stack([_native_from_ee(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ else:
+ A = np.stack([_clip_joints(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ rec = recorder(cams, fps, meta)
+ E["calls"] += 1
+ step0, before = E["step"], ctrl_steps()
+ rec.tick(force=True)
+ if typ == "ee_pose":
+ prev = np.asarray(S.hold_action(), dtype=np.float64)
+ else:
+ prev = np.concatenate([np.concatenate([D.qpos[QADR[ARM_QI[a]]], S._arm_target(a)[7:23]]) for a in ARMS])
+ for row in A:
+ E["step"] += 1
+ stop = False
+ for s in range(1, n + 1):
+ if interp == "hold" or s == n:
+ target = row # a row's own values land exactly on its last control step
+ else:
+ target = prev + (row - prev) * (s / n)
+ if typ == "ee_pose":
+ for k in range(len(ARMS)):
+ o = 23 * k
+ target[o + 3:o + 7] = M.quat_slerp(prev[o + 3:o + 7], row[o + 3:o + 7], s / n)
+ native = target if typ == "ee_pose" else _native_from_joints(target)
+ if ctrl_step(native, rec):
+ stop = True
+ break
+ prev = row
+ 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"], "type": typ, "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 = np.asarray(S.hold_action(), dtype=np.float64)
+ 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={"task": TASK, "instance_sha": S.instance_sha, "instance_ok": bool(S.instance_exact), "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} DexJoCo sim ready ({TASK}; 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/dexjoco-fold-glasses-i00-standard/environment/sim/task_text.txt b/tasks/dexjoco-fold-glasses-i00-standard/environment/sim/task_text.txt
new file mode 100644
index 0000000000..96977511fc
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-standard/environment/sim/task_text.txt
@@ -0,0 +1,3 @@
+Fold both temples of the glasses and put the glasses into the open case. Success: both temple hinges past 1.1 rad AND the glasses' centre inside the case (within 0.145 m of the case centre in x and y, between 0.045 m below and 0.0275 m above it), held for 50 consecutive control steps.
+
+Open glasses lie on the table; the open case is next to them. Each temple is a hinge (`temple_0`, `temple_1`).
diff --git a/tasks/dexjoco-fold-glasses-i00-standard/instruction.md b/tasks/dexjoco-fold-glasses-i00-standard/instruction.md
new file mode 100644
index 0000000000..ebfc38726a
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-standard/instruction.md
@@ -0,0 +1,68 @@
+# DexJoCo · fold_glasses — STANDARD MODE (robot as a service, eai-standard/2.2)
+
+You control a Franka Panda arm with a 16-DoF Allegro hand, **as if it were real hardware**: the simulator runs in a service you cannot open. You get
+one client and one episode. **Task:** Fold both temples of the glasses and put the glasses into the open case. Success: both temple hinges past 1.1 rad AND the glasses' centre inside the case (within 0.145 m of the case centre in x and y, between 0.045 m below and 0.0275 m above it), held for 50 consecutive control steps.
+
+Open glasses lie on the table; the open case is next to them. Each temple is a hinge (`temple_0`, `temple_1`).
+
+## Rules (real-robot rules)
+- **No reset.** The episode starts when the service comes up and ends on success, on a task failure (see the task), when
+ your time is up, or on a simulator error. Knocked-over objects stay knocked over.
+- **No privileged state.** You see what the cameras see (RGB, and depth on request, with each camera's calibration) plus
+ the robot's own proprioception (joints, tcp poses, the current targets). No object poses, no success check:
+ `meta["done"]` / `meta["reason"]` tell you when the episode is over and why.
+- Steps are unlimited; your wall-clock budget (90 minutes) is the limit (`meta["time_left_s"]`). Actions and
+ simulated time are reported as cost. Do not stop before the task is solved.
+- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
+ `/app/output/gen.py` for the record (save it early, update it as you go).
+- **Nothing is put into your context automatically.** Images and videos come back as arrays/bytes in a Python object;
+ what you look at and where you store it is your code's decision.
+
+## Client (`/opt/tools/rcb_client.py`, protocol `eai-standard/2.2`)
+```python
+from rcb_client import Robot
+r = Robot() # connects (waits while the service starts)
+spec = r.spec() # action types, cameras (+ calibration), proprio layout, robot_spec, kinematics, budget
+obs = r.get_obs() # current frames of spec["default_cameras"]: obs.last[cam] -> uint8 (480, 640, 3)
+obs = r.get_obs(cameras=["front", "handcam_rgb"], depth=True) # + obs.last_depth[cam] -> float32 (480, 640) z-depth (m)
+obs.meta["proprio"] # {"layout": [...], "now": [...]}; obs.group("tcp_pose", now=True)
+obs.meta["cameras"] # per camera intrinsic_cv / extrinsic_cv / cam2world_gl for these frames
+obs = r.get_obs(seconds=2.0, video="mp4") # hold the current targets and watch for 2 s (max 30): obs.video[cam] = mp4 bytes
+
+res = r.submit("ee_pose", rows, dt=0.1) # rows: (T, 23) targets dt seconds apart, executed at 50 Hz with interpolation
+res = r.submit("joint_position", q_rows, dt=0.1) # (T, 23) joint targets instead (see below)
+res.meta["done"], res.meta["reason"], res.meta["clipped"], res.meta["control_steps_chunk"]
+res.video["front"]; res.last["front"]; res.proprio # mp4 of the chunk, last frame, float32 (N, P) proprio per frame
+res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, proprio.npy, ...
+r.fk(q); r.ik({"tcp": pose}, seed=q) # kinematics of the robot (stateless: no physics, no time)
+r.status() # calls, control steps, done, reason, elapsed time
+```
+Cameras: `front`, `back`, `left`, `right`, `top0` (static), `handcam_rgb` (on the hand mount; they move,
+so use the calibration that comes with each response; `spec["cameras"][cam]["mount"]` gives the static pose or the mount
+link). Resolution 640x480. Rendering runs on the CPU: ask only for the cameras you need; `video="none"` makes a chunk
+fastest. If a call fails with a connection error the service may have crashed: it resumes the same episode;
+`r.wait_ready()`, then check `r.status()` (`spec["on_service_error"]`).
+
+### Action type `ee_pose` (23) — DexJoCo's own action
+tcp target position (3, metres, world frame), tcp target orientation (4, quaternion wxyz), 16
+Allegro joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+target and stops where contact blocks it); the hand joints are position-controlled. Rows are `dt` apart (a whole multiple
+of 1/50 s, at most 0.5 s); between rows positions and joints move linearly and orientations by slerp
+(`interpolate="linear"`) or jump (`"hold"`); a chunk may cover at most 10 s. Hand targets outside the ranges
+(`spec["action_types"]["ee_pose"]["hand_limits"]`) are clamped by the simulator and listed in `meta["clipped"]`. Build
+the next row from the `tcp_target` and `hand_target` proprio groups to move smoothly.
+
+### Action type `joint_position` (23)
+7 Panda joint targets, then the 16 Allegro joint targets (rad). The service turns the arm's targets
+into a tcp target by forward kinematics and the same controller tracks it: the tcp reaches FK(q), but the measured arm
+joints may differ from q in the arm's redundant direction (the controller's null space pulls towards a home posture).
+Out-of-limit values are clipped and reported.
+
+## Conventions
+- World frame, metres, z up; the robot stands at low x and reaches towards +x; each
+ arm's base pose is in `spec["robot_spec"]["base"]`. No other world coordinates are given (D7: the cameras are
+ calibrated, depth is available). Quaternions are **WXYZ**.
+- The tcp (`tcp`) is the hand's mounting flange (`spec["robot_spec"]["tcp"]`), not the fingertips. Allegro joint
+ order: index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger = spread, 1-3 = flexion
+ from the knuckle out; thumb 12 = opposition).
+- Control runs at 50 Hz (10 physics substeps of 2 ms). There is no step budget: your wall-clock time is the limit.
diff --git a/tasks/dexjoco-fold-glasses-i00-standard/solution/oracle_stream.py b/tasks/dexjoco-fold-glasses-i00-standard/solution/oracle_stream.py
new file mode 100644
index 0000000000..19877300c1
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-standard/solution/oracle_stream.py
@@ -0,0 +1,43 @@
+"""Oracle (standard mode): streams the reference rows (the human demonstration's own actions, one per 1/50 s control step,
+float32-exact) as `ee_pose` 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
+
+A = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle_trajectory.npz"))["actions"].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(A), flush=True)
+t0, i = time.time(), 0
+while i < len(A):
+ chunk = A[i:i + per_chunk]
+ try:
+ res = r.submit("ee_pose", chunk, dt=dt, interpolate="hold", 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/dexjoco-fold-glasses-i00-standard/solution/oracle_trajectory.npz b/tasks/dexjoco-fold-glasses-i00-standard/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..721e4675b4
Binary files /dev/null and b/tasks/dexjoco-fold-glasses-i00-standard/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-fold-glasses-i00-standard/solution/solve.sh b/tasks/dexjoco-fold-glasses-i00-standard/solution/solve.sh
new file mode 100755
index 0000000000..1bd55d898f
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-standard/solution/solve.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+# Oracle (standard mode): streams the reference trajectory's rows (solution/oracle_trajectory.npz, one row per control
+# step) as `ee_pose` chunks through the client. Uses no privileged information at run time (only the pre-recorded rows);
+# the service's recorded trajectory is then exactly the privileged reference.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_stream.py /app/output/gen.py
+python /solution/oracle_stream.py
diff --git a/tasks/dexjoco-fold-glasses-i00-standard/task.toml b/tasks/dexjoco-fold-glasses-i00-standard/task.toml
new file mode 100644
index 0000000000..0902006e23
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-standard/task.toml
@@ -0,0 +1,52 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator 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/dexjoco-fold-glasses-i00-standard"
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): DexJoCo fold_glasses (a Franka Panda arm with a 16-DoF Allegro hand) on the same frozen instance as dexjoco-fold-glasses-i00-privileged. Fold both temples of the glasses and put the glasses into the open case. The agent only gets a client: calibrated cameras (RGB, optional depth), the robot's joints and tcp poses, tcp-target + hand-joint chunks at 50 Hz, the robot's kinematics; one episode, no reset, no object state; the sim service records the episode, replays it in fresh processes and grades it."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "standard-mode", "robot-as-a-service", "fold_glasses"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro"
+family = "fold_glasses"
+mode = "standard"
+protocol = "eai-standard/2.2"
+oracle = "full"
+expert_time_estimate_hours = 2.5
+
+[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 = 3600
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
diff --git a/tasks/dexjoco-fold-glasses-i00-standard/tests/Dockerfile b/tasks/dexjoco-fold-glasses-i00-standard/tests/Dockerfile
new file mode 100644
index 0000000000..26bc699ebe
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-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.sh
diff --git a/tasks/dexjoco-fold-glasses-i00-standard/tests/grade.py b/tasks/dexjoco-fold-glasses-i00-standard/tests/grade.py
new file mode 100644
index 0000000000..003b933315
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-standard/tests/grade.py
@@ -0,0 +1,60 @@
+"""Standard-mode verifier (DexJoCo): 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 frozen 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"))),
+ "task_failure": int(bool(d.get("task_failure"))),
+ "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),
+ "calls": int(d.get("calls") or 0),
+ "elapsed_s": float(d.get("elapsed_s") or 0),
+ "video_rendered": int(bool(d.get("video"))),
+ # 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 frozen 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/dexjoco-fold-glasses-i00-standard/tests/test.sh b/tasks/dexjoco-fold-glasses-i00-standard/tests/test.sh
new file mode 100755
index 0000000000..bc608aa8b9
--- /dev/null
+++ b/tasks/dexjoco-fold-glasses-i00-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
diff --git a/tasks/dexjoco-hammer-nail-i00-privileged/README.md b/tasks/dexjoco-hammer-nail-i00-privileged/README.md
new file mode 100644
index 0000000000..3fc71b5d59
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-privileged/README.md
@@ -0,0 +1,49 @@
+# dexjoco-hammer-nail-i00-privileged
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | privileged |
+| Twin | `dexjoco-hammer-nail-i00-standard` |
+| Simulator / robot | `dexjoco` / `franka-allegro` |
+| Family / instance | `hammer_nail` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `hammer_nail` (a Franka Panda arm with a 16-DoF Allegro hand): Pick up the hammer and drive the nail into the wooden block by striking its head. A strike counts only if the hammer face was moving down faster than 0.02 m/s just before it touched the nail; each counted strike drives the nail 8 mm x min(3, speed / 0.02) deeper (at most 7.26 cm). Success: the nail is at least 4 cm deep.
+Privileged mode: the agent works in the simulator's container with live object poses, unlimited resets and thin motion
+primitives, and hands in one trajectory replayed open-loop from the frozen instance.
+
+## Difficulty
+First-pass rating: hard. Dexterous manipulation with a 16-DoF hand on a 7-DoF arm (23 action values per control step);
+the primitives only move tcp and hand-joint targets, so grasping, pressing and every other skill is the agent's. The
+reference (the human teleoperator's demonstration) takes 202 control steps (4.0 s at 50 Hz).
+
+## Reference solution
+`solution/oracle_trajectory.npz` = the human demonstration's own actions, rounded to float32 (the standard client's
+precision; the rounded rows still succeed) and replayed from the frozen instance until the episode ends in success
+(202 rows). The demonstration is public (DexJoCo-Datasets-Raw on Hugging Face), so agent egress is
+limited to the model APIs.
+
+## Verification
+Open-loop replay of `/app/output/trajectory.npz` from `tests/instance.npz`, twice in a fresh process in the verifier's own
+sandbox (no network); pass iff both episodes end in success, their final-state hashes agree and the rebuilt instance
+matches its recorded hash (`tests/grade.py`); plus `/logs/verifier/replay.mp4`. Oracle: success after 202 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `hammer_nail_demo_10_2026-02-05_19-18-55_029010` (DexJoCo-Datasets-Raw), restored with DexJoCo's own state restorer; instance sha `095c53d8e9a1cae0` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Tooling notes
+DexJoCo's reset samples object poses from the global RNG and its state restorer edits the MuJoCo model (table height,
+fixed bodies), so `instance.npz` stores the full physics state (`mjSTATE_INTEGRATION`), the mocap targets, the controls,
+every numeric model array a task can change, and the env's Python-side task state. Its per-step camera rendering,
+real-time sleep, episode cap and hanoi's wall-clock auto-reset are disabled in the tooling (`rcb_dexjoco.py`).
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py` from `scripts/dexjoco/instances/hammer_nail/` (`make_instances.py`).
diff --git a/tasks/dexjoco-hammer-nail-i00-privileged/environment/Dockerfile b/tasks/dexjoco-hammer-nail-i00-privileged/environment/Dockerfile
new file mode 100644
index 0000000000..d736fe8a7d
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-privileged/environment/Dockerfile
@@ -0,0 +1,7 @@
+# Base image = DexJoCo on MuJoCo 3.4.0 (images/dexjoco/). Everything task-specific is copied here. CPU only.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY instance.npz /app/instance.npz
+COPY rcb_dexjoco.py /opt/tools/rcb_dexjoco.py
+ENV PYTHONPATH=/opt/tools
+RUN mkdir -p /app/output
+WORKDIR /app
diff --git a/tasks/dexjoco-hammer-nail-i00-privileged/environment/instance.npz b/tasks/dexjoco-hammer-nail-i00-privileged/environment/instance.npz
new file mode 100644
index 0000000000..443d63038d
Binary files /dev/null and b/tasks/dexjoco-hammer-nail-i00-privileged/environment/instance.npz differ
diff --git a/tasks/dexjoco-hammer-nail-i00-privileged/environment/rcb_dexjoco.py b/tasks/dexjoco-hammer-nail-i00-privileged/environment/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-privileged/environment/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-hammer-nail-i00-privileged/instruction.md b/tasks/dexjoco-hammer-nail-i00-privileged/instruction.md
new file mode 100644
index 0000000000..dc96163255
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-privileged/instruction.md
@@ -0,0 +1,100 @@
+# DexJoCo · hammer_nail — frozen instance
+
+You control a Franka Panda arm with a 16-DoF Allegro hand (DexJoCo on MuJoCo 3.4) via Python. **Task:** Pick up the hammer and drive the nail into the wooden block by striking its head. A strike counts only if the hammer face was moving down faster than 0.02 m/s just before it touched the nail; each counted strike drives the nail 8 mm x min(3, speed / 0.02) deeper (at most 7.26 cm). Success: the nail is at least 4 cm deep.
+
+The hammer lies on the table at the robot's right (low y); the nail stands upright in a wooden block in front of the robot. The nail is not a free body: it only moves down when struck. `s.objects()` gives the live poses of the task objects (`hammer`, `nail`, `nail_top`, `wood_top`, `table_top`). DexJoCo's success code (from
+`/opt/dexjoco/dexjoco/dexjoco/sim/envs/panda_hammer_nail_env.py`; `step()` ends the episode on success or on a task failure):
+```python
+def _compute_success(self):
+ return float(self._nail_depth) >= self._success_depth
+
+def _apply_hammer_nail_interaction(self) -> bool:
+ if not self._hammer_geom_ids or not self._nail_geom_ids:
+ return False
+
+ hammer_set = set(self._hammer_geom_ids)
+ nail_set = set(self._nail_geom_ids)
+ hit = False
+ ncon = int(self._data.ncon)
+ for i in range(ncon):
+ c = self._data.contact[i]
+ g1 = int(c.geom1)
+ g2 = int(c.geom2)
+ if (g1 in hammer_set and g2 in nail_set) or (
+ g2 in hammer_set and g1 in nail_set
+ ):
+ hit = True
+ break
+
+ if not hit:
+ return False
+
+ preimpact_vz = min(self._vz_buf) if self._vz_buf else 0.0
+ if preimpact_vz >= -self._impact_vel_threshold:
+ return True
+
+ depth = float(self._nail_depth)
+ max_depth = float(self._nail_max_depth)
+ scale = min(3.0, abs(preimpact_vz) / max(self._impact_vel_threshold, 1e-6))
+ delta = self._impact_insert_step * scale
+ new_depth = min(max_depth, depth + delta)
+ if new_depth > depth:
+ self._nail_depth = new_depth
+ new_pos = self._nail_init_pos.copy()
+ new_pos[2] = self._nail_init_pos[2] - new_depth
+ self._data.mocap_pos[self._nail_mocap_id] = new_pos
+ self._data.mocap_quat[self._nail_mocap_id] = self._nail_init_quat
+ mujoco.mj_forward(self._model, self._data)
+
+ return True
+```
+
+This is a *fixed scene instance*: object poses, the table height and the robot's start pose never change between
+resets. You may reset and retry as many times as you want. Your deliverable is **one replayable trajectory**, not a
+general policy.
+
+## Deliverable
+Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
+open-loop from the same initial state in a fresh process and scored 1 if its episode ends in success, else 0. Also
+leave the script that produced it at `/app/output/gen.py`. You have 90 minutes of wall clock: save a
+first trajectory early, improve it, and do not stop before the task is solved.
+
+## Tooling (already installed; run `python` from any directory)
+```python
+from rcb_dexjoco import Session
+s = Session("hammer_nail", instance="/app/instance.npz") # ~1 s: builds the env and loads the frozen state
+s.reset() # back to the frozen initial state (as often as you like; an exact snapshot restore)
+s.objects() # live task objects: name -> pos, quat_wxyz (bodies) / pos (sites) / qpos (joints)
+s.state() # DexJoCo's state dict: tcp_pose, gripper_pose (hand joints), INITIAL object poses, table height
+p = s.primitives() # thin wrappers of the low-level action; each has a docstring: help(p["move_ee"])
+p["move_ee"]("right", pos, quat_wxyz) # straight-line + slerp motion of an arm's tcp target, then settle
+p["set_hand"]("right", q16) # interpolate the 16 Allegro joint targets
+p["hold"](10); p["set_targets"](row, steps) # keep every target / send one raw action row
+p["get_ee_pose"]("right"); p["get_ee_target"]("right"); p["get_hand"]("right"); p["get_body_pose"](name)
+s.render_frame("front") # RGB uint8 (480, 640, 3); cameras: ['front', 'back', 'left', 'right', 'top0', 'handcam_rgb']; s.render_grid()
+s.step(action) # one control step (23 values, below) = 1/50 s; returns False once the episode is over
+s.record_start(); ...; actions = s.record_stop() # (T, 23) actions, one row per control step
+s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+s.replay(actions) # resets, replays open-loop until the episode ends, returns status -> self-check
+s.save_trajectory(actions, "/app/output/trajectory.npz")
+s.render_video(actions, "/app/output/check.mp4", cameras=["front"]) # replays from the frozen state into a video
+```
+The primitives are deliberately thin (tcp target moves, hand joint targets, hold): grasping, pressing, striking and
+every other skill are yours to build from them. `s.bodies()` lists every MuJoCo body for `p["get_body_pose"]`.
+
+CLI equivalent of the grader:
+`python /opt/tools/rcb_dexjoco.py replay --task hammer_nail --instance /app/instance.npz --traj /app/output/trajectory.npz`
+
+## Conventions
+- World frame, metres; z up; the robot stands at low x and reaches towards +x. The table top is at z = 0.936. Arm base (`link0`): link0 [-0.75, 0.0, 0.924]. Quaternions are **WXYZ**.
+- Action (23): tcp target position (3), tcp target orientation (4, wxyz), 16 Allegro
+ joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+ target and stops where contact blocks it); the hand joints are position-controlled. `s.hold_action()` is the no-op.
+ At the start the tcp target is [-0.059, 0.008, 1.096] / [1.0, 0.0, 0.0, 0.0].
+- Allegro joint order: index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger =
+ spread, 1-3 = flexion from the knuckle out; thumb 12 = opposition).
+ Target ranges (rad, same for every finger slot, thumb last): low [-0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, 0.26, -0.1, -0.19, -0.16], high [0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 1.4, 1.16, 1.64, 1.72]; the simulator clamps
+ targets to them.
+- Control runs at 50 Hz (10 physics substeps of 2 ms). DexJoCo's own episode cap and real-time pacing are lifted: there
+ is no step budget, your wall-clock time is the limit (~400 control steps/s here). An episode ends at the
+ first success or task failure; `s.step` then refuses further actions until `s.reset()`.
diff --git a/tasks/dexjoco-hammer-nail-i00-privileged/solution/gen.py b/tasks/dexjoco-hammer-nail-i00-privileged/solution/gen.py
new file mode 100644
index 0000000000..0e1f7e3bc7
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-privileged/solution/gen.py
@@ -0,0 +1,4 @@
+# How solution/oracle_trajectory.npz was made (scripts/dexjoco/make_instances.py): the DexJoCo human demonstration's
+# own actions (replay.zarr data/action), rounded to float32, replayed from the frozen instance with Session.replay until
+# the episode ended in success (holding the last row a few steps where the rounded rows ended short of a hold count),
+# truncated there and saved with Session.save_trajectory.
diff --git a/tasks/dexjoco-hammer-nail-i00-privileged/solution/oracle_trajectory.npz b/tasks/dexjoco-hammer-nail-i00-privileged/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..9608c88267
Binary files /dev/null and b/tasks/dexjoco-hammer-nail-i00-privileged/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-hammer-nail-i00-privileged/solution/solve.sh b/tasks/dexjoco-hammer-nail-i00-privileged/solution/solve.sh
new file mode 100755
index 0000000000..7909c90cb8
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-privileged/solution/solve.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+# Reference solution: the human demonstration's actions (float32), replayed through the task tooling until success.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_trajectory.npz /app/output/trajectory.npz
+cp /solution/gen.py /app/output/gen.py
diff --git a/tasks/dexjoco-hammer-nail-i00-privileged/task.toml b/tasks/dexjoco-hammer-nail-i00-privileged/task.toml
new file mode 100644
index 0000000000..ec79959f23
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-privileged/task.toml
@@ -0,0 +1,37 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator or the instance, not this.
+schema_version = "1.3"
+artifacts = ["/app/output/"]
+
+[task]
+name = "robot-coding-bench/dexjoco-hammer-nail-i00-privileged"
+description = "DexJoCo hammer_nail (a Franka Panda arm with a 16-DoF Allegro hand, MuJoCo): produce one replayable trajectory. Pick up the hammer and drive the nail into the wooden block by striking its head. Frozen scene instance (the initial state of a DexJoCo human demonstration)."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "code-as-policy", "trajectory", "hammer_nail"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro"
+family = "hammer_nail"
+mode = "privileged"
+oracle = "full"
+expert_time_estimate_hours = 2.0
+
+[verifier]
+timeout_sec = 1800.0
+environment_mode = "separate" # the verifier runs in its own sandbox (tests/Dockerfile); the agent container is gone by then
+network_mode = "no-network"
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
+
+[verifier.environment]
+build_timeout_sec = 1800.0
diff --git a/tasks/dexjoco-hammer-nail-i00-privileged/tests/Dockerfile b/tasks/dexjoco-hammer-nail-i00-privileged/tests/Dockerfile
new file mode 100644
index 0000000000..a2620a4da8
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-privileged/tests/Dockerfile
@@ -0,0 +1,8 @@
+# Separate verifier sandbox (PROTOCOL §2.6): the same simulator image with the verifier's own copies of the tooling and
+# the frozen instance baked in. Nothing the agent did in its container reaches this one: Harbor uploads only the declared
+# artifacts (/app/output/), so a patched success check in the agent container cannot count.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY grade.py instance.npz rcb_dexjoco.py test.sh /tests/
+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
+ENV PYTHONPATH=/tests
+WORKDIR /tests
diff --git a/tasks/dexjoco-hammer-nail-i00-privileged/tests/grade.py b/tasks/dexjoco-hammer-nail-i00-privileged/tests/grade.py
new file mode 100644
index 0000000000..ad916e8bb9
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-privileged/tests/grade.py
@@ -0,0 +1,109 @@
+"""Verifier entry point for the privileged DexJoCo tasks: replay /app/output/trajectory.npz from the frozen instance and
+write Harbor rewards.
+
+ python /tests/grade.py --family water_plant --instance /tests/instance.npz --traj /app/output/trajectory.npz
+
+Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only; Harbor rejects strings), a replay video
+/logs/verifier/replay.mp4 (front camera + wrist camera) and replay.last.png. Replays `--repeat` times in this fresh
+process; success requires every replay to end its episode in success (DexJoCo's own rule: the episode ends at the first
+success or task failure) AND all final-state hashes to agree (MuJoCo on the CPU is bit-deterministic), and the frozen
+instance rebuilt here from tests/instance.npz must match its recorded hash.
+"""
+from __future__ import annotations
+import argparse, json, os, sys, time, traceback
+import numpy as np
+
+LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")
+
+
+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 self_reported_cost() -> dict:
+ # From the tooling's append-only log in the agent's container: SELF-REPORTED accounting, never evidence.
+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_records": 0, "agent_replays": 0,
+ "agent_cost_self_reported": 1}
+ try:
+ with open("/app/output/rcb_session_log.jsonl") 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 == "session_end": cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)
+ elif ev == "record": cost["agent_records"] += 1
+ elif ev == "replay": cost["agent_replays"] += 1
+ except Exception: # noqa: BLE001 — one bad line must not sink the verdict
+ continue
+ except Exception: # noqa: BLE001
+ pass
+ return cost
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--family", required=True); ap.add_argument("--instance", required=True)
+ ap.add_argument("--traj", default="/app/output/trajectory.npz"); ap.add_argument("--repeat", type=int, default=2)
+ ap.add_argument("--no-video", action="store_true")
+ a = ap.parse_args()
+ cost = self_reported_cost()
+ os.environ["RCB_SESSION_LOG"] = "" # the verifier's own sessions are not the agent's cost
+ if not os.path.isfile(a.traj):
+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost}); return 0
+ s = None
+ try:
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the verifier's own copy of the tooling
+ import rcb_dexjoco
+ rcb_dexjoco.SESSION_LOG = ""
+ from rcb_dexjoco import Session, MAX_STEPS
+ d = np.load(a.traj, allow_pickle=False)
+ if str(d["task"]) != a.family:
+ write(False, {"success": 0, "wrong_family": 1, "grader_error": 0, **cost}); return 0
+ acts = np.asarray(d["actions"], dtype=np.float64)
+ s = Session(a.family, instance=a.instance)
+ if (acts.ndim != 2 or acts.shape[1] != s.action_dim or acts.shape[0] > MAX_STEPS
+ or not np.all(np.isfinite(acts))):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0,
+ "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0, **cost}); return 0
+ t0 = time.time()
+ outs = []
+ for _ in range(a.repeat):
+ try:
+ outs.append(s.replay(acts))
+ except (ValueError, rcb_dexjoco.PrimitiveError):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0, "n_actions": int(len(acts)), **cost}); return 0
+ all_success = all(o["success"] for o in outs)
+ deterministic = len({o["state_sha"] for o in outs}) == 1
+ instance_ok = bool(s.instance_exact)
+ ok = all_success and deterministic and instance_ok
+ out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
+ "instance_ok": int(instance_ok), "n_actions": int(len(acts)), "sim_steps": int(outs[0]["steps"]),
+ "task_failure": int(bool(outs[0]["reason"]) and not outs[0]["success"]),
+ "replay_wall_s": round(time.time() - t0, 1), "grader_error": 0, "video_rendered": 0, **cost}
+ if not a.no_video: # human-viewable replay (never affects the verdict)
+ try:
+ n = int(outs[0]["replayed_rows"])
+ s.render_video(acts[:n], os.path.join(LOG_DIR, "replay.mp4"), cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ import imageio.v2 as imageio
+ imageio.imwrite(os.path.join(LOG_DIR, "replay.last.png"), s.render_frame(s.default_camera(), (480, 640)))
+ out["video_rendered"] = int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4")))
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(ok, out)
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(False, {"success": 0, "grader_error": 1, **cost})
+ finally:
+ if s is not None:
+ s.close()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tasks/dexjoco-hammer-nail-i00-privileged/tests/instance.npz b/tasks/dexjoco-hammer-nail-i00-privileged/tests/instance.npz
new file mode 100644
index 0000000000..443d63038d
Binary files /dev/null and b/tasks/dexjoco-hammer-nail-i00-privileged/tests/instance.npz differ
diff --git a/tasks/dexjoco-hammer-nail-i00-privileged/tests/rcb_dexjoco.py b/tasks/dexjoco-hammer-nail-i00-privileged/tests/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-privileged/tests/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-hammer-nail-i00-privileged/tests/test.sh b/tasks/dexjoco-hammer-nail-i00-privileged/tests/test.sh
new file mode 100755
index 0000000000..00291aeff3
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-privileged/tests/test.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in a fresh process.
+# 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/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)
+mkdir -p /logs/verifier
+python /tests/grade.py --family hammer_nail --instance /tests/instance.npz --traj /app/output/trajectory.npz --repeat 2 \
+ 2> /logs/verifier/grade.log
diff --git a/tasks/dexjoco-hammer-nail-i00-standard/README.md b/tasks/dexjoco-hammer-nail-i00-standard/README.md
new file mode 100644
index 0000000000..ad3345aa3a
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-standard/README.md
@@ -0,0 +1,45 @@
+# dexjoco-hammer-nail-i00-standard
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | standard (`eai-standard/2.2`) |
+| Twin | `dexjoco-hammer-nail-i00-privileged` |
+| Simulator / robot | `dexjoco` / `franka-allegro` |
+| Family / instance | `hammer_nail` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `hammer_nail` (a Franka Panda arm with a 16-DoF Allegro hand) on the same frozen instance as `dexjoco-hammer-nail-i00-privileged`: Pick up the hammer and drive the nail into the wooden block by striking its head. A strike counts only if the hammer face was moving down faster than 0.02 m/s just before it touched the nail; each counted strike drives the nail 8 mm x min(3, speed / 0.02) deeper (at most 7.26 cm). Success: the nail is at least 4 cm deep.
+Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with the robot's own
+sensors, calibrated cameras (RGB, optional depth) and the robot's kinematics.
+
+## Difficulty
+Same instance and success check as `dexjoco-hammer-nail-i00-privileged`. In standard mode the agent loses resets, the
+simulator and the object poses: it sees camera images and proprioception, acts in chunks of tcp-target + hand-joint rows
+(or joint targets), and gets one episode, so it has to close the loop on what the cameras show and recover from its own
+mistakes without starting over.
+
+## Reference solution
+`solution/oracle_stream.py` streams the privileged reference's rows (`solution/oracle_trajectory.npz`, 202 rows, float32-exact)
+through the client as `ee_pose` 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 202 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 202 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `hammer_nail_demo_10_2026-02-05_19-18-55_029010` (DexJoCo-Datasets-Raw); instance sha `095c53d8e9a1cae0` |
+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); action types `ee_pose` and `joint_position`; cameras `front`, `back`, `left`, `right`, `top0`, `handcam_rgb` (640 x 480); `/kinematics` for the arm links, the hand mount and the tcp; crash recovery class `exact` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py`, as its privileged twin.
diff --git a/tasks/dexjoco-hammer-nail-i00-standard/environment/Dockerfile b/tasks/dexjoco-hammer-nail-i00-standard/environment/Dockerfile
new file mode 100644
index 0000000000..a778c94561
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-standard/environment/Dockerfile
@@ -0,0 +1,9 @@
+# Standard mode: the agent container has NO simulator and no DexJoCo 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 /app
diff --git a/tasks/dexjoco-hammer-nail-i00-standard/environment/client-requirements.txt b/tasks/dexjoco-hammer-nail-i00-standard/environment/client-requirements.txt
new file mode 100644
index 0000000000..8aa73a968f
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-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.0
diff --git a/tasks/dexjoco-hammer-nail-i00-standard/environment/docker-compose.yaml b/tasks/dexjoco-hammer-nail-i00-standard/environment/docker-compose.yaml
new file mode 100644
index 0000000000..93612f88bf
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-standard/environment/docker-compose.yaml
@@ -0,0 +1,24 @@
+# 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 OSMesa rendering; 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-dexjoco:0.1.2
+ 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_TASK: hammer_nail
+ RCB_INSTANCE: /srv/instance.npz
+ RCB_TOOL: /srv/rcb_dexjoco.py
+ RCB_DATA: /data
+ RCB_WALL_CLOCK_S: "5400"
+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in a few seconds
+ PYTHONPATH: /srv
+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction log
diff --git a/tasks/dexjoco-hammer-nail-i00-standard/environment/rcb1.py b/tasks/dexjoco-hammer-nail-i00-standard/environment/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-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/dexjoco-hammer-nail-i00-standard/environment/rcb_client.py b/tasks/dexjoco-hammer-nail-i00-standard/environment/rcb_client.py
new file mode 100644
index 0000000000..aa25b0e050
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-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/dexjoco-hammer-nail-i00-standard/environment/sim/finalize.sh b/tasks/dexjoco-hammer-nail-i00-standard/environment/sim/finalize.sh
new file mode 100755
index 0000000000..e0cf248720
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-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_dexjoco.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:?}"; TASK="${RCB_TASK:?}"
+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 --task "$TASK" --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --repeat 1 \
+ --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"))
+PY
diff --git a/tasks/dexjoco-hammer-nail-i00-standard/environment/sim/instance.npz b/tasks/dexjoco-hammer-nail-i00-standard/environment/sim/instance.npz
new file mode 100644
index 0000000000..443d63038d
Binary files /dev/null and b/tasks/dexjoco-hammer-nail-i00-standard/environment/sim/instance.npz differ
diff --git a/tasks/dexjoco-hammer-nail-i00-standard/environment/sim/rcb1.py b/tasks/dexjoco-hammer-nail-i00-standard/environment/sim/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-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/dexjoco-hammer-nail-i00-standard/environment/sim/rcb_dexjoco.py b/tasks/dexjoco-hammer-nail-i00-standard/environment/sim/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-standard/environment/sim/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-hammer-nail-i00-standard/environment/sim/rcb_limited.py b/tasks/dexjoco-hammer-nail-i00-standard/environment/sim/rcb_limited.py
new file mode 100644
index 0000000000..1ce1171787
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-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/dexjoco-hammer-nail-i00-standard/environment/sim/run.sh b/tasks/dexjoco-hammer-nail-i00-standard/environment/sim/run.sh
new file mode 100755
index 0000000000..49d4d045d4
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-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; done
diff --git a/tasks/dexjoco-hammer-nail-i00-standard/environment/sim/server.py b/tasks/dexjoco-hammer-nail-i00-standard/environment/sim/server.py
new file mode 100644
index 0000000000..ca5b61fc5c
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-standard/environment/sim/server.py
@@ -0,0 +1,625 @@
+"""eai-standard/2.2 sim service for DexJoCo (docs/STANDARD_MODE_2_2.md): the adapter of the shared layer rcb_limited.py;
+the simulator is rcb_dexjoco.Session (DexJoCo on MuJoCo 3.4, CPU physics, OSMesa rendering).
+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to
+/data/episode.jsonl.
+
+The robot is a Franka Panda with a 16-DoF Allegro hand, or two of them side by side (right arm first). One control step
+= 1/50 s (10 physics substeps of 2 ms). Two action types:
+ ee_pose DexJoCo's own row, per arm: the tcp target pose (xyz m, quaternion wxyz, world frame) that its
+ operational-space controller tracks + 16 Allegro joint targets (rad);
+ joint_position per arm: 7 arm joint targets + 16 Allegro joint targets; the arm's targets are turned into a tcp target
+ by forward kinematics (the controller tracks the tcp pose, not the joints).
+Either way, the executed (journaled, recorded) row is DexJoCo's own row, so the recorded trajectory replays in the
+privileged tooling unchanged. As in DexJoCo's evaluation the episode ends at the first success or task failure;
+otherwise when the agent's time is over (the collect hook's SIGUSR1).
+
+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 instance 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")
+TASK = os.environ.get("RCB_TASK", "water_plant")
+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.npz"))
+TASK_TEXT_FILE = os.environ.get("RCB_TASK_TEXT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "task_text.txt"))
+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "5400"))
+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 = 640, 480
+CTRL_HZ = 50.0
+DT = 1.0 / CTRL_HZ
+SUBSTEPS = 10
+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"] = "" # the sidecar's Session is not the agent's interaction log
+import rcb_dexjoco as M # noqa: E402
+import mujoco # noqa: E402
+
+M.SESSION_LOG = ""
+BIM = TASK.startswith("bimanual_")
+ADIM = 46 if BIM else 23
+EP = L.Episode(DATA, dim=ADIM, resume="exact")
+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()
+S = M.Session(TASK, instance=INSTANCE, image_size=(CAM_H, CAM_W))
+MD, D = S.model, S.data
+ARMS = S.arms()
+SFX = {a: (f"_{a}" if BIM else "") for a in ARMS}
+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz
+
+# ------------------------------------------------------------------------------------------------- the robot
+ARM_JOINTS = {a: [f"joint{i}{SFX[a]}" for i in range(1, 8)] for a in ARMS}
+HAND_CTRL = {a: np.asarray(S._hand_ctrl_ids(a)) for a in ARMS}
+HAND_JOINTS = {a: [MD.joint(int(MD.actuator_trnid[i, 0])).name for i in HAND_CTRL[a]] for a in ARMS} # action order
+ARM_CTRL = {a: [MD.actuator(f"actuator{i}{SFX[a]}").id for i in range(1, 8)] for a in ARMS}
+JOINTS = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]] # kinematics q = proprio joint_pos columns
+QADR = np.array([MD.jnt_qposadr[MD.joint(j).id] for j in JOINTS])
+VADR = np.array([MD.jnt_dofadr[MD.joint(j).id] for j in JOINTS])
+EFF_ACT = np.array([i for a in ARMS for i in list(ARM_CTRL[a]) + list(HAND_CTRL[a])])
+TCP_SITE = {a: MD.site(f"attachment_site{SFX[a]}").id for a in ARMS}
+TCP = {a: f"tcp{SFX[a]}" for a in ARMS}
+MOUNT_BODY = {a: f"attachment{SFX[a]}" for a in ARMS}
+LINKS = {a: [f"link{i}{SFX[a]}" for i in range(0, 8) if mujoco.mj_name2id(MD, mujoco.mjtObj.mjOBJ_BODY, f"link{i}{SFX[a]}") >= 0]
+ + [MOUNT_BODY[a]] for a in ARMS}
+KIN_LINKS = [n for a in ARMS for n in LINKS[a] + [TCP[a]]]
+JLIM = {j: MD.jnt_range[MD.joint(j).id].astype(float).tolist() for j in JOINTS}
+HLIM = {a: S.hand_limits(a) for a in ARMS} # actuator ctrlrange, action order
+ALIM = {} # joint_position limits (inside the joint ranges)
+for a in ARMS:
+ for j in ARM_JOINTS[a]:
+ ALIM[j] = JLIM[j]
+ for j, (lo, hi) in zip(HAND_JOINTS[a], HLIM[a]):
+ ALIM[j] = [max(float(lo), JLIM[j][0]), min(float(hi), JLIM[j][1])]
+POSE = ["x", "y", "z", "qw", "qx", "qy", "qz"]
+EE_LAYOUT = [] # per arm, right first
+for a in ARMS:
+ EE_LAYOUT += [f"{TCP[a]}_target_{k}" for k in POSE] + [f"{j}_target" for j in HAND_JOINTS[a]]
+JP_LAYOUT = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]]
+
+GROUPS = [
+ ("joint_pos", JOINTS, "measured joint positions (rad): per arm (right first) the 7 Panda joints, then the 16 Allegro "
+ "joints in the action's order"),
+ ("joint_vel", [f"{j}_vel" for j in JOINTS], "measured joint velocities (rad/s)"),
+ ("joint_effort", [f"{j}_effort" for j in JOINTS], "actuator efforts (N m): the arm's operational-space torques and the "
+ "hand's position-actuator forces"),
+ ("gripper_opening", [], "none: a 16-DoF Allegro hand, its finger joints are in joint_pos"),
+ ("tcp_pose", [f"{TCP[a]}_{k}" for a in ARMS for k in POSE], "measured tcp pose per arm (x y z m, quaternion wxyz, world)"),
+ ("tcp_target", [f"{TCP[a]}_target_{k}" for a in ARMS for k in POSE], "the tcp target the controller tracks now (the "
+ "ee_pose part of the last executed row)"),
+ ("hand_target", [f"{j}_target" for a in ARMS for j in HAND_JOINTS[a]], "the Allegro joint targets now (rad)"),
+]
+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)
+
+
+def _quat(xmat) -> np.ndarray:
+ q = np.zeros(4)
+ mujoco.mju_mat2Quat(q, np.asarray(xmat, dtype=np.float64).reshape(9))
+ return q
+
+
+# ------------------------------------------------------------------------------------------------- cameras
+CAMS = S.cameras()
+HAND_CAMS = [c for c in CAMS if c.startswith("handcam")]
+DEFAULT_CAMS = [S.default_camera()]
+GL2CV = np.diag([1.0, -1.0, -1.0, 1.0])
+
+
+def _intrinsic(cam: str) -> list:
+ fovy = math.radians(float(MD.cam_fovy[MD.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 _cam2world_gl(cam: str) -> np.ndarray:
+ i = MD.camera(cam).id
+ T = np.eye(4)
+ T[:3, :3] = D.cam_xmat[i].reshape(3, 3) # MuJoCo camera axes: OpenGL (x right, y up, z back)
+ T[:3, 3] = D.cam_xpos[i]
+ return T
+
+
+def _extrinsic(cam: str) -> np.ndarray:
+ return np.linalg.inv(_cam2world_gl(cam) @ GL2CV)[:3, :]
+
+
+def camera_info(cam: str) -> dict:
+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist(),
+ "image_size": [CAM_W, CAM_H]}
+
+
+def _mount(cam: str) -> dict:
+ i = MD.camera(cam).id
+ body = MD.body(int(MD.cam_bodyid[i])).name
+ if int(MD.cam_bodyid[i]) == 0:
+ return {"type": "static", "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist()}
+ T = np.eye(4) # body -> camera (OpenGL axes), then to OpenCV axes
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.cam_quat[i])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.cam_pos[i]
+ return {"type": "link", "parent_link": body, "link_T_cam_cv": (T @ GL2CV).tolist()}
+
+
+def _mounted(cam: str) -> str:
+ if cam.startswith("handcam"):
+ side = "the right" if cam.endswith("_right") else "the left" if cam.endswith("_left") else "the"
+ return f"on {side} hand's mount (moves with the hand)"
+ return {"front": "static, across the table, facing the robot", "back": "static, behind the robot, looking over the table",
+ "left": "static, at the robot's left", "right": "static, at the robot's right",
+ "top0": "static, above the table, looking down"}.get(cam, "static")
+
+
+# ------------------------------------------------------------------------------------------------- kinematics
+KD = mujoco.MjData(MD) # kinematics only: never stepped; the robot's joints are set, everything else stays put
+ARM_QI = {a: [JOINTS.index(j) for j in ARM_JOINTS[a]] for a in ARMS}
+
+
+def _fk(q) -> None:
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR] = np.asarray(q, dtype=np.float64)
+ mujoco.mj_kinematics(MD, KD)
+
+
+def _link_pose(name: str) -> list:
+ for a in ARMS:
+ if name == TCP[a]:
+ s = TCP_SITE[a]
+ return [*KD.site_xpos[s].tolist(), *_quat(KD.site_xmat[s]).tolist()]
+ b = MD.body(name).id
+ return [*KD.xpos[b].tolist(), *KD.xquat[b].tolist()]
+
+
+def tcp_from_arm_joints(a: str, q7) -> np.ndarray:
+ """The tcp pose (xyz + wxyz) of arm `a` with its 7 joints at q7 (the joint_position action's tcp target)."""
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR[ARM_QI[a]]] = q7
+ mujoco.mj_kinematics(MD, KD)
+ s = TCP_SITE[a]
+ return np.concatenate([KD.site_xpos[s], _quat(KD.site_xmat[s])])
+
+
+def do_kinematics(req: dict) -> dict:
+ """World frame. FK: every link of spec kinematics.links for q. IK: per tcp target, damped least squares over that
+ arm's 7 joints (position and orientation), within the joint ranges; the hand joints are taken from the seed."""
+ if req["op"] == "fk":
+ _fk(req["q"])
+ return L.fk_response({n: _link_pose(n) for n in req["links"]}, "world")
+ q = np.array(req["seed"] if req["seed"] is not None else D.qpos[QADR], dtype=np.float64)
+ errors = {}
+ jp, jr = np.zeros((3, MD.nv)), np.zeros((3, MD.nv))
+ for frame, pose in req["targets"].items():
+ a = next(x for x in ARMS if TCP[x] == frame)
+ idx = ARM_QI[a]
+ dofs = VADR[idx]
+ tp, tq = np.asarray(pose[:3]), np.asarray(pose[3:7])
+ lo = np.array([JLIM[JOINTS[i]][0] for i in idx]); hi = np.array([JLIM[JOINTS[i]][1] for i in idx])
+ for _ in range(req["max_iters"]):
+ _fk(q)
+ mujoco.mj_comPos(MD, KD) # the Jacobian needs cdof, which mj_kinematics alone leaves stale
+ s = TCP_SITE[a]
+ ep = tp - KD.site_xpos[s]
+ cq = _quat(KD.site_xmat[s])
+ dq = np.zeros(4); neg = np.zeros(4); er = np.zeros(3)
+ mujoco.mju_negQuat(neg, cq); mujoco.mju_mulQuat(dq, tq, neg); mujoco.mju_quat2Vel(er, dq, 1.0)
+ if np.linalg.norm(ep) < req["tol_pos_m"] and np.linalg.norm(er) < req["tol_rot_rad"]:
+ break
+ mujoco.mj_jacSite(MD, KD, jp, jr, s)
+ J = np.vstack([jp[:, dofs], jr[:, dofs]])
+ err = np.concatenate([ep, er])
+ step = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), err)
+ q[idx] = np.clip(q[idx] + step, lo, hi)
+ _fk(q)
+ s = TCP_SITE[a]
+ errors[frame] = (float(np.linalg.norm(tp - KD.site_xpos[s])), L.quat_angle(_quat(KD.site_xmat[s]), tq / np.linalg.norm(tq)))
+ ok = all(e[0] <= req["tol_pos_m"] and e[1] <= req["tol_rot_rad"] for e in errors.values())
+ return L.ik_response(q, ok, errors, "world", note="the tcp (attachment_site) of each arm; the hand joints are the seed's")
+
+
+# ------------------------------------------------------------------------------------------------- spec
+def _joint_spec(a: str) -> list:
+ out = []
+ for j, ai in zip(ARM_JOINTS[a], ARM_CTRL[a]):
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_ctrlrange[ai][1]), "group": f"{a}_arm"})
+ for j, ai in zip(HAND_JOINTS[a], HAND_CTRL[a]):
+ fl = bool(MD.actuator_forcelimited[ai]) and float(MD.actuator_forcerange[ai][1]) > 0
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_forcerange[ai][1]) if fl else None, "group": f"{a}_hand"})
+ return out
+
+
+def _tcp_spec(a: str) -> dict:
+ s = TCP_SITE[a]
+ T = np.eye(4)
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.site_quat[s])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.site_pos[s]
+ return {"parent_link": MD.body(int(MD.site_bodyid[s])).name, "link_T_frame": T.tolist(),
+ "definition": "DexJoCo's attachment_site: the flange where the Allegro hand is mounted, the point its "
+ "operational-space controller drives to the ee_pose target (not the fingertips)"}
+
+
+def _base(a: str) -> list:
+ b = D.body(f"link0{SFX[a]}")
+ return [*np.round(b.xpos, 6).tolist(), *np.round(b.xquat, 6).tolist()]
+
+
+GAINS = {}
+for _a in ARMS:
+ for _j, _ai in zip(HAND_JOINTS[_a], HAND_CTRL[_a]):
+ GAINS[_j] = {"stiffness": float(MD.actuator_gainprm[_ai][0]), "damping": float(MD.dof_damping[MD.jnt_dofadr[MD.joint(_j).id]])}
+ROBOT_NAME = "franka-allegro-bimanual" if BIM else "franka-allegro"
+try:
+ TASK_TEXT = open(TASK_TEXT_FILE).read().strip()
+except OSError:
+ TASK_TEXT = f"DexJoCo {TASK}"
+SPEC = {
+ "protocol": L.PROTOCOL,
+ "protocol_compat": list(L.COMPAT),
+ "simulator": "DexJoCo @ 8d23b0f on MuJoCo 3.4.0 (CPU physics, OSMesa rendering)",
+ "robot": ROBOT_NAME,
+ "task_text": TASK_TEXT,
+ "control_hz": CTRL_HZ,
+ "physics_substeps": SUBSTEPS,
+ "physics_hz": CTRL_HZ * SUBSTEPS,
+ "max_chunk_s": MAX_CHUNK_S,
+ "max_watch_s": MAX_WATCH_S,
+ "cameras": {c: {"rgb": True, "depth": True, "mounted": _mounted(c), "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),
+ "mount": _mount(c)} for c in CAMS},
+ "default_cameras": DEFAULT_CAMS,
+ "action_types": {
+ "ee_pose": {
+ "dim": ADIM, "layout": EE_LAYOUT,
+ "units": "per arm (right first): tcp target position (m, world frame), tcp target orientation (quaternion wxyz), "
+ "16 Allegro joint targets (rad)",
+ "frame": "world", "quaternion_order": "wxyz", "ee_frames": [TCP[a] for a in ARMS],
+ "hand_limits": {j: ALIM[j] for a in ARMS for j in HAND_JOINTS[a]},
+ "semantics": "DexJoCo's own action row. The arm tracks the tcp target through DexJoCo's operational-space "
+ "controller (it lags a moving target and stops where contact blocks it); the hand joints are "
+ "position-controlled. Rows are `dt` apart (a whole multiple of 1/50 s, at most 0.5 s); between rows "
+ "positions and joints move linearly and orientations by slerp (`linear`) or jump (`hold`); a row's "
+ "own values land exactly on its last control step. Hand targets outside the ranges are clamped by "
+ "the simulator and reported in `clipped`; a zero quaternion is a 400.",
+ },
+ "joint_position": {
+ "dim": ADIM, "layout": JP_LAYOUT, "units": "rad", "limits": {j: ALIM[j] for j in JP_LAYOUT},
+ "semantics": "per arm (right first): 7 Panda joint targets, then the 16 Allegro joint targets. The arm's "
+ "targets are turned into a tcp target by forward kinematics (as POST /kinematics fk) and the arm "
+ "tracks that pose through the same operational-space controller as ee_pose, whose null space "
+ "pulls towards DexJoCo's home posture: the tcp reaches FK(q), the measured joints may differ from q "
+ "in the arm's redundant direction. Rows `dt` apart, `linear` (in joint space) or `hold`; values "
+ "outside the limits are clipped and reported.",
+ },
+ "not_yet": ["joint_delta", "joint_velocity", "ee_delta", "joint_torque"],
+ },
+ "proprio_layout": PROPRIO_LAYOUT,
+ "proprio_groups": PROPRIO_GROUPS,
+ "static": {},
+ "world": {"frame": "DexJoCo's world frame: z up, metres; the robot" + ("s stand" if BIM else " stands")
+ + " at low x and reach" + ("" if BIM else "es") + " towards +x"
+ + (" (right arm at y < 0, left arm at y > 0)" if BIM else ""),
+ "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},
+ "episode": "one episode, no reset: it ends at the first success, at a task failure (see task_text), or when your time is over",
+ "robot_spec": {
+ "name": ROBOT_NAME,
+ "description": ("two Franka Panda arms side by side, each with a 16-DoF Allegro hand (right arm first)" if BIM
+ else "a Franka Panda arm with a 16-DoF Allegro hand"),
+ "base": {"type": "fixed", "pose": _base(ARMS[0]), **({"per_arm": {a: _base(a) for a in ARMS}} if BIM else {}),
+ "note": "pose of the arm's base link (link0), world frame, x y z + quaternion wxyz"},
+ "joints": [j for a in ARMS for j in _joint_spec(a)],
+ "grippers": {},
+ "controller": {"type": "arm: operational-space control of the tcp (torques); hand: joint position actuators",
+ "control_hz": CTRL_HZ, "physics_hz": CTRL_HZ * SUBSTEPS, "gains": GAINS,
+ "note": "arm: DexJoCo's opspace controller drives attachment_site to the tcp target (position gains "
+ "400 N/m, damping ratio 4, gravity compensation, null space towards the home posture), "
+ "torques limited to effort_limit; hand: position actuators (stiffness N m/rad) on joints "
+ "with their own damping (N m s/rad)"},
+ "tcp": {TCP[a]: _tcp_spec(a) for a in ARMS},
+ },
+ "kinematics": {"endpoint": "/kinematics", "joint_names": JOINTS, "frame": "world", "quaternion_order": "wxyz",
+ "links": KIN_LINKS, "tcp_frames": [TCP[a] for a in ARMS], "ee_frames": [TCP[a] for a in ARMS],
+ "ik_targets": [TCP[a] for a in ARMS], "ik": {"tol_pos_m": 0.001, "tol_rot_rad": 0.01, "max_iters": 300},
+ "note": "the arm links, the hand mount (the hand cameras' parent) and the tcp, world frame; ik solves "
+ "each tcp target over that arm's 7 joints"},
+ "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()
+
+
+# ------------------------------------------------------------------------------------------------- state and frames
+def ctrl_steps() -> int:
+ return int(S.steps)
+
+
+def proprio_row() -> np.ndarray:
+ tcp, tgt, hand = [], [], []
+ for a in ARMS:
+ s = TCP_SITE[a]
+ tcp += [D.site_xpos[s], _quat(D.site_xmat[s])]
+ t = S._arm_target(a)
+ tgt.append(t[:7]); hand.append(t[7:23])
+ return np.concatenate([D.qpos[QADR], D.qvel[VADR], D.actuator_force[EFF_ACT], *tcp, *tgt, *hand]).astype(np.float32)
+
+
+def grab(cams, want_depth: bool):
+ rgb, dep = {}, {}
+ for c in cams:
+ rgb[c] = S.render_frame(c, (CAM_H, CAM_W))
+ if want_depth:
+ r = S._renderer # the one renderer (a second OSMesa context reads back garbage)
+ r.enable_depth_rendering()
+ try:
+ r.update_scene(D, camera=c)
+ dep[c] = r.render().astype(np.float32).copy()
+ finally:
+ r.disable_depth_rendering()
+ return rgb, dep
+
+
+def extrinsics(cams) -> dict:
+ return {c: _extrinsic(c) for c in cams}
+
+
+def summary() -> dict:
+ n = int(E.get("episode_control_steps") or ctrl_steps())
+ 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"],
+ "task": TASK, "protocol": L.PROTOCOL, "n_actions": len(ROWS), "task_failure": int(str(E["reason"] or "").startswith("failure")),
+ **EP.final_fields()}
+
+
+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 finish(reason: str) -> None:
+ """The episode is over: record the live verdict and dump the trajectory 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()
+ E["success"] = bool(S.success)
+ 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()
+ S.save_trajectory(np.asarray(ROWS, dtype=np.float64).reshape(-1, ADIM), os.path.join(DATA, "trajectory.npz"),
+ {"source": "standard-mode episode", "reason": E["reason"]})
+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})
+ write_final()
+
+
+def ctrl_step(a, rec) -> bool:
+ """One executed control step (DexJoCo's own row), journaled. True when the call must stop here."""
+ a = np.asarray(a, dtype=np.float64)
+ running = S.step(a)
+ ROWS.append(a.copy())
+ stop = EP.journal(a)
+ rec.tick()
+ if not running:
+ finish(S.reason or "done")
+ 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 DEFAULT_CAMS
+ if not isinstance(cams, list) or any(c not in CAMS for c in cams):
+ raise ValueError(f"unknown cameras {cams}; cameras: {CAMS}")
+ return list(dict.fromkeys(cams))
+
+
+def meta_common(cams) -> dict:
+ n = ctrl_steps()
+ return {"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}}
+
+
+def _native_from_ee(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ """ee_pose rows are executed as sent (the recorded row is what the agent commanded); hand targets outside the
+ actuator ranges are clamped by MuJoCo itself (ctrllimited) and only reported."""
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ if float(np.linalg.norm(row[o + 3:o + 7])) < 1e-6:
+ raise ValueError(f"row {ri}: the {a} tcp quaternion has zero norm")
+ for j in range(16):
+ lo, hi = HLIM[a][j]
+ v = row[o + 7 + j]
+ if v < lo or v > hi:
+ clipped.append({"row": ri, "index": int(o + 7 + j), "reason": f"{EE_LAYOUT[o + 7 + j]} outside [{lo:.3f}, {hi:.3f}]: clamped by the simulator"})
+ return row
+
+
+def _clip_joints(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ lo = np.array([ALIM[j][0] for j in JP_LAYOUT]); hi = np.array([ALIM[j][1] for j in JP_LAYOUT])
+ out = np.clip(row, lo, hi)
+ for j in np.flatnonzero(out != row)[:20]:
+ clipped.append({"row": ri, "index": int(j), "reason": f"{JP_LAYOUT[j]} limit [{lo[j]:g}, {hi[j]:g}]"})
+ return out
+
+
+def _native_from_joints(q: np.ndarray) -> np.ndarray:
+ out = []
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ out += [tcp_from_arm_joints(a, q[o:o + 7]), q[o + 7:o + 23]]
+ return np.concatenate(out)
+
+
+def _check_chunk(typ: str, A: np.ndarray, dt: float, interp: str, video: str) -> int:
+ k = dt / DT
+ if A.ndim != 2 or A.shape[1] != ADIM:
+ raise ValueError(f"{typ} actions must be (T, {ADIM}), got {list(A.shape)}")
+ if A.shape[0] == 0:
+ raise ValueError("no rows")
+ 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")
+ return int(round(k))
+
+
+def do_submit(meta: dict, A: np.ndarray):
+ typ = meta.get("type")
+ if typ not in ("ee_pose", "joint_position"):
+ raise ValueError(f"type must be ee_pose or joint_position (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)
+ n = _check_chunk(typ, A, dt, interp, video)
+ clipped: list = []
+ if typ == "ee_pose":
+ A = np.stack([_native_from_ee(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ else:
+ A = np.stack([_clip_joints(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ rec = recorder(cams, fps, meta)
+ E["calls"] += 1
+ step0, before = E["step"], ctrl_steps()
+ rec.tick(force=True)
+ if typ == "ee_pose":
+ prev = np.asarray(S.hold_action(), dtype=np.float64)
+ else:
+ prev = np.concatenate([np.concatenate([D.qpos[QADR[ARM_QI[a]]], S._arm_target(a)[7:23]]) for a in ARMS])
+ for row in A:
+ E["step"] += 1
+ stop = False
+ for s in range(1, n + 1):
+ if interp == "hold" or s == n:
+ target = row # a row's own values land exactly on its last control step
+ else:
+ target = prev + (row - prev) * (s / n)
+ if typ == "ee_pose":
+ for k in range(len(ARMS)):
+ o = 23 * k
+ target[o + 3:o + 7] = M.quat_slerp(prev[o + 3:o + 7], row[o + 3:o + 7], s / n)
+ native = target if typ == "ee_pose" else _native_from_joints(target)
+ if ctrl_step(native, rec):
+ stop = True
+ break
+ prev = row
+ 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"], "type": typ, "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 = np.asarray(S.hold_action(), dtype=np.float64)
+ 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={"task": TASK, "instance_sha": S.instance_sha, "instance_ok": bool(S.instance_exact), "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} DexJoCo sim ready ({TASK}; 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/dexjoco-hammer-nail-i00-standard/environment/sim/task_text.txt b/tasks/dexjoco-hammer-nail-i00-standard/environment/sim/task_text.txt
new file mode 100644
index 0000000000..e9fe781db4
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-standard/environment/sim/task_text.txt
@@ -0,0 +1,3 @@
+Pick up the hammer and drive the nail into the wooden block by striking its head. A strike counts only if the hammer face was moving down faster than 0.02 m/s just before it touched the nail; each counted strike drives the nail 8 mm x min(3, speed / 0.02) deeper (at most 7.26 cm). Success: the nail is at least 4 cm deep.
+
+The hammer lies on the table at the robot's right (low y); the nail stands upright in a wooden block in front of the robot. The nail is not a free body: it only moves down when struck.
diff --git a/tasks/dexjoco-hammer-nail-i00-standard/instruction.md b/tasks/dexjoco-hammer-nail-i00-standard/instruction.md
new file mode 100644
index 0000000000..2cda4acac9
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-standard/instruction.md
@@ -0,0 +1,68 @@
+# DexJoCo · hammer_nail — STANDARD MODE (robot as a service, eai-standard/2.2)
+
+You control a Franka Panda arm with a 16-DoF Allegro hand, **as if it were real hardware**: the simulator runs in a service you cannot open. You get
+one client and one episode. **Task:** Pick up the hammer and drive the nail into the wooden block by striking its head. A strike counts only if the hammer face was moving down faster than 0.02 m/s just before it touched the nail; each counted strike drives the nail 8 mm x min(3, speed / 0.02) deeper (at most 7.26 cm). Success: the nail is at least 4 cm deep.
+
+The hammer lies on the table at the robot's right (low y); the nail stands upright in a wooden block in front of the robot. The nail is not a free body: it only moves down when struck.
+
+## Rules (real-robot rules)
+- **No reset.** The episode starts when the service comes up and ends on success, on a task failure (see the task), when
+ your time is up, or on a simulator error. Knocked-over objects stay knocked over.
+- **No privileged state.** You see what the cameras see (RGB, and depth on request, with each camera's calibration) plus
+ the robot's own proprioception (joints, tcp poses, the current targets). No object poses, no success check:
+ `meta["done"]` / `meta["reason"]` tell you when the episode is over and why.
+- Steps are unlimited; your wall-clock budget (90 minutes) is the limit (`meta["time_left_s"]`). Actions and
+ simulated time are reported as cost. Do not stop before the task is solved.
+- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
+ `/app/output/gen.py` for the record (save it early, update it as you go).
+- **Nothing is put into your context automatically.** Images and videos come back as arrays/bytes in a Python object;
+ what you look at and where you store it is your code's decision.
+
+## Client (`/opt/tools/rcb_client.py`, protocol `eai-standard/2.2`)
+```python
+from rcb_client import Robot
+r = Robot() # connects (waits while the service starts)
+spec = r.spec() # action types, cameras (+ calibration), proprio layout, robot_spec, kinematics, budget
+obs = r.get_obs() # current frames of spec["default_cameras"]: obs.last[cam] -> uint8 (480, 640, 3)
+obs = r.get_obs(cameras=["front", "handcam_rgb"], depth=True) # + obs.last_depth[cam] -> float32 (480, 640) z-depth (m)
+obs.meta["proprio"] # {"layout": [...], "now": [...]}; obs.group("tcp_pose", now=True)
+obs.meta["cameras"] # per camera intrinsic_cv / extrinsic_cv / cam2world_gl for these frames
+obs = r.get_obs(seconds=2.0, video="mp4") # hold the current targets and watch for 2 s (max 30): obs.video[cam] = mp4 bytes
+
+res = r.submit("ee_pose", rows, dt=0.1) # rows: (T, 23) targets dt seconds apart, executed at 50 Hz with interpolation
+res = r.submit("joint_position", q_rows, dt=0.1) # (T, 23) joint targets instead (see below)
+res.meta["done"], res.meta["reason"], res.meta["clipped"], res.meta["control_steps_chunk"]
+res.video["front"]; res.last["front"]; res.proprio # mp4 of the chunk, last frame, float32 (N, P) proprio per frame
+res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, proprio.npy, ...
+r.fk(q); r.ik({"tcp": pose}, seed=q) # kinematics of the robot (stateless: no physics, no time)
+r.status() # calls, control steps, done, reason, elapsed time
+```
+Cameras: `front`, `back`, `left`, `right`, `top0` (static), `handcam_rgb` (on the hand mount; they move,
+so use the calibration that comes with each response; `spec["cameras"][cam]["mount"]` gives the static pose or the mount
+link). Resolution 640x480. Rendering runs on the CPU: ask only for the cameras you need; `video="none"` makes a chunk
+fastest. If a call fails with a connection error the service may have crashed: it resumes the same episode;
+`r.wait_ready()`, then check `r.status()` (`spec["on_service_error"]`).
+
+### Action type `ee_pose` (23) — DexJoCo's own action
+tcp target position (3, metres, world frame), tcp target orientation (4, quaternion wxyz), 16
+Allegro joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+target and stops where contact blocks it); the hand joints are position-controlled. Rows are `dt` apart (a whole multiple
+of 1/50 s, at most 0.5 s); between rows positions and joints move linearly and orientations by slerp
+(`interpolate="linear"`) or jump (`"hold"`); a chunk may cover at most 10 s. Hand targets outside the ranges
+(`spec["action_types"]["ee_pose"]["hand_limits"]`) are clamped by the simulator and listed in `meta["clipped"]`. Build
+the next row from the `tcp_target` and `hand_target` proprio groups to move smoothly.
+
+### Action type `joint_position` (23)
+7 Panda joint targets, then the 16 Allegro joint targets (rad). The service turns the arm's targets
+into a tcp target by forward kinematics and the same controller tracks it: the tcp reaches FK(q), but the measured arm
+joints may differ from q in the arm's redundant direction (the controller's null space pulls towards a home posture).
+Out-of-limit values are clipped and reported.
+
+## Conventions
+- World frame, metres, z up; the robot stands at low x and reaches towards +x; each
+ arm's base pose is in `spec["robot_spec"]["base"]`. No other world coordinates are given (D7: the cameras are
+ calibrated, depth is available). Quaternions are **WXYZ**.
+- The tcp (`tcp`) is the hand's mounting flange (`spec["robot_spec"]["tcp"]`), not the fingertips. Allegro joint
+ order: index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger = spread, 1-3 = flexion
+ from the knuckle out; thumb 12 = opposition).
+- Control runs at 50 Hz (10 physics substeps of 2 ms). There is no step budget: your wall-clock time is the limit.
diff --git a/tasks/dexjoco-hammer-nail-i00-standard/solution/oracle_stream.py b/tasks/dexjoco-hammer-nail-i00-standard/solution/oracle_stream.py
new file mode 100644
index 0000000000..19877300c1
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-standard/solution/oracle_stream.py
@@ -0,0 +1,43 @@
+"""Oracle (standard mode): streams the reference rows (the human demonstration's own actions, one per 1/50 s control step,
+float32-exact) as `ee_pose` 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
+
+A = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle_trajectory.npz"))["actions"].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(A), flush=True)
+t0, i = time.time(), 0
+while i < len(A):
+ chunk = A[i:i + per_chunk]
+ try:
+ res = r.submit("ee_pose", chunk, dt=dt, interpolate="hold", 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/dexjoco-hammer-nail-i00-standard/solution/oracle_trajectory.npz b/tasks/dexjoco-hammer-nail-i00-standard/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..9608c88267
Binary files /dev/null and b/tasks/dexjoco-hammer-nail-i00-standard/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-hammer-nail-i00-standard/solution/solve.sh b/tasks/dexjoco-hammer-nail-i00-standard/solution/solve.sh
new file mode 100755
index 0000000000..1bd55d898f
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-standard/solution/solve.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+# Oracle (standard mode): streams the reference trajectory's rows (solution/oracle_trajectory.npz, one row per control
+# step) as `ee_pose` chunks through the client. Uses no privileged information at run time (only the pre-recorded rows);
+# the service's recorded trajectory is then exactly the privileged reference.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_stream.py /app/output/gen.py
+python /solution/oracle_stream.py
diff --git a/tasks/dexjoco-hammer-nail-i00-standard/task.toml b/tasks/dexjoco-hammer-nail-i00-standard/task.toml
new file mode 100644
index 0000000000..ec65776e21
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-standard/task.toml
@@ -0,0 +1,52 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator 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/dexjoco-hammer-nail-i00-standard"
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): DexJoCo hammer_nail (a Franka Panda arm with a 16-DoF Allegro hand) on the same frozen instance as dexjoco-hammer-nail-i00-privileged. Pick up the hammer and drive the nail into the wooden block by striking its head. The agent only gets a client: calibrated cameras (RGB, optional depth), the robot's joints and tcp poses, tcp-target + hand-joint chunks at 50 Hz, the robot's kinematics; one episode, no reset, no object state; the sim service records the episode, replays it in fresh processes and grades it."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "standard-mode", "robot-as-a-service", "hammer_nail"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro"
+family = "hammer_nail"
+mode = "standard"
+protocol = "eai-standard/2.2"
+oracle = "full"
+expert_time_estimate_hours = 2.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 = 3600
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
diff --git a/tasks/dexjoco-hammer-nail-i00-standard/tests/Dockerfile b/tasks/dexjoco-hammer-nail-i00-standard/tests/Dockerfile
new file mode 100644
index 0000000000..26bc699ebe
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-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.sh
diff --git a/tasks/dexjoco-hammer-nail-i00-standard/tests/grade.py b/tasks/dexjoco-hammer-nail-i00-standard/tests/grade.py
new file mode 100644
index 0000000000..003b933315
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-standard/tests/grade.py
@@ -0,0 +1,60 @@
+"""Standard-mode verifier (DexJoCo): 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 frozen 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"))),
+ "task_failure": int(bool(d.get("task_failure"))),
+ "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),
+ "calls": int(d.get("calls") or 0),
+ "elapsed_s": float(d.get("elapsed_s") or 0),
+ "video_rendered": int(bool(d.get("video"))),
+ # 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 frozen 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/dexjoco-hammer-nail-i00-standard/tests/test.sh b/tasks/dexjoco-hammer-nail-i00-standard/tests/test.sh
new file mode 100755
index 0000000000..bc608aa8b9
--- /dev/null
+++ b/tasks/dexjoco-hammer-nail-i00-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
diff --git a/tasks/dexjoco-pick-bucket-i00-privileged/README.md b/tasks/dexjoco-pick-bucket-i00-privileged/README.md
new file mode 100644
index 0000000000..38a038c0d1
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-privileged/README.md
@@ -0,0 +1,49 @@
+# dexjoco-pick-bucket-i00-privileged
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | privileged |
+| Twin | `dexjoco-pick-bucket-i00-standard` |
+| Simulator / robot | `dexjoco` / `franka-allegro` |
+| Family / instance | `pick_bucket` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `pick_bucket` (a Franka Panda arm with a 16-DoF Allegro hand): Put the boxed food into the bucket, then lift the bucket. Success: the boxed food's centre is inside the bounding box of the bucket's eight reference corners AND the bucket's bottom is at least 0.15 m above where it started, at the same control step.
+Privileged mode: the agent works in the simulator's container with live object poses, unlimited resets and thin motion
+primitives, and hands in one trajectory replayed open-loop from the frozen instance.
+
+## Difficulty
+First-pass rating: medium. Dexterous manipulation with a 16-DoF hand on a 7-DoF arm (23 action values per control step);
+the primitives only move tcp and hand-joint targets, so grasping, pressing and every other skill is the agent's. The
+reference (the human teleoperator's demonstration) takes 580 control steps (11.6 s at 50 Hz).
+
+## Reference solution
+`solution/oracle_trajectory.npz` = the human demonstration's own actions, rounded to float32 (the standard client's
+precision; the rounded rows still succeed) and replayed from the frozen instance until the episode ends in success
+(580 rows). The demonstration is public (DexJoCo-Datasets-Raw on Hugging Face), so agent egress is
+limited to the model APIs.
+
+## Verification
+Open-loop replay of `/app/output/trajectory.npz` from `tests/instance.npz`, twice in a fresh process in the verifier's own
+sandbox (no network); pass iff both episodes end in success, their final-state hashes agree and the rebuilt instance
+matches its recorded hash (`tests/grade.py`); plus `/logs/verifier/replay.mp4`. Oracle: success after 580 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `bucket_pick_demo_10_2026-03-10_18-19-00_120725` (DexJoCo-Datasets-Raw), restored with DexJoCo's own state restorer; instance sha `1cb042bf6d46ad45` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Tooling notes
+DexJoCo's reset samples object poses from the global RNG and its state restorer edits the MuJoCo model (table height,
+fixed bodies), so `instance.npz` stores the full physics state (`mjSTATE_INTEGRATION`), the mocap targets, the controls,
+every numeric model array a task can change, and the env's Python-side task state. Its per-step camera rendering,
+real-time sleep, episode cap and hanoi's wall-clock auto-reset are disabled in the tooling (`rcb_dexjoco.py`).
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py` from `scripts/dexjoco/instances/pick_bucket/` (`make_instances.py`).
diff --git a/tasks/dexjoco-pick-bucket-i00-privileged/environment/Dockerfile b/tasks/dexjoco-pick-bucket-i00-privileged/environment/Dockerfile
new file mode 100644
index 0000000000..d736fe8a7d
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-privileged/environment/Dockerfile
@@ -0,0 +1,7 @@
+# Base image = DexJoCo on MuJoCo 3.4.0 (images/dexjoco/). Everything task-specific is copied here. CPU only.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY instance.npz /app/instance.npz
+COPY rcb_dexjoco.py /opt/tools/rcb_dexjoco.py
+ENV PYTHONPATH=/opt/tools
+RUN mkdir -p /app/output
+WORKDIR /app
diff --git a/tasks/dexjoco-pick-bucket-i00-privileged/environment/instance.npz b/tasks/dexjoco-pick-bucket-i00-privileged/environment/instance.npz
new file mode 100644
index 0000000000..473da0693d
Binary files /dev/null and b/tasks/dexjoco-pick-bucket-i00-privileged/environment/instance.npz differ
diff --git a/tasks/dexjoco-pick-bucket-i00-privileged/environment/rcb_dexjoco.py b/tasks/dexjoco-pick-bucket-i00-privileged/environment/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-privileged/environment/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-pick-bucket-i00-privileged/instruction.md b/tasks/dexjoco-pick-bucket-i00-privileged/instruction.md
new file mode 100644
index 0000000000..2252574788
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-privileged/instruction.md
@@ -0,0 +1,70 @@
+# DexJoCo · pick_bucket — frozen instance
+
+You control a Franka Panda arm with a 16-DoF Allegro hand (DexJoCo on MuJoCo 3.4) via Python. **Task:** Put the boxed food into the bucket, then lift the bucket. Success: the boxed food's centre is inside the bounding box of the bucket's eight reference corners AND the bucket's bottom is at least 0.15 m above where it started, at the same control step.
+
+The bucket stands on the table with a hinged handle over it; the boxed food lies next to it. The handle swings on a hinge (`bucket_handle`). `s.objects()` gives the live poses of the task objects (`bucket`, `bucket_handle`, `boxed_food`, `table_top`). DexJoCo's success code (from
+`/opt/dexjoco/dexjoco/dexjoco/sim/envs/panda_pick_bucket_env.py`; `step()` ends the episode on success or on a task failure):
+```python
+def _compute_success(self):
+ box_pos = np.array(self._data.sensor("boxed_food_0_pos").data, dtype=float)
+ site_ids = [self.model.site(f"bucket_ref_{i}").id for i in range(8)]
+ corners = np.array(self._data.site_xpos[site_ids], dtype=float) # (8,3)
+ mins = corners.min(axis=0)
+ maxs = corners.max(axis=0)
+ inside = np.all(box_pos >= mins) and np.all(box_pos <= maxs)
+ bottom_z = self._data.site_xpos[self._bucket_bottom_site_ids, 2]
+ lifted = np.all(bottom_z - self._bucket_bottom_z0 >= 0.15)
+ success = inside and lifted
+
+ return success
+```
+
+This is a *fixed scene instance*: object poses, the table height and the robot's start pose never change between
+resets. You may reset and retry as many times as you want. Your deliverable is **one replayable trajectory**, not a
+general policy.
+
+## Deliverable
+Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
+open-loop from the same initial state in a fresh process and scored 1 if its episode ends in success, else 0. Also
+leave the script that produced it at `/app/output/gen.py`. You have 90 minutes of wall clock: save a
+first trajectory early, improve it, and do not stop before the task is solved.
+
+## Tooling (already installed; run `python` from any directory)
+```python
+from rcb_dexjoco import Session
+s = Session("pick_bucket", instance="/app/instance.npz") # ~1 s: builds the env and loads the frozen state
+s.reset() # back to the frozen initial state (as often as you like; an exact snapshot restore)
+s.objects() # live task objects: name -> pos, quat_wxyz (bodies) / pos (sites) / qpos (joints)
+s.state() # DexJoCo's state dict: tcp_pose, gripper_pose (hand joints), INITIAL object poses, table height
+p = s.primitives() # thin wrappers of the low-level action; each has a docstring: help(p["move_ee"])
+p["move_ee"]("right", pos, quat_wxyz) # straight-line + slerp motion of an arm's tcp target, then settle
+p["set_hand"]("right", q16) # interpolate the 16 Allegro joint targets
+p["hold"](10); p["set_targets"](row, steps) # keep every target / send one raw action row
+p["get_ee_pose"]("right"); p["get_ee_target"]("right"); p["get_hand"]("right"); p["get_body_pose"](name)
+s.render_frame("front") # RGB uint8 (480, 640, 3); cameras: ['front', 'back', 'left', 'right', 'top0', 'handcam_rgb']; s.render_grid()
+s.step(action) # one control step (23 values, below) = 1/50 s; returns False once the episode is over
+s.record_start(); ...; actions = s.record_stop() # (T, 23) actions, one row per control step
+s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+s.replay(actions) # resets, replays open-loop until the episode ends, returns status -> self-check
+s.save_trajectory(actions, "/app/output/trajectory.npz")
+s.render_video(actions, "/app/output/check.mp4", cameras=["front"]) # replays from the frozen state into a video
+```
+The primitives are deliberately thin (tcp target moves, hand joint targets, hold): grasping, pressing, striking and
+every other skill are yours to build from them. `s.bodies()` lists every MuJoCo body for `p["get_body_pose"]`.
+
+CLI equivalent of the grader:
+`python /opt/tools/rcb_dexjoco.py replay --task pick_bucket --instance /app/instance.npz --traj /app/output/trajectory.npz`
+
+## Conventions
+- World frame, metres; z up; the robot stands at low x and reaches towards +x. The table top is at z = 0.946. Arm base (`link0`): link0 [-0.75, 0.0, 0.924]. Quaternions are **WXYZ**.
+- Action (23): tcp target position (3), tcp target orientation (4, wxyz), 16 Allegro
+ joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+ target and stops where contact blocks it); the hand joints are position-controlled. `s.hold_action()` is the no-op.
+ At the start the tcp target is [-0.443, -0.0, 1.517] / [0.0, 1.0, 0.0, 0.0].
+- Allegro joint order: index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger =
+ spread, 1-3 = flexion from the knuckle out; thumb 12 = opposition).
+ Target ranges (rad, same for every finger slot, thumb last): low [-0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, 0.26, -0.1, -0.19, -0.16], high [0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 1.4, 1.16, 1.64, 1.72]; the simulator clamps
+ targets to them.
+- Control runs at 50 Hz (10 physics substeps of 2 ms). DexJoCo's own episode cap and real-time pacing are lifted: there
+ is no step budget, your wall-clock time is the limit (~350 control steps/s here). An episode ends at the
+ first success or task failure; `s.step` then refuses further actions until `s.reset()`.
diff --git a/tasks/dexjoco-pick-bucket-i00-privileged/solution/gen.py b/tasks/dexjoco-pick-bucket-i00-privileged/solution/gen.py
new file mode 100644
index 0000000000..0e1f7e3bc7
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-privileged/solution/gen.py
@@ -0,0 +1,4 @@
+# How solution/oracle_trajectory.npz was made (scripts/dexjoco/make_instances.py): the DexJoCo human demonstration's
+# own actions (replay.zarr data/action), rounded to float32, replayed from the frozen instance with Session.replay until
+# the episode ended in success (holding the last row a few steps where the rounded rows ended short of a hold count),
+# truncated there and saved with Session.save_trajectory.
diff --git a/tasks/dexjoco-pick-bucket-i00-privileged/solution/oracle_trajectory.npz b/tasks/dexjoco-pick-bucket-i00-privileged/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..8e5a6a7641
Binary files /dev/null and b/tasks/dexjoco-pick-bucket-i00-privileged/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-pick-bucket-i00-privileged/solution/solve.sh b/tasks/dexjoco-pick-bucket-i00-privileged/solution/solve.sh
new file mode 100755
index 0000000000..7909c90cb8
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-privileged/solution/solve.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+# Reference solution: the human demonstration's actions (float32), replayed through the task tooling until success.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_trajectory.npz /app/output/trajectory.npz
+cp /solution/gen.py /app/output/gen.py
diff --git a/tasks/dexjoco-pick-bucket-i00-privileged/task.toml b/tasks/dexjoco-pick-bucket-i00-privileged/task.toml
new file mode 100644
index 0000000000..e56c3783ba
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-privileged/task.toml
@@ -0,0 +1,37 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator or the instance, not this.
+schema_version = "1.3"
+artifacts = ["/app/output/"]
+
+[task]
+name = "robot-coding-bench/dexjoco-pick-bucket-i00-privileged"
+description = "DexJoCo pick_bucket (a Franka Panda arm with a 16-DoF Allegro hand, MuJoCo): produce one replayable trajectory. Put the boxed food into the bucket, then lift the bucket. Frozen scene instance (the initial state of a DexJoCo human demonstration)."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "code-as-policy", "trajectory", "pick_bucket"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro"
+family = "pick_bucket"
+mode = "privileged"
+oracle = "full"
+expert_time_estimate_hours = 2.0
+
+[verifier]
+timeout_sec = 1800.0
+environment_mode = "separate" # the verifier runs in its own sandbox (tests/Dockerfile); the agent container is gone by then
+network_mode = "no-network"
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
+
+[verifier.environment]
+build_timeout_sec = 1800.0
diff --git a/tasks/dexjoco-pick-bucket-i00-privileged/tests/Dockerfile b/tasks/dexjoco-pick-bucket-i00-privileged/tests/Dockerfile
new file mode 100644
index 0000000000..a2620a4da8
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-privileged/tests/Dockerfile
@@ -0,0 +1,8 @@
+# Separate verifier sandbox (PROTOCOL §2.6): the same simulator image with the verifier's own copies of the tooling and
+# the frozen instance baked in. Nothing the agent did in its container reaches this one: Harbor uploads only the declared
+# artifacts (/app/output/), so a patched success check in the agent container cannot count.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY grade.py instance.npz rcb_dexjoco.py test.sh /tests/
+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
+ENV PYTHONPATH=/tests
+WORKDIR /tests
diff --git a/tasks/dexjoco-pick-bucket-i00-privileged/tests/grade.py b/tasks/dexjoco-pick-bucket-i00-privileged/tests/grade.py
new file mode 100644
index 0000000000..ad916e8bb9
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-privileged/tests/grade.py
@@ -0,0 +1,109 @@
+"""Verifier entry point for the privileged DexJoCo tasks: replay /app/output/trajectory.npz from the frozen instance and
+write Harbor rewards.
+
+ python /tests/grade.py --family water_plant --instance /tests/instance.npz --traj /app/output/trajectory.npz
+
+Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only; Harbor rejects strings), a replay video
+/logs/verifier/replay.mp4 (front camera + wrist camera) and replay.last.png. Replays `--repeat` times in this fresh
+process; success requires every replay to end its episode in success (DexJoCo's own rule: the episode ends at the first
+success or task failure) AND all final-state hashes to agree (MuJoCo on the CPU is bit-deterministic), and the frozen
+instance rebuilt here from tests/instance.npz must match its recorded hash.
+"""
+from __future__ import annotations
+import argparse, json, os, sys, time, traceback
+import numpy as np
+
+LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")
+
+
+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 self_reported_cost() -> dict:
+ # From the tooling's append-only log in the agent's container: SELF-REPORTED accounting, never evidence.
+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_records": 0, "agent_replays": 0,
+ "agent_cost_self_reported": 1}
+ try:
+ with open("/app/output/rcb_session_log.jsonl") 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 == "session_end": cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)
+ elif ev == "record": cost["agent_records"] += 1
+ elif ev == "replay": cost["agent_replays"] += 1
+ except Exception: # noqa: BLE001 — one bad line must not sink the verdict
+ continue
+ except Exception: # noqa: BLE001
+ pass
+ return cost
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--family", required=True); ap.add_argument("--instance", required=True)
+ ap.add_argument("--traj", default="/app/output/trajectory.npz"); ap.add_argument("--repeat", type=int, default=2)
+ ap.add_argument("--no-video", action="store_true")
+ a = ap.parse_args()
+ cost = self_reported_cost()
+ os.environ["RCB_SESSION_LOG"] = "" # the verifier's own sessions are not the agent's cost
+ if not os.path.isfile(a.traj):
+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost}); return 0
+ s = None
+ try:
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the verifier's own copy of the tooling
+ import rcb_dexjoco
+ rcb_dexjoco.SESSION_LOG = ""
+ from rcb_dexjoco import Session, MAX_STEPS
+ d = np.load(a.traj, allow_pickle=False)
+ if str(d["task"]) != a.family:
+ write(False, {"success": 0, "wrong_family": 1, "grader_error": 0, **cost}); return 0
+ acts = np.asarray(d["actions"], dtype=np.float64)
+ s = Session(a.family, instance=a.instance)
+ if (acts.ndim != 2 or acts.shape[1] != s.action_dim or acts.shape[0] > MAX_STEPS
+ or not np.all(np.isfinite(acts))):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0,
+ "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0, **cost}); return 0
+ t0 = time.time()
+ outs = []
+ for _ in range(a.repeat):
+ try:
+ outs.append(s.replay(acts))
+ except (ValueError, rcb_dexjoco.PrimitiveError):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0, "n_actions": int(len(acts)), **cost}); return 0
+ all_success = all(o["success"] for o in outs)
+ deterministic = len({o["state_sha"] for o in outs}) == 1
+ instance_ok = bool(s.instance_exact)
+ ok = all_success and deterministic and instance_ok
+ out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
+ "instance_ok": int(instance_ok), "n_actions": int(len(acts)), "sim_steps": int(outs[0]["steps"]),
+ "task_failure": int(bool(outs[0]["reason"]) and not outs[0]["success"]),
+ "replay_wall_s": round(time.time() - t0, 1), "grader_error": 0, "video_rendered": 0, **cost}
+ if not a.no_video: # human-viewable replay (never affects the verdict)
+ try:
+ n = int(outs[0]["replayed_rows"])
+ s.render_video(acts[:n], os.path.join(LOG_DIR, "replay.mp4"), cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ import imageio.v2 as imageio
+ imageio.imwrite(os.path.join(LOG_DIR, "replay.last.png"), s.render_frame(s.default_camera(), (480, 640)))
+ out["video_rendered"] = int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4")))
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(ok, out)
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(False, {"success": 0, "grader_error": 1, **cost})
+ finally:
+ if s is not None:
+ s.close()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tasks/dexjoco-pick-bucket-i00-privileged/tests/instance.npz b/tasks/dexjoco-pick-bucket-i00-privileged/tests/instance.npz
new file mode 100644
index 0000000000..473da0693d
Binary files /dev/null and b/tasks/dexjoco-pick-bucket-i00-privileged/tests/instance.npz differ
diff --git a/tasks/dexjoco-pick-bucket-i00-privileged/tests/rcb_dexjoco.py b/tasks/dexjoco-pick-bucket-i00-privileged/tests/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-privileged/tests/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-pick-bucket-i00-privileged/tests/test.sh b/tasks/dexjoco-pick-bucket-i00-privileged/tests/test.sh
new file mode 100755
index 0000000000..293121f256
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-privileged/tests/test.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in a fresh process.
+# 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/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)
+mkdir -p /logs/verifier
+python /tests/grade.py --family pick_bucket --instance /tests/instance.npz --traj /app/output/trajectory.npz --repeat 2 \
+ 2> /logs/verifier/grade.log
diff --git a/tasks/dexjoco-pick-bucket-i00-standard/README.md b/tasks/dexjoco-pick-bucket-i00-standard/README.md
new file mode 100644
index 0000000000..29b5bdf768
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-standard/README.md
@@ -0,0 +1,45 @@
+# dexjoco-pick-bucket-i00-standard
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | standard (`eai-standard/2.2`) |
+| Twin | `dexjoco-pick-bucket-i00-privileged` |
+| Simulator / robot | `dexjoco` / `franka-allegro` |
+| Family / instance | `pick_bucket` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `pick_bucket` (a Franka Panda arm with a 16-DoF Allegro hand) on the same frozen instance as `dexjoco-pick-bucket-i00-privileged`: Put the boxed food into the bucket, then lift the bucket. Success: the boxed food's centre is inside the bounding box of the bucket's eight reference corners AND the bucket's bottom is at least 0.15 m above where it started, at the same control step.
+Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with the robot's own
+sensors, calibrated cameras (RGB, optional depth) and the robot's kinematics.
+
+## Difficulty
+Same instance and success check as `dexjoco-pick-bucket-i00-privileged`. In standard mode the agent loses resets, the
+simulator and the object poses: it sees camera images and proprioception, acts in chunks of tcp-target + hand-joint rows
+(or joint targets), and gets one episode, so it has to close the loop on what the cameras show and recover from its own
+mistakes without starting over.
+
+## Reference solution
+`solution/oracle_stream.py` streams the privileged reference's rows (`solution/oracle_trajectory.npz`, 580 rows, float32-exact)
+through the client as `ee_pose` 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 580 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 580 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `bucket_pick_demo_10_2026-03-10_18-19-00_120725` (DexJoCo-Datasets-Raw); instance sha `1cb042bf6d46ad45` |
+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); action types `ee_pose` and `joint_position`; cameras `front`, `back`, `left`, `right`, `top0`, `handcam_rgb` (640 x 480); `/kinematics` for the arm links, the hand mount and the tcp; crash recovery class `exact` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py`, as its privileged twin.
diff --git a/tasks/dexjoco-pick-bucket-i00-standard/environment/Dockerfile b/tasks/dexjoco-pick-bucket-i00-standard/environment/Dockerfile
new file mode 100644
index 0000000000..a778c94561
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-standard/environment/Dockerfile
@@ -0,0 +1,9 @@
+# Standard mode: the agent container has NO simulator and no DexJoCo 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 /app
diff --git a/tasks/dexjoco-pick-bucket-i00-standard/environment/client-requirements.txt b/tasks/dexjoco-pick-bucket-i00-standard/environment/client-requirements.txt
new file mode 100644
index 0000000000..8aa73a968f
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-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.0
diff --git a/tasks/dexjoco-pick-bucket-i00-standard/environment/docker-compose.yaml b/tasks/dexjoco-pick-bucket-i00-standard/environment/docker-compose.yaml
new file mode 100644
index 0000000000..6c9c5957ba
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-standard/environment/docker-compose.yaml
@@ -0,0 +1,24 @@
+# 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 OSMesa rendering; 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-dexjoco:0.1.2
+ 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_TASK: pick_bucket
+ RCB_INSTANCE: /srv/instance.npz
+ RCB_TOOL: /srv/rcb_dexjoco.py
+ RCB_DATA: /data
+ RCB_WALL_CLOCK_S: "5400"
+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in a few seconds
+ PYTHONPATH: /srv
+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction log
diff --git a/tasks/dexjoco-pick-bucket-i00-standard/environment/rcb1.py b/tasks/dexjoco-pick-bucket-i00-standard/environment/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-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/dexjoco-pick-bucket-i00-standard/environment/rcb_client.py b/tasks/dexjoco-pick-bucket-i00-standard/environment/rcb_client.py
new file mode 100644
index 0000000000..aa25b0e050
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-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/dexjoco-pick-bucket-i00-standard/environment/sim/finalize.sh b/tasks/dexjoco-pick-bucket-i00-standard/environment/sim/finalize.sh
new file mode 100755
index 0000000000..e0cf248720
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-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_dexjoco.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:?}"; TASK="${RCB_TASK:?}"
+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 --task "$TASK" --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --repeat 1 \
+ --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"))
+PY
diff --git a/tasks/dexjoco-pick-bucket-i00-standard/environment/sim/instance.npz b/tasks/dexjoco-pick-bucket-i00-standard/environment/sim/instance.npz
new file mode 100644
index 0000000000..473da0693d
Binary files /dev/null and b/tasks/dexjoco-pick-bucket-i00-standard/environment/sim/instance.npz differ
diff --git a/tasks/dexjoco-pick-bucket-i00-standard/environment/sim/rcb1.py b/tasks/dexjoco-pick-bucket-i00-standard/environment/sim/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-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/dexjoco-pick-bucket-i00-standard/environment/sim/rcb_dexjoco.py b/tasks/dexjoco-pick-bucket-i00-standard/environment/sim/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-standard/environment/sim/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-pick-bucket-i00-standard/environment/sim/rcb_limited.py b/tasks/dexjoco-pick-bucket-i00-standard/environment/sim/rcb_limited.py
new file mode 100644
index 0000000000..1ce1171787
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-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/dexjoco-pick-bucket-i00-standard/environment/sim/run.sh b/tasks/dexjoco-pick-bucket-i00-standard/environment/sim/run.sh
new file mode 100755
index 0000000000..49d4d045d4
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-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; done
diff --git a/tasks/dexjoco-pick-bucket-i00-standard/environment/sim/server.py b/tasks/dexjoco-pick-bucket-i00-standard/environment/sim/server.py
new file mode 100644
index 0000000000..ca5b61fc5c
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-standard/environment/sim/server.py
@@ -0,0 +1,625 @@
+"""eai-standard/2.2 sim service for DexJoCo (docs/STANDARD_MODE_2_2.md): the adapter of the shared layer rcb_limited.py;
+the simulator is rcb_dexjoco.Session (DexJoCo on MuJoCo 3.4, CPU physics, OSMesa rendering).
+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to
+/data/episode.jsonl.
+
+The robot is a Franka Panda with a 16-DoF Allegro hand, or two of them side by side (right arm first). One control step
+= 1/50 s (10 physics substeps of 2 ms). Two action types:
+ ee_pose DexJoCo's own row, per arm: the tcp target pose (xyz m, quaternion wxyz, world frame) that its
+ operational-space controller tracks + 16 Allegro joint targets (rad);
+ joint_position per arm: 7 arm joint targets + 16 Allegro joint targets; the arm's targets are turned into a tcp target
+ by forward kinematics (the controller tracks the tcp pose, not the joints).
+Either way, the executed (journaled, recorded) row is DexJoCo's own row, so the recorded trajectory replays in the
+privileged tooling unchanged. As in DexJoCo's evaluation the episode ends at the first success or task failure;
+otherwise when the agent's time is over (the collect hook's SIGUSR1).
+
+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 instance 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")
+TASK = os.environ.get("RCB_TASK", "water_plant")
+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.npz"))
+TASK_TEXT_FILE = os.environ.get("RCB_TASK_TEXT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "task_text.txt"))
+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "5400"))
+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 = 640, 480
+CTRL_HZ = 50.0
+DT = 1.0 / CTRL_HZ
+SUBSTEPS = 10
+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"] = "" # the sidecar's Session is not the agent's interaction log
+import rcb_dexjoco as M # noqa: E402
+import mujoco # noqa: E402
+
+M.SESSION_LOG = ""
+BIM = TASK.startswith("bimanual_")
+ADIM = 46 if BIM else 23
+EP = L.Episode(DATA, dim=ADIM, resume="exact")
+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()
+S = M.Session(TASK, instance=INSTANCE, image_size=(CAM_H, CAM_W))
+MD, D = S.model, S.data
+ARMS = S.arms()
+SFX = {a: (f"_{a}" if BIM else "") for a in ARMS}
+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz
+
+# ------------------------------------------------------------------------------------------------- the robot
+ARM_JOINTS = {a: [f"joint{i}{SFX[a]}" for i in range(1, 8)] for a in ARMS}
+HAND_CTRL = {a: np.asarray(S._hand_ctrl_ids(a)) for a in ARMS}
+HAND_JOINTS = {a: [MD.joint(int(MD.actuator_trnid[i, 0])).name for i in HAND_CTRL[a]] for a in ARMS} # action order
+ARM_CTRL = {a: [MD.actuator(f"actuator{i}{SFX[a]}").id for i in range(1, 8)] for a in ARMS}
+JOINTS = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]] # kinematics q = proprio joint_pos columns
+QADR = np.array([MD.jnt_qposadr[MD.joint(j).id] for j in JOINTS])
+VADR = np.array([MD.jnt_dofadr[MD.joint(j).id] for j in JOINTS])
+EFF_ACT = np.array([i for a in ARMS for i in list(ARM_CTRL[a]) + list(HAND_CTRL[a])])
+TCP_SITE = {a: MD.site(f"attachment_site{SFX[a]}").id for a in ARMS}
+TCP = {a: f"tcp{SFX[a]}" for a in ARMS}
+MOUNT_BODY = {a: f"attachment{SFX[a]}" for a in ARMS}
+LINKS = {a: [f"link{i}{SFX[a]}" for i in range(0, 8) if mujoco.mj_name2id(MD, mujoco.mjtObj.mjOBJ_BODY, f"link{i}{SFX[a]}") >= 0]
+ + [MOUNT_BODY[a]] for a in ARMS}
+KIN_LINKS = [n for a in ARMS for n in LINKS[a] + [TCP[a]]]
+JLIM = {j: MD.jnt_range[MD.joint(j).id].astype(float).tolist() for j in JOINTS}
+HLIM = {a: S.hand_limits(a) for a in ARMS} # actuator ctrlrange, action order
+ALIM = {} # joint_position limits (inside the joint ranges)
+for a in ARMS:
+ for j in ARM_JOINTS[a]:
+ ALIM[j] = JLIM[j]
+ for j, (lo, hi) in zip(HAND_JOINTS[a], HLIM[a]):
+ ALIM[j] = [max(float(lo), JLIM[j][0]), min(float(hi), JLIM[j][1])]
+POSE = ["x", "y", "z", "qw", "qx", "qy", "qz"]
+EE_LAYOUT = [] # per arm, right first
+for a in ARMS:
+ EE_LAYOUT += [f"{TCP[a]}_target_{k}" for k in POSE] + [f"{j}_target" for j in HAND_JOINTS[a]]
+JP_LAYOUT = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]]
+
+GROUPS = [
+ ("joint_pos", JOINTS, "measured joint positions (rad): per arm (right first) the 7 Panda joints, then the 16 Allegro "
+ "joints in the action's order"),
+ ("joint_vel", [f"{j}_vel" for j in JOINTS], "measured joint velocities (rad/s)"),
+ ("joint_effort", [f"{j}_effort" for j in JOINTS], "actuator efforts (N m): the arm's operational-space torques and the "
+ "hand's position-actuator forces"),
+ ("gripper_opening", [], "none: a 16-DoF Allegro hand, its finger joints are in joint_pos"),
+ ("tcp_pose", [f"{TCP[a]}_{k}" for a in ARMS for k in POSE], "measured tcp pose per arm (x y z m, quaternion wxyz, world)"),
+ ("tcp_target", [f"{TCP[a]}_target_{k}" for a in ARMS for k in POSE], "the tcp target the controller tracks now (the "
+ "ee_pose part of the last executed row)"),
+ ("hand_target", [f"{j}_target" for a in ARMS for j in HAND_JOINTS[a]], "the Allegro joint targets now (rad)"),
+]
+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)
+
+
+def _quat(xmat) -> np.ndarray:
+ q = np.zeros(4)
+ mujoco.mju_mat2Quat(q, np.asarray(xmat, dtype=np.float64).reshape(9))
+ return q
+
+
+# ------------------------------------------------------------------------------------------------- cameras
+CAMS = S.cameras()
+HAND_CAMS = [c for c in CAMS if c.startswith("handcam")]
+DEFAULT_CAMS = [S.default_camera()]
+GL2CV = np.diag([1.0, -1.0, -1.0, 1.0])
+
+
+def _intrinsic(cam: str) -> list:
+ fovy = math.radians(float(MD.cam_fovy[MD.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 _cam2world_gl(cam: str) -> np.ndarray:
+ i = MD.camera(cam).id
+ T = np.eye(4)
+ T[:3, :3] = D.cam_xmat[i].reshape(3, 3) # MuJoCo camera axes: OpenGL (x right, y up, z back)
+ T[:3, 3] = D.cam_xpos[i]
+ return T
+
+
+def _extrinsic(cam: str) -> np.ndarray:
+ return np.linalg.inv(_cam2world_gl(cam) @ GL2CV)[:3, :]
+
+
+def camera_info(cam: str) -> dict:
+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist(),
+ "image_size": [CAM_W, CAM_H]}
+
+
+def _mount(cam: str) -> dict:
+ i = MD.camera(cam).id
+ body = MD.body(int(MD.cam_bodyid[i])).name
+ if int(MD.cam_bodyid[i]) == 0:
+ return {"type": "static", "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist()}
+ T = np.eye(4) # body -> camera (OpenGL axes), then to OpenCV axes
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.cam_quat[i])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.cam_pos[i]
+ return {"type": "link", "parent_link": body, "link_T_cam_cv": (T @ GL2CV).tolist()}
+
+
+def _mounted(cam: str) -> str:
+ if cam.startswith("handcam"):
+ side = "the right" if cam.endswith("_right") else "the left" if cam.endswith("_left") else "the"
+ return f"on {side} hand's mount (moves with the hand)"
+ return {"front": "static, across the table, facing the robot", "back": "static, behind the robot, looking over the table",
+ "left": "static, at the robot's left", "right": "static, at the robot's right",
+ "top0": "static, above the table, looking down"}.get(cam, "static")
+
+
+# ------------------------------------------------------------------------------------------------- kinematics
+KD = mujoco.MjData(MD) # kinematics only: never stepped; the robot's joints are set, everything else stays put
+ARM_QI = {a: [JOINTS.index(j) for j in ARM_JOINTS[a]] for a in ARMS}
+
+
+def _fk(q) -> None:
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR] = np.asarray(q, dtype=np.float64)
+ mujoco.mj_kinematics(MD, KD)
+
+
+def _link_pose(name: str) -> list:
+ for a in ARMS:
+ if name == TCP[a]:
+ s = TCP_SITE[a]
+ return [*KD.site_xpos[s].tolist(), *_quat(KD.site_xmat[s]).tolist()]
+ b = MD.body(name).id
+ return [*KD.xpos[b].tolist(), *KD.xquat[b].tolist()]
+
+
+def tcp_from_arm_joints(a: str, q7) -> np.ndarray:
+ """The tcp pose (xyz + wxyz) of arm `a` with its 7 joints at q7 (the joint_position action's tcp target)."""
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR[ARM_QI[a]]] = q7
+ mujoco.mj_kinematics(MD, KD)
+ s = TCP_SITE[a]
+ return np.concatenate([KD.site_xpos[s], _quat(KD.site_xmat[s])])
+
+
+def do_kinematics(req: dict) -> dict:
+ """World frame. FK: every link of spec kinematics.links for q. IK: per tcp target, damped least squares over that
+ arm's 7 joints (position and orientation), within the joint ranges; the hand joints are taken from the seed."""
+ if req["op"] == "fk":
+ _fk(req["q"])
+ return L.fk_response({n: _link_pose(n) for n in req["links"]}, "world")
+ q = np.array(req["seed"] if req["seed"] is not None else D.qpos[QADR], dtype=np.float64)
+ errors = {}
+ jp, jr = np.zeros((3, MD.nv)), np.zeros((3, MD.nv))
+ for frame, pose in req["targets"].items():
+ a = next(x for x in ARMS if TCP[x] == frame)
+ idx = ARM_QI[a]
+ dofs = VADR[idx]
+ tp, tq = np.asarray(pose[:3]), np.asarray(pose[3:7])
+ lo = np.array([JLIM[JOINTS[i]][0] for i in idx]); hi = np.array([JLIM[JOINTS[i]][1] for i in idx])
+ for _ in range(req["max_iters"]):
+ _fk(q)
+ mujoco.mj_comPos(MD, KD) # the Jacobian needs cdof, which mj_kinematics alone leaves stale
+ s = TCP_SITE[a]
+ ep = tp - KD.site_xpos[s]
+ cq = _quat(KD.site_xmat[s])
+ dq = np.zeros(4); neg = np.zeros(4); er = np.zeros(3)
+ mujoco.mju_negQuat(neg, cq); mujoco.mju_mulQuat(dq, tq, neg); mujoco.mju_quat2Vel(er, dq, 1.0)
+ if np.linalg.norm(ep) < req["tol_pos_m"] and np.linalg.norm(er) < req["tol_rot_rad"]:
+ break
+ mujoco.mj_jacSite(MD, KD, jp, jr, s)
+ J = np.vstack([jp[:, dofs], jr[:, dofs]])
+ err = np.concatenate([ep, er])
+ step = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), err)
+ q[idx] = np.clip(q[idx] + step, lo, hi)
+ _fk(q)
+ s = TCP_SITE[a]
+ errors[frame] = (float(np.linalg.norm(tp - KD.site_xpos[s])), L.quat_angle(_quat(KD.site_xmat[s]), tq / np.linalg.norm(tq)))
+ ok = all(e[0] <= req["tol_pos_m"] and e[1] <= req["tol_rot_rad"] for e in errors.values())
+ return L.ik_response(q, ok, errors, "world", note="the tcp (attachment_site) of each arm; the hand joints are the seed's")
+
+
+# ------------------------------------------------------------------------------------------------- spec
+def _joint_spec(a: str) -> list:
+ out = []
+ for j, ai in zip(ARM_JOINTS[a], ARM_CTRL[a]):
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_ctrlrange[ai][1]), "group": f"{a}_arm"})
+ for j, ai in zip(HAND_JOINTS[a], HAND_CTRL[a]):
+ fl = bool(MD.actuator_forcelimited[ai]) and float(MD.actuator_forcerange[ai][1]) > 0
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_forcerange[ai][1]) if fl else None, "group": f"{a}_hand"})
+ return out
+
+
+def _tcp_spec(a: str) -> dict:
+ s = TCP_SITE[a]
+ T = np.eye(4)
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.site_quat[s])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.site_pos[s]
+ return {"parent_link": MD.body(int(MD.site_bodyid[s])).name, "link_T_frame": T.tolist(),
+ "definition": "DexJoCo's attachment_site: the flange where the Allegro hand is mounted, the point its "
+ "operational-space controller drives to the ee_pose target (not the fingertips)"}
+
+
+def _base(a: str) -> list:
+ b = D.body(f"link0{SFX[a]}")
+ return [*np.round(b.xpos, 6).tolist(), *np.round(b.xquat, 6).tolist()]
+
+
+GAINS = {}
+for _a in ARMS:
+ for _j, _ai in zip(HAND_JOINTS[_a], HAND_CTRL[_a]):
+ GAINS[_j] = {"stiffness": float(MD.actuator_gainprm[_ai][0]), "damping": float(MD.dof_damping[MD.jnt_dofadr[MD.joint(_j).id]])}
+ROBOT_NAME = "franka-allegro-bimanual" if BIM else "franka-allegro"
+try:
+ TASK_TEXT = open(TASK_TEXT_FILE).read().strip()
+except OSError:
+ TASK_TEXT = f"DexJoCo {TASK}"
+SPEC = {
+ "protocol": L.PROTOCOL,
+ "protocol_compat": list(L.COMPAT),
+ "simulator": "DexJoCo @ 8d23b0f on MuJoCo 3.4.0 (CPU physics, OSMesa rendering)",
+ "robot": ROBOT_NAME,
+ "task_text": TASK_TEXT,
+ "control_hz": CTRL_HZ,
+ "physics_substeps": SUBSTEPS,
+ "physics_hz": CTRL_HZ * SUBSTEPS,
+ "max_chunk_s": MAX_CHUNK_S,
+ "max_watch_s": MAX_WATCH_S,
+ "cameras": {c: {"rgb": True, "depth": True, "mounted": _mounted(c), "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),
+ "mount": _mount(c)} for c in CAMS},
+ "default_cameras": DEFAULT_CAMS,
+ "action_types": {
+ "ee_pose": {
+ "dim": ADIM, "layout": EE_LAYOUT,
+ "units": "per arm (right first): tcp target position (m, world frame), tcp target orientation (quaternion wxyz), "
+ "16 Allegro joint targets (rad)",
+ "frame": "world", "quaternion_order": "wxyz", "ee_frames": [TCP[a] for a in ARMS],
+ "hand_limits": {j: ALIM[j] for a in ARMS for j in HAND_JOINTS[a]},
+ "semantics": "DexJoCo's own action row. The arm tracks the tcp target through DexJoCo's operational-space "
+ "controller (it lags a moving target and stops where contact blocks it); the hand joints are "
+ "position-controlled. Rows are `dt` apart (a whole multiple of 1/50 s, at most 0.5 s); between rows "
+ "positions and joints move linearly and orientations by slerp (`linear`) or jump (`hold`); a row's "
+ "own values land exactly on its last control step. Hand targets outside the ranges are clamped by "
+ "the simulator and reported in `clipped`; a zero quaternion is a 400.",
+ },
+ "joint_position": {
+ "dim": ADIM, "layout": JP_LAYOUT, "units": "rad", "limits": {j: ALIM[j] for j in JP_LAYOUT},
+ "semantics": "per arm (right first): 7 Panda joint targets, then the 16 Allegro joint targets. The arm's "
+ "targets are turned into a tcp target by forward kinematics (as POST /kinematics fk) and the arm "
+ "tracks that pose through the same operational-space controller as ee_pose, whose null space "
+ "pulls towards DexJoCo's home posture: the tcp reaches FK(q), the measured joints may differ from q "
+ "in the arm's redundant direction. Rows `dt` apart, `linear` (in joint space) or `hold`; values "
+ "outside the limits are clipped and reported.",
+ },
+ "not_yet": ["joint_delta", "joint_velocity", "ee_delta", "joint_torque"],
+ },
+ "proprio_layout": PROPRIO_LAYOUT,
+ "proprio_groups": PROPRIO_GROUPS,
+ "static": {},
+ "world": {"frame": "DexJoCo's world frame: z up, metres; the robot" + ("s stand" if BIM else " stands")
+ + " at low x and reach" + ("" if BIM else "es") + " towards +x"
+ + (" (right arm at y < 0, left arm at y > 0)" if BIM else ""),
+ "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},
+ "episode": "one episode, no reset: it ends at the first success, at a task failure (see task_text), or when your time is over",
+ "robot_spec": {
+ "name": ROBOT_NAME,
+ "description": ("two Franka Panda arms side by side, each with a 16-DoF Allegro hand (right arm first)" if BIM
+ else "a Franka Panda arm with a 16-DoF Allegro hand"),
+ "base": {"type": "fixed", "pose": _base(ARMS[0]), **({"per_arm": {a: _base(a) for a in ARMS}} if BIM else {}),
+ "note": "pose of the arm's base link (link0), world frame, x y z + quaternion wxyz"},
+ "joints": [j for a in ARMS for j in _joint_spec(a)],
+ "grippers": {},
+ "controller": {"type": "arm: operational-space control of the tcp (torques); hand: joint position actuators",
+ "control_hz": CTRL_HZ, "physics_hz": CTRL_HZ * SUBSTEPS, "gains": GAINS,
+ "note": "arm: DexJoCo's opspace controller drives attachment_site to the tcp target (position gains "
+ "400 N/m, damping ratio 4, gravity compensation, null space towards the home posture), "
+ "torques limited to effort_limit; hand: position actuators (stiffness N m/rad) on joints "
+ "with their own damping (N m s/rad)"},
+ "tcp": {TCP[a]: _tcp_spec(a) for a in ARMS},
+ },
+ "kinematics": {"endpoint": "/kinematics", "joint_names": JOINTS, "frame": "world", "quaternion_order": "wxyz",
+ "links": KIN_LINKS, "tcp_frames": [TCP[a] for a in ARMS], "ee_frames": [TCP[a] for a in ARMS],
+ "ik_targets": [TCP[a] for a in ARMS], "ik": {"tol_pos_m": 0.001, "tol_rot_rad": 0.01, "max_iters": 300},
+ "note": "the arm links, the hand mount (the hand cameras' parent) and the tcp, world frame; ik solves "
+ "each tcp target over that arm's 7 joints"},
+ "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()
+
+
+# ------------------------------------------------------------------------------------------------- state and frames
+def ctrl_steps() -> int:
+ return int(S.steps)
+
+
+def proprio_row() -> np.ndarray:
+ tcp, tgt, hand = [], [], []
+ for a in ARMS:
+ s = TCP_SITE[a]
+ tcp += [D.site_xpos[s], _quat(D.site_xmat[s])]
+ t = S._arm_target(a)
+ tgt.append(t[:7]); hand.append(t[7:23])
+ return np.concatenate([D.qpos[QADR], D.qvel[VADR], D.actuator_force[EFF_ACT], *tcp, *tgt, *hand]).astype(np.float32)
+
+
+def grab(cams, want_depth: bool):
+ rgb, dep = {}, {}
+ for c in cams:
+ rgb[c] = S.render_frame(c, (CAM_H, CAM_W))
+ if want_depth:
+ r = S._renderer # the one renderer (a second OSMesa context reads back garbage)
+ r.enable_depth_rendering()
+ try:
+ r.update_scene(D, camera=c)
+ dep[c] = r.render().astype(np.float32).copy()
+ finally:
+ r.disable_depth_rendering()
+ return rgb, dep
+
+
+def extrinsics(cams) -> dict:
+ return {c: _extrinsic(c) for c in cams}
+
+
+def summary() -> dict:
+ n = int(E.get("episode_control_steps") or ctrl_steps())
+ 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"],
+ "task": TASK, "protocol": L.PROTOCOL, "n_actions": len(ROWS), "task_failure": int(str(E["reason"] or "").startswith("failure")),
+ **EP.final_fields()}
+
+
+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 finish(reason: str) -> None:
+ """The episode is over: record the live verdict and dump the trajectory 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()
+ E["success"] = bool(S.success)
+ 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()
+ S.save_trajectory(np.asarray(ROWS, dtype=np.float64).reshape(-1, ADIM), os.path.join(DATA, "trajectory.npz"),
+ {"source": "standard-mode episode", "reason": E["reason"]})
+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})
+ write_final()
+
+
+def ctrl_step(a, rec) -> bool:
+ """One executed control step (DexJoCo's own row), journaled. True when the call must stop here."""
+ a = np.asarray(a, dtype=np.float64)
+ running = S.step(a)
+ ROWS.append(a.copy())
+ stop = EP.journal(a)
+ rec.tick()
+ if not running:
+ finish(S.reason or "done")
+ 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 DEFAULT_CAMS
+ if not isinstance(cams, list) or any(c not in CAMS for c in cams):
+ raise ValueError(f"unknown cameras {cams}; cameras: {CAMS}")
+ return list(dict.fromkeys(cams))
+
+
+def meta_common(cams) -> dict:
+ n = ctrl_steps()
+ return {"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}}
+
+
+def _native_from_ee(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ """ee_pose rows are executed as sent (the recorded row is what the agent commanded); hand targets outside the
+ actuator ranges are clamped by MuJoCo itself (ctrllimited) and only reported."""
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ if float(np.linalg.norm(row[o + 3:o + 7])) < 1e-6:
+ raise ValueError(f"row {ri}: the {a} tcp quaternion has zero norm")
+ for j in range(16):
+ lo, hi = HLIM[a][j]
+ v = row[o + 7 + j]
+ if v < lo or v > hi:
+ clipped.append({"row": ri, "index": int(o + 7 + j), "reason": f"{EE_LAYOUT[o + 7 + j]} outside [{lo:.3f}, {hi:.3f}]: clamped by the simulator"})
+ return row
+
+
+def _clip_joints(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ lo = np.array([ALIM[j][0] for j in JP_LAYOUT]); hi = np.array([ALIM[j][1] for j in JP_LAYOUT])
+ out = np.clip(row, lo, hi)
+ for j in np.flatnonzero(out != row)[:20]:
+ clipped.append({"row": ri, "index": int(j), "reason": f"{JP_LAYOUT[j]} limit [{lo[j]:g}, {hi[j]:g}]"})
+ return out
+
+
+def _native_from_joints(q: np.ndarray) -> np.ndarray:
+ out = []
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ out += [tcp_from_arm_joints(a, q[o:o + 7]), q[o + 7:o + 23]]
+ return np.concatenate(out)
+
+
+def _check_chunk(typ: str, A: np.ndarray, dt: float, interp: str, video: str) -> int:
+ k = dt / DT
+ if A.ndim != 2 or A.shape[1] != ADIM:
+ raise ValueError(f"{typ} actions must be (T, {ADIM}), got {list(A.shape)}")
+ if A.shape[0] == 0:
+ raise ValueError("no rows")
+ 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")
+ return int(round(k))
+
+
+def do_submit(meta: dict, A: np.ndarray):
+ typ = meta.get("type")
+ if typ not in ("ee_pose", "joint_position"):
+ raise ValueError(f"type must be ee_pose or joint_position (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)
+ n = _check_chunk(typ, A, dt, interp, video)
+ clipped: list = []
+ if typ == "ee_pose":
+ A = np.stack([_native_from_ee(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ else:
+ A = np.stack([_clip_joints(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ rec = recorder(cams, fps, meta)
+ E["calls"] += 1
+ step0, before = E["step"], ctrl_steps()
+ rec.tick(force=True)
+ if typ == "ee_pose":
+ prev = np.asarray(S.hold_action(), dtype=np.float64)
+ else:
+ prev = np.concatenate([np.concatenate([D.qpos[QADR[ARM_QI[a]]], S._arm_target(a)[7:23]]) for a in ARMS])
+ for row in A:
+ E["step"] += 1
+ stop = False
+ for s in range(1, n + 1):
+ if interp == "hold" or s == n:
+ target = row # a row's own values land exactly on its last control step
+ else:
+ target = prev + (row - prev) * (s / n)
+ if typ == "ee_pose":
+ for k in range(len(ARMS)):
+ o = 23 * k
+ target[o + 3:o + 7] = M.quat_slerp(prev[o + 3:o + 7], row[o + 3:o + 7], s / n)
+ native = target if typ == "ee_pose" else _native_from_joints(target)
+ if ctrl_step(native, rec):
+ stop = True
+ break
+ prev = row
+ 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"], "type": typ, "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 = np.asarray(S.hold_action(), dtype=np.float64)
+ 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={"task": TASK, "instance_sha": S.instance_sha, "instance_ok": bool(S.instance_exact), "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} DexJoCo sim ready ({TASK}; 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/dexjoco-pick-bucket-i00-standard/environment/sim/task_text.txt b/tasks/dexjoco-pick-bucket-i00-standard/environment/sim/task_text.txt
new file mode 100644
index 0000000000..1b40e985e1
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-standard/environment/sim/task_text.txt
@@ -0,0 +1,3 @@
+Put the boxed food into the bucket, then lift the bucket. Success: the boxed food's centre is inside the bounding box of the bucket's eight reference corners AND the bucket's bottom is at least 0.15 m above where it started, at the same control step.
+
+The bucket stands on the table with a hinged handle over it; the boxed food lies next to it. The handle swings on a hinge (`bucket_handle`).
diff --git a/tasks/dexjoco-pick-bucket-i00-standard/instruction.md b/tasks/dexjoco-pick-bucket-i00-standard/instruction.md
new file mode 100644
index 0000000000..ef1df666df
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-standard/instruction.md
@@ -0,0 +1,68 @@
+# DexJoCo · pick_bucket — STANDARD MODE (robot as a service, eai-standard/2.2)
+
+You control a Franka Panda arm with a 16-DoF Allegro hand, **as if it were real hardware**: the simulator runs in a service you cannot open. You get
+one client and one episode. **Task:** Put the boxed food into the bucket, then lift the bucket. Success: the boxed food's centre is inside the bounding box of the bucket's eight reference corners AND the bucket's bottom is at least 0.15 m above where it started, at the same control step.
+
+The bucket stands on the table with a hinged handle over it; the boxed food lies next to it. The handle swings on a hinge (`bucket_handle`).
+
+## Rules (real-robot rules)
+- **No reset.** The episode starts when the service comes up and ends on success, on a task failure (see the task), when
+ your time is up, or on a simulator error. Knocked-over objects stay knocked over.
+- **No privileged state.** You see what the cameras see (RGB, and depth on request, with each camera's calibration) plus
+ the robot's own proprioception (joints, tcp poses, the current targets). No object poses, no success check:
+ `meta["done"]` / `meta["reason"]` tell you when the episode is over and why.
+- Steps are unlimited; your wall-clock budget (90 minutes) is the limit (`meta["time_left_s"]`). Actions and
+ simulated time are reported as cost. Do not stop before the task is solved.
+- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
+ `/app/output/gen.py` for the record (save it early, update it as you go).
+- **Nothing is put into your context automatically.** Images and videos come back as arrays/bytes in a Python object;
+ what you look at and where you store it is your code's decision.
+
+## Client (`/opt/tools/rcb_client.py`, protocol `eai-standard/2.2`)
+```python
+from rcb_client import Robot
+r = Robot() # connects (waits while the service starts)
+spec = r.spec() # action types, cameras (+ calibration), proprio layout, robot_spec, kinematics, budget
+obs = r.get_obs() # current frames of spec["default_cameras"]: obs.last[cam] -> uint8 (480, 640, 3)
+obs = r.get_obs(cameras=["front", "handcam_rgb"], depth=True) # + obs.last_depth[cam] -> float32 (480, 640) z-depth (m)
+obs.meta["proprio"] # {"layout": [...], "now": [...]}; obs.group("tcp_pose", now=True)
+obs.meta["cameras"] # per camera intrinsic_cv / extrinsic_cv / cam2world_gl for these frames
+obs = r.get_obs(seconds=2.0, video="mp4") # hold the current targets and watch for 2 s (max 30): obs.video[cam] = mp4 bytes
+
+res = r.submit("ee_pose", rows, dt=0.1) # rows: (T, 23) targets dt seconds apart, executed at 50 Hz with interpolation
+res = r.submit("joint_position", q_rows, dt=0.1) # (T, 23) joint targets instead (see below)
+res.meta["done"], res.meta["reason"], res.meta["clipped"], res.meta["control_steps_chunk"]
+res.video["front"]; res.last["front"]; res.proprio # mp4 of the chunk, last frame, float32 (N, P) proprio per frame
+res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, proprio.npy, ...
+r.fk(q); r.ik({"tcp": pose}, seed=q) # kinematics of the robot (stateless: no physics, no time)
+r.status() # calls, control steps, done, reason, elapsed time
+```
+Cameras: `front`, `back`, `left`, `right`, `top0` (static), `handcam_rgb` (on the hand mount; they move,
+so use the calibration that comes with each response; `spec["cameras"][cam]["mount"]` gives the static pose or the mount
+link). Resolution 640x480. Rendering runs on the CPU: ask only for the cameras you need; `video="none"` makes a chunk
+fastest. If a call fails with a connection error the service may have crashed: it resumes the same episode;
+`r.wait_ready()`, then check `r.status()` (`spec["on_service_error"]`).
+
+### Action type `ee_pose` (23) — DexJoCo's own action
+tcp target position (3, metres, world frame), tcp target orientation (4, quaternion wxyz), 16
+Allegro joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+target and stops where contact blocks it); the hand joints are position-controlled. Rows are `dt` apart (a whole multiple
+of 1/50 s, at most 0.5 s); between rows positions and joints move linearly and orientations by slerp
+(`interpolate="linear"`) or jump (`"hold"`); a chunk may cover at most 10 s. Hand targets outside the ranges
+(`spec["action_types"]["ee_pose"]["hand_limits"]`) are clamped by the simulator and listed in `meta["clipped"]`. Build
+the next row from the `tcp_target` and `hand_target` proprio groups to move smoothly.
+
+### Action type `joint_position` (23)
+7 Panda joint targets, then the 16 Allegro joint targets (rad). The service turns the arm's targets
+into a tcp target by forward kinematics and the same controller tracks it: the tcp reaches FK(q), but the measured arm
+joints may differ from q in the arm's redundant direction (the controller's null space pulls towards a home posture).
+Out-of-limit values are clipped and reported.
+
+## Conventions
+- World frame, metres, z up; the robot stands at low x and reaches towards +x; each
+ arm's base pose is in `spec["robot_spec"]["base"]`. No other world coordinates are given (D7: the cameras are
+ calibrated, depth is available). Quaternions are **WXYZ**.
+- The tcp (`tcp`) is the hand's mounting flange (`spec["robot_spec"]["tcp"]`), not the fingertips. Allegro joint
+ order: index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger = spread, 1-3 = flexion
+ from the knuckle out; thumb 12 = opposition).
+- Control runs at 50 Hz (10 physics substeps of 2 ms). There is no step budget: your wall-clock time is the limit.
diff --git a/tasks/dexjoco-pick-bucket-i00-standard/solution/oracle_stream.py b/tasks/dexjoco-pick-bucket-i00-standard/solution/oracle_stream.py
new file mode 100644
index 0000000000..19877300c1
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-standard/solution/oracle_stream.py
@@ -0,0 +1,43 @@
+"""Oracle (standard mode): streams the reference rows (the human demonstration's own actions, one per 1/50 s control step,
+float32-exact) as `ee_pose` 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
+
+A = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle_trajectory.npz"))["actions"].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(A), flush=True)
+t0, i = time.time(), 0
+while i < len(A):
+ chunk = A[i:i + per_chunk]
+ try:
+ res = r.submit("ee_pose", chunk, dt=dt, interpolate="hold", 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/dexjoco-pick-bucket-i00-standard/solution/oracle_trajectory.npz b/tasks/dexjoco-pick-bucket-i00-standard/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..8e5a6a7641
Binary files /dev/null and b/tasks/dexjoco-pick-bucket-i00-standard/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-pick-bucket-i00-standard/solution/solve.sh b/tasks/dexjoco-pick-bucket-i00-standard/solution/solve.sh
new file mode 100755
index 0000000000..1bd55d898f
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-standard/solution/solve.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+# Oracle (standard mode): streams the reference trajectory's rows (solution/oracle_trajectory.npz, one row per control
+# step) as `ee_pose` chunks through the client. Uses no privileged information at run time (only the pre-recorded rows);
+# the service's recorded trajectory is then exactly the privileged reference.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_stream.py /app/output/gen.py
+python /solution/oracle_stream.py
diff --git a/tasks/dexjoco-pick-bucket-i00-standard/task.toml b/tasks/dexjoco-pick-bucket-i00-standard/task.toml
new file mode 100644
index 0000000000..654c37a345
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-standard/task.toml
@@ -0,0 +1,52 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator 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/dexjoco-pick-bucket-i00-standard"
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): DexJoCo pick_bucket (a Franka Panda arm with a 16-DoF Allegro hand) on the same frozen instance as dexjoco-pick-bucket-i00-privileged. Put the boxed food into the bucket, then lift the bucket. The agent only gets a client: calibrated cameras (RGB, optional depth), the robot's joints and tcp poses, tcp-target + hand-joint chunks at 50 Hz, the robot's kinematics; one episode, no reset, no object state; the sim service records the episode, replays it in fresh processes and grades it."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "standard-mode", "robot-as-a-service", "pick_bucket"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro"
+family = "pick_bucket"
+mode = "standard"
+protocol = "eai-standard/2.2"
+oracle = "full"
+expert_time_estimate_hours = 2.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 = 3600
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
diff --git a/tasks/dexjoco-pick-bucket-i00-standard/tests/Dockerfile b/tasks/dexjoco-pick-bucket-i00-standard/tests/Dockerfile
new file mode 100644
index 0000000000..26bc699ebe
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-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.sh
diff --git a/tasks/dexjoco-pick-bucket-i00-standard/tests/grade.py b/tasks/dexjoco-pick-bucket-i00-standard/tests/grade.py
new file mode 100644
index 0000000000..003b933315
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-standard/tests/grade.py
@@ -0,0 +1,60 @@
+"""Standard-mode verifier (DexJoCo): 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 frozen 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"))),
+ "task_failure": int(bool(d.get("task_failure"))),
+ "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),
+ "calls": int(d.get("calls") or 0),
+ "elapsed_s": float(d.get("elapsed_s") or 0),
+ "video_rendered": int(bool(d.get("video"))),
+ # 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 frozen 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/dexjoco-pick-bucket-i00-standard/tests/test.sh b/tasks/dexjoco-pick-bucket-i00-standard/tests/test.sh
new file mode 100755
index 0000000000..bc608aa8b9
--- /dev/null
+++ b/tasks/dexjoco-pick-bucket-i00-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
diff --git a/tasks/dexjoco-pinch-tongs-i00-privileged/README.md b/tasks/dexjoco-pinch-tongs-i00-privileged/README.md
new file mode 100644
index 0000000000..4db1691321
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-privileged/README.md
@@ -0,0 +1,49 @@
+# dexjoco-pinch-tongs-i00-privileged
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | privileged |
+| Twin | `dexjoco-pinch-tongs-i00-standard` |
+| Simulator / robot | `dexjoco` / `franka-allegro` |
+| Family / instance | `pinch_tongs` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `pinch_tongs` (a Franka Panda arm with a 16-DoF Allegro hand): Pick up the tongs and open and close them three times while holding them up. A pinch counts each time the tongs' hinge goes from open (>= 0.1 rad) to closed (<= -0.07 rad). Success: at least three pinches counted and the tongs at least 0.10 m above the table, held for 30 consecutive control steps.
+Privileged mode: the agent works in the simulator's container with live object poses, unlimited resets and thin motion
+primitives, and hands in one trajectory replayed open-loop from the frozen instance.
+
+## Difficulty
+First-pass rating: medium. Dexterous manipulation with a 16-DoF hand on a 7-DoF arm (23 action values per control step);
+the primitives only move tcp and hand-joint targets, so grasping, pressing and every other skill is the agent's. The
+reference (the human teleoperator's demonstration) takes 375 control steps (7.5 s at 50 Hz).
+
+## Reference solution
+`solution/oracle_trajectory.npz` = the human demonstration's own actions, rounded to float32 (the standard client's
+precision; the rounded rows still succeed) and replayed from the frozen instance until the episode ends in success
+(375 rows). The demonstration is public (DexJoCo-Datasets-Raw on Hugging Face), so agent egress is
+limited to the model APIs.
+
+## Verification
+Open-loop replay of `/app/output/trajectory.npz` from `tests/instance.npz`, twice in a fresh process in the verifier's own
+sandbox (no network); pass iff both episodes end in success, their final-state hashes agree and the rebuilt instance
+matches its recorded hash (`tests/grade.py`); plus `/logs/verifier/replay.mp4`. Oracle: success after 375 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `table_tongs_demo_10_2026-03-12_16-30-04_442884` (DexJoCo-Datasets-Raw), restored with DexJoCo's own state restorer; instance sha `ad2cfca40d427e20` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Tooling notes
+DexJoCo's reset samples object poses from the global RNG and its state restorer edits the MuJoCo model (table height,
+fixed bodies), so `instance.npz` stores the full physics state (`mjSTATE_INTEGRATION`), the mocap targets, the controls,
+every numeric model array a task can change, and the env's Python-side task state. Its per-step camera rendering,
+real-time sleep, episode cap and hanoi's wall-clock auto-reset are disabled in the tooling (`rcb_dexjoco.py`).
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py` from `scripts/dexjoco/instances/pinch_tongs/` (`make_instances.py`).
diff --git a/tasks/dexjoco-pinch-tongs-i00-privileged/environment/Dockerfile b/tasks/dexjoco-pinch-tongs-i00-privileged/environment/Dockerfile
new file mode 100644
index 0000000000..d736fe8a7d
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-privileged/environment/Dockerfile
@@ -0,0 +1,7 @@
+# Base image = DexJoCo on MuJoCo 3.4.0 (images/dexjoco/). Everything task-specific is copied here. CPU only.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY instance.npz /app/instance.npz
+COPY rcb_dexjoco.py /opt/tools/rcb_dexjoco.py
+ENV PYTHONPATH=/opt/tools
+RUN mkdir -p /app/output
+WORKDIR /app
diff --git a/tasks/dexjoco-pinch-tongs-i00-privileged/environment/instance.npz b/tasks/dexjoco-pinch-tongs-i00-privileged/environment/instance.npz
new file mode 100644
index 0000000000..fb46289594
Binary files /dev/null and b/tasks/dexjoco-pinch-tongs-i00-privileged/environment/instance.npz differ
diff --git a/tasks/dexjoco-pinch-tongs-i00-privileged/environment/rcb_dexjoco.py b/tasks/dexjoco-pinch-tongs-i00-privileged/environment/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-privileged/environment/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-pinch-tongs-i00-privileged/instruction.md b/tasks/dexjoco-pinch-tongs-i00-privileged/instruction.md
new file mode 100644
index 0000000000..e08b9d28d0
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-privileged/instruction.md
@@ -0,0 +1,96 @@
+# DexJoCo · pinch_tongs — frozen instance
+
+You control a Franka Panda arm with a 16-DoF Allegro hand (DexJoCo on MuJoCo 3.4) via Python. **Task:** Pick up the tongs and open and close them three times while holding them up. A pinch counts each time the tongs' hinge goes from open (>= 0.1 rad) to closed (<= -0.07 rad). Success: at least three pinches counted and the tongs at least 0.10 m above the table, held for 30 consecutive control steps.
+
+The kitchen tongs lie on the table in front of the robot; their two arms are joined by a hinge (`tongs_hinge`). `s.objects()` gives the live poses of the task objects (`tongs`, `tongs_hinge`, `table_top`). DexJoCo's success code (from
+`/opt/dexjoco/dexjoco/dexjoco/sim/envs/panda_pinch_tongs_env.py`; `step()` ends the episode on success or on a task failure):
+```python
+def _compute_success(self) -> bool:
+ try:
+ tongs_pos = self._data.sensor("tongs_pos").data
+ except Exception:
+ return False
+
+ lifted = tongs_pos[2] >= self._lift_z
+ triggered = lifted and self._pinch_count >= _REQUIRED_PINCHES
+
+ if triggered:
+ if not getattr(self, "_success_started", False):
+ self._success_started = True
+ self._success_counter = 1
+ else:
+ self._success_counter += 1
+ else:
+ self._success_started = False
+ self._success_counter = 0
+
+ # print(f"Triggered: {triggered}")
+ if getattr(self, "_success_counter", 0) >= 30:
+ return True
+
+ return False
+
+def _update_pinch_count(self) -> None:
+ try:
+ joint_pos = float(self._data.sensor("tongs_joint_0_pos").data)
+ except Exception:
+ return
+
+ if joint_pos <= _TONGS_CLOSE_THRESHOLD and self._pinch_in_progress:
+ self._pinch_in_progress = False
+ self._pinch_count += 1
+ elif joint_pos >= _TONGS_OPEN_THRESHOLD and not self._pinch_in_progress:
+ self._pinch_in_progress = True
+
+ # print(f"Pinch count: {self._pinch_count}, Joint pos: {joint_pos:.3f}")
+```
+
+This is a *fixed scene instance*: object poses, the table height and the robot's start pose never change between
+resets. You may reset and retry as many times as you want. Your deliverable is **one replayable trajectory**, not a
+general policy.
+
+## Deliverable
+Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
+open-loop from the same initial state in a fresh process and scored 1 if its episode ends in success, else 0. Also
+leave the script that produced it at `/app/output/gen.py`. You have 90 minutes of wall clock: save a
+first trajectory early, improve it, and do not stop before the task is solved.
+
+## Tooling (already installed; run `python` from any directory)
+```python
+from rcb_dexjoco import Session
+s = Session("pinch_tongs", instance="/app/instance.npz") # ~1 s: builds the env and loads the frozen state
+s.reset() # back to the frozen initial state (as often as you like; an exact snapshot restore)
+s.objects() # live task objects: name -> pos, quat_wxyz (bodies) / pos (sites) / qpos (joints)
+s.state() # DexJoCo's state dict: tcp_pose, gripper_pose (hand joints), INITIAL object poses, table height
+p = s.primitives() # thin wrappers of the low-level action; each has a docstring: help(p["move_ee"])
+p["move_ee"]("right", pos, quat_wxyz) # straight-line + slerp motion of an arm's tcp target, then settle
+p["set_hand"]("right", q16) # interpolate the 16 Allegro joint targets
+p["hold"](10); p["set_targets"](row, steps) # keep every target / send one raw action row
+p["get_ee_pose"]("right"); p["get_ee_target"]("right"); p["get_hand"]("right"); p["get_body_pose"](name)
+s.render_frame("front") # RGB uint8 (480, 640, 3); cameras: ['front', 'back', 'left', 'right', 'top0', 'handcam_rgb']; s.render_grid()
+s.step(action) # one control step (23 values, below) = 1/50 s; returns False once the episode is over
+s.record_start(); ...; actions = s.record_stop() # (T, 23) actions, one row per control step
+s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+s.replay(actions) # resets, replays open-loop until the episode ends, returns status -> self-check
+s.save_trajectory(actions, "/app/output/trajectory.npz")
+s.render_video(actions, "/app/output/check.mp4", cameras=["front"]) # replays from the frozen state into a video
+```
+The primitives are deliberately thin (tcp target moves, hand joint targets, hold): grasping, pressing, striking and
+every other skill are yours to build from them. `s.bodies()` lists every MuJoCo body for `p["get_body_pose"]`.
+
+CLI equivalent of the grader:
+`python /opt/tools/rcb_dexjoco.py replay --task pinch_tongs --instance /app/instance.npz --traj /app/output/trajectory.npz`
+
+## Conventions
+- World frame, metres; z up; the robot stands at low x and reaches towards +x. The table top is at z = 0.970. Arm base (`link0`): link0 [-0.75, 0.0, 0.924]. Quaternions are **WXYZ**.
+- Action (23): tcp target position (3), tcp target orientation (4, wxyz), 16 Allegro
+ joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+ target and stops where contact blocks it); the hand joints are position-controlled. `s.hold_action()` is the no-op.
+ At the start the tcp target is [-0.443, -0.0, 1.517] / [0.0, 1.0, 0.0, 0.0].
+- Allegro joint order: index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger =
+ spread, 1-3 = flexion from the knuckle out; thumb 12 = opposition).
+ Target ranges (rad, same for every finger slot, thumb last): low [-0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, 0.26, -0.1, -0.19, -0.16], high [0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 1.4, 1.16, 1.64, 1.72]; the simulator clamps
+ targets to them.
+- Control runs at 50 Hz (10 physics substeps of 2 ms). DexJoCo's own episode cap and real-time pacing are lifted: there
+ is no step budget, your wall-clock time is the limit (~390 control steps/s here). An episode ends at the
+ first success or task failure; `s.step` then refuses further actions until `s.reset()`.
diff --git a/tasks/dexjoco-pinch-tongs-i00-privileged/solution/gen.py b/tasks/dexjoco-pinch-tongs-i00-privileged/solution/gen.py
new file mode 100644
index 0000000000..0e1f7e3bc7
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-privileged/solution/gen.py
@@ -0,0 +1,4 @@
+# How solution/oracle_trajectory.npz was made (scripts/dexjoco/make_instances.py): the DexJoCo human demonstration's
+# own actions (replay.zarr data/action), rounded to float32, replayed from the frozen instance with Session.replay until
+# the episode ended in success (holding the last row a few steps where the rounded rows ended short of a hold count),
+# truncated there and saved with Session.save_trajectory.
diff --git a/tasks/dexjoco-pinch-tongs-i00-privileged/solution/oracle_trajectory.npz b/tasks/dexjoco-pinch-tongs-i00-privileged/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..8710cc5bde
Binary files /dev/null and b/tasks/dexjoco-pinch-tongs-i00-privileged/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-pinch-tongs-i00-privileged/solution/solve.sh b/tasks/dexjoco-pinch-tongs-i00-privileged/solution/solve.sh
new file mode 100755
index 0000000000..7909c90cb8
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-privileged/solution/solve.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+# Reference solution: the human demonstration's actions (float32), replayed through the task tooling until success.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_trajectory.npz /app/output/trajectory.npz
+cp /solution/gen.py /app/output/gen.py
diff --git a/tasks/dexjoco-pinch-tongs-i00-privileged/task.toml b/tasks/dexjoco-pinch-tongs-i00-privileged/task.toml
new file mode 100644
index 0000000000..b9a67f8657
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-privileged/task.toml
@@ -0,0 +1,37 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator or the instance, not this.
+schema_version = "1.3"
+artifacts = ["/app/output/"]
+
+[task]
+name = "robot-coding-bench/dexjoco-pinch-tongs-i00-privileged"
+description = "DexJoCo pinch_tongs (a Franka Panda arm with a 16-DoF Allegro hand, MuJoCo): produce one replayable trajectory. Pick up the tongs and open and close them three times while holding them up. Frozen scene instance (the initial state of a DexJoCo human demonstration)."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "code-as-policy", "trajectory", "pinch_tongs"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro"
+family = "pinch_tongs"
+mode = "privileged"
+oracle = "full"
+expert_time_estimate_hours = 2.0
+
+[verifier]
+timeout_sec = 1800.0
+environment_mode = "separate" # the verifier runs in its own sandbox (tests/Dockerfile); the agent container is gone by then
+network_mode = "no-network"
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
+
+[verifier.environment]
+build_timeout_sec = 1800.0
diff --git a/tasks/dexjoco-pinch-tongs-i00-privileged/tests/Dockerfile b/tasks/dexjoco-pinch-tongs-i00-privileged/tests/Dockerfile
new file mode 100644
index 0000000000..a2620a4da8
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-privileged/tests/Dockerfile
@@ -0,0 +1,8 @@
+# Separate verifier sandbox (PROTOCOL §2.6): the same simulator image with the verifier's own copies of the tooling and
+# the frozen instance baked in. Nothing the agent did in its container reaches this one: Harbor uploads only the declared
+# artifacts (/app/output/), so a patched success check in the agent container cannot count.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY grade.py instance.npz rcb_dexjoco.py test.sh /tests/
+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
+ENV PYTHONPATH=/tests
+WORKDIR /tests
diff --git a/tasks/dexjoco-pinch-tongs-i00-privileged/tests/grade.py b/tasks/dexjoco-pinch-tongs-i00-privileged/tests/grade.py
new file mode 100644
index 0000000000..ad916e8bb9
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-privileged/tests/grade.py
@@ -0,0 +1,109 @@
+"""Verifier entry point for the privileged DexJoCo tasks: replay /app/output/trajectory.npz from the frozen instance and
+write Harbor rewards.
+
+ python /tests/grade.py --family water_plant --instance /tests/instance.npz --traj /app/output/trajectory.npz
+
+Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only; Harbor rejects strings), a replay video
+/logs/verifier/replay.mp4 (front camera + wrist camera) and replay.last.png. Replays `--repeat` times in this fresh
+process; success requires every replay to end its episode in success (DexJoCo's own rule: the episode ends at the first
+success or task failure) AND all final-state hashes to agree (MuJoCo on the CPU is bit-deterministic), and the frozen
+instance rebuilt here from tests/instance.npz must match its recorded hash.
+"""
+from __future__ import annotations
+import argparse, json, os, sys, time, traceback
+import numpy as np
+
+LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")
+
+
+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 self_reported_cost() -> dict:
+ # From the tooling's append-only log in the agent's container: SELF-REPORTED accounting, never evidence.
+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_records": 0, "agent_replays": 0,
+ "agent_cost_self_reported": 1}
+ try:
+ with open("/app/output/rcb_session_log.jsonl") 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 == "session_end": cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)
+ elif ev == "record": cost["agent_records"] += 1
+ elif ev == "replay": cost["agent_replays"] += 1
+ except Exception: # noqa: BLE001 — one bad line must not sink the verdict
+ continue
+ except Exception: # noqa: BLE001
+ pass
+ return cost
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--family", required=True); ap.add_argument("--instance", required=True)
+ ap.add_argument("--traj", default="/app/output/trajectory.npz"); ap.add_argument("--repeat", type=int, default=2)
+ ap.add_argument("--no-video", action="store_true")
+ a = ap.parse_args()
+ cost = self_reported_cost()
+ os.environ["RCB_SESSION_LOG"] = "" # the verifier's own sessions are not the agent's cost
+ if not os.path.isfile(a.traj):
+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost}); return 0
+ s = None
+ try:
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the verifier's own copy of the tooling
+ import rcb_dexjoco
+ rcb_dexjoco.SESSION_LOG = ""
+ from rcb_dexjoco import Session, MAX_STEPS
+ d = np.load(a.traj, allow_pickle=False)
+ if str(d["task"]) != a.family:
+ write(False, {"success": 0, "wrong_family": 1, "grader_error": 0, **cost}); return 0
+ acts = np.asarray(d["actions"], dtype=np.float64)
+ s = Session(a.family, instance=a.instance)
+ if (acts.ndim != 2 or acts.shape[1] != s.action_dim or acts.shape[0] > MAX_STEPS
+ or not np.all(np.isfinite(acts))):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0,
+ "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0, **cost}); return 0
+ t0 = time.time()
+ outs = []
+ for _ in range(a.repeat):
+ try:
+ outs.append(s.replay(acts))
+ except (ValueError, rcb_dexjoco.PrimitiveError):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0, "n_actions": int(len(acts)), **cost}); return 0
+ all_success = all(o["success"] for o in outs)
+ deterministic = len({o["state_sha"] for o in outs}) == 1
+ instance_ok = bool(s.instance_exact)
+ ok = all_success and deterministic and instance_ok
+ out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
+ "instance_ok": int(instance_ok), "n_actions": int(len(acts)), "sim_steps": int(outs[0]["steps"]),
+ "task_failure": int(bool(outs[0]["reason"]) and not outs[0]["success"]),
+ "replay_wall_s": round(time.time() - t0, 1), "grader_error": 0, "video_rendered": 0, **cost}
+ if not a.no_video: # human-viewable replay (never affects the verdict)
+ try:
+ n = int(outs[0]["replayed_rows"])
+ s.render_video(acts[:n], os.path.join(LOG_DIR, "replay.mp4"), cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ import imageio.v2 as imageio
+ imageio.imwrite(os.path.join(LOG_DIR, "replay.last.png"), s.render_frame(s.default_camera(), (480, 640)))
+ out["video_rendered"] = int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4")))
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(ok, out)
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(False, {"success": 0, "grader_error": 1, **cost})
+ finally:
+ if s is not None:
+ s.close()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tasks/dexjoco-pinch-tongs-i00-privileged/tests/instance.npz b/tasks/dexjoco-pinch-tongs-i00-privileged/tests/instance.npz
new file mode 100644
index 0000000000..fb46289594
Binary files /dev/null and b/tasks/dexjoco-pinch-tongs-i00-privileged/tests/instance.npz differ
diff --git a/tasks/dexjoco-pinch-tongs-i00-privileged/tests/rcb_dexjoco.py b/tasks/dexjoco-pinch-tongs-i00-privileged/tests/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-privileged/tests/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-pinch-tongs-i00-privileged/tests/test.sh b/tasks/dexjoco-pinch-tongs-i00-privileged/tests/test.sh
new file mode 100755
index 0000000000..acc2a289d7
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-privileged/tests/test.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in a fresh process.
+# 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/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)
+mkdir -p /logs/verifier
+python /tests/grade.py --family pinch_tongs --instance /tests/instance.npz --traj /app/output/trajectory.npz --repeat 2 \
+ 2> /logs/verifier/grade.log
diff --git a/tasks/dexjoco-pinch-tongs-i00-standard/README.md b/tasks/dexjoco-pinch-tongs-i00-standard/README.md
new file mode 100644
index 0000000000..a9a1d7adb2
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-standard/README.md
@@ -0,0 +1,45 @@
+# dexjoco-pinch-tongs-i00-standard
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | standard (`eai-standard/2.2`) |
+| Twin | `dexjoco-pinch-tongs-i00-privileged` |
+| Simulator / robot | `dexjoco` / `franka-allegro` |
+| Family / instance | `pinch_tongs` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `pinch_tongs` (a Franka Panda arm with a 16-DoF Allegro hand) on the same frozen instance as `dexjoco-pinch-tongs-i00-privileged`: Pick up the tongs and open and close them three times while holding them up. A pinch counts each time the tongs' hinge goes from open (>= 0.1 rad) to closed (<= -0.07 rad). Success: at least three pinches counted and the tongs at least 0.10 m above the table, held for 30 consecutive control steps.
+Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with the robot's own
+sensors, calibrated cameras (RGB, optional depth) and the robot's kinematics.
+
+## Difficulty
+Same instance and success check as `dexjoco-pinch-tongs-i00-privileged`. In standard mode the agent loses resets, the
+simulator and the object poses: it sees camera images and proprioception, acts in chunks of tcp-target + hand-joint rows
+(or joint targets), and gets one episode, so it has to close the loop on what the cameras show and recover from its own
+mistakes without starting over.
+
+## Reference solution
+`solution/oracle_stream.py` streams the privileged reference's rows (`solution/oracle_trajectory.npz`, 375 rows, float32-exact)
+through the client as `ee_pose` 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 375 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 375 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `table_tongs_demo_10_2026-03-12_16-30-04_442884` (DexJoCo-Datasets-Raw); instance sha `ad2cfca40d427e20` |
+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); action types `ee_pose` and `joint_position`; cameras `front`, `back`, `left`, `right`, `top0`, `handcam_rgb` (640 x 480); `/kinematics` for the arm links, the hand mount and the tcp; crash recovery class `exact` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py`, as its privileged twin.
diff --git a/tasks/dexjoco-pinch-tongs-i00-standard/environment/Dockerfile b/tasks/dexjoco-pinch-tongs-i00-standard/environment/Dockerfile
new file mode 100644
index 0000000000..a778c94561
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-standard/environment/Dockerfile
@@ -0,0 +1,9 @@
+# Standard mode: the agent container has NO simulator and no DexJoCo 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 /app
diff --git a/tasks/dexjoco-pinch-tongs-i00-standard/environment/client-requirements.txt b/tasks/dexjoco-pinch-tongs-i00-standard/environment/client-requirements.txt
new file mode 100644
index 0000000000..8aa73a968f
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-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.0
diff --git a/tasks/dexjoco-pinch-tongs-i00-standard/environment/docker-compose.yaml b/tasks/dexjoco-pinch-tongs-i00-standard/environment/docker-compose.yaml
new file mode 100644
index 0000000000..215818f260
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-standard/environment/docker-compose.yaml
@@ -0,0 +1,24 @@
+# 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 OSMesa rendering; 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-dexjoco:0.1.2
+ 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_TASK: pinch_tongs
+ RCB_INSTANCE: /srv/instance.npz
+ RCB_TOOL: /srv/rcb_dexjoco.py
+ RCB_DATA: /data
+ RCB_WALL_CLOCK_S: "5400"
+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in a few seconds
+ PYTHONPATH: /srv
+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction log
diff --git a/tasks/dexjoco-pinch-tongs-i00-standard/environment/rcb1.py b/tasks/dexjoco-pinch-tongs-i00-standard/environment/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-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/dexjoco-pinch-tongs-i00-standard/environment/rcb_client.py b/tasks/dexjoco-pinch-tongs-i00-standard/environment/rcb_client.py
new file mode 100644
index 0000000000..aa25b0e050
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-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/dexjoco-pinch-tongs-i00-standard/environment/sim/finalize.sh b/tasks/dexjoco-pinch-tongs-i00-standard/environment/sim/finalize.sh
new file mode 100755
index 0000000000..e0cf248720
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-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_dexjoco.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:?}"; TASK="${RCB_TASK:?}"
+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 --task "$TASK" --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --repeat 1 \
+ --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"))
+PY
diff --git a/tasks/dexjoco-pinch-tongs-i00-standard/environment/sim/instance.npz b/tasks/dexjoco-pinch-tongs-i00-standard/environment/sim/instance.npz
new file mode 100644
index 0000000000..fb46289594
Binary files /dev/null and b/tasks/dexjoco-pinch-tongs-i00-standard/environment/sim/instance.npz differ
diff --git a/tasks/dexjoco-pinch-tongs-i00-standard/environment/sim/rcb1.py b/tasks/dexjoco-pinch-tongs-i00-standard/environment/sim/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-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/dexjoco-pinch-tongs-i00-standard/environment/sim/rcb_dexjoco.py b/tasks/dexjoco-pinch-tongs-i00-standard/environment/sim/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-standard/environment/sim/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-pinch-tongs-i00-standard/environment/sim/rcb_limited.py b/tasks/dexjoco-pinch-tongs-i00-standard/environment/sim/rcb_limited.py
new file mode 100644
index 0000000000..1ce1171787
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-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/dexjoco-pinch-tongs-i00-standard/environment/sim/run.sh b/tasks/dexjoco-pinch-tongs-i00-standard/environment/sim/run.sh
new file mode 100755
index 0000000000..49d4d045d4
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-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; done
diff --git a/tasks/dexjoco-pinch-tongs-i00-standard/environment/sim/server.py b/tasks/dexjoco-pinch-tongs-i00-standard/environment/sim/server.py
new file mode 100644
index 0000000000..ca5b61fc5c
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-standard/environment/sim/server.py
@@ -0,0 +1,625 @@
+"""eai-standard/2.2 sim service for DexJoCo (docs/STANDARD_MODE_2_2.md): the adapter of the shared layer rcb_limited.py;
+the simulator is rcb_dexjoco.Session (DexJoCo on MuJoCo 3.4, CPU physics, OSMesa rendering).
+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to
+/data/episode.jsonl.
+
+The robot is a Franka Panda with a 16-DoF Allegro hand, or two of them side by side (right arm first). One control step
+= 1/50 s (10 physics substeps of 2 ms). Two action types:
+ ee_pose DexJoCo's own row, per arm: the tcp target pose (xyz m, quaternion wxyz, world frame) that its
+ operational-space controller tracks + 16 Allegro joint targets (rad);
+ joint_position per arm: 7 arm joint targets + 16 Allegro joint targets; the arm's targets are turned into a tcp target
+ by forward kinematics (the controller tracks the tcp pose, not the joints).
+Either way, the executed (journaled, recorded) row is DexJoCo's own row, so the recorded trajectory replays in the
+privileged tooling unchanged. As in DexJoCo's evaluation the episode ends at the first success or task failure;
+otherwise when the agent's time is over (the collect hook's SIGUSR1).
+
+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 instance 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")
+TASK = os.environ.get("RCB_TASK", "water_plant")
+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.npz"))
+TASK_TEXT_FILE = os.environ.get("RCB_TASK_TEXT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "task_text.txt"))
+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "5400"))
+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 = 640, 480
+CTRL_HZ = 50.0
+DT = 1.0 / CTRL_HZ
+SUBSTEPS = 10
+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"] = "" # the sidecar's Session is not the agent's interaction log
+import rcb_dexjoco as M # noqa: E402
+import mujoco # noqa: E402
+
+M.SESSION_LOG = ""
+BIM = TASK.startswith("bimanual_")
+ADIM = 46 if BIM else 23
+EP = L.Episode(DATA, dim=ADIM, resume="exact")
+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()
+S = M.Session(TASK, instance=INSTANCE, image_size=(CAM_H, CAM_W))
+MD, D = S.model, S.data
+ARMS = S.arms()
+SFX = {a: (f"_{a}" if BIM else "") for a in ARMS}
+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz
+
+# ------------------------------------------------------------------------------------------------- the robot
+ARM_JOINTS = {a: [f"joint{i}{SFX[a]}" for i in range(1, 8)] for a in ARMS}
+HAND_CTRL = {a: np.asarray(S._hand_ctrl_ids(a)) for a in ARMS}
+HAND_JOINTS = {a: [MD.joint(int(MD.actuator_trnid[i, 0])).name for i in HAND_CTRL[a]] for a in ARMS} # action order
+ARM_CTRL = {a: [MD.actuator(f"actuator{i}{SFX[a]}").id for i in range(1, 8)] for a in ARMS}
+JOINTS = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]] # kinematics q = proprio joint_pos columns
+QADR = np.array([MD.jnt_qposadr[MD.joint(j).id] for j in JOINTS])
+VADR = np.array([MD.jnt_dofadr[MD.joint(j).id] for j in JOINTS])
+EFF_ACT = np.array([i for a in ARMS for i in list(ARM_CTRL[a]) + list(HAND_CTRL[a])])
+TCP_SITE = {a: MD.site(f"attachment_site{SFX[a]}").id for a in ARMS}
+TCP = {a: f"tcp{SFX[a]}" for a in ARMS}
+MOUNT_BODY = {a: f"attachment{SFX[a]}" for a in ARMS}
+LINKS = {a: [f"link{i}{SFX[a]}" for i in range(0, 8) if mujoco.mj_name2id(MD, mujoco.mjtObj.mjOBJ_BODY, f"link{i}{SFX[a]}") >= 0]
+ + [MOUNT_BODY[a]] for a in ARMS}
+KIN_LINKS = [n for a in ARMS for n in LINKS[a] + [TCP[a]]]
+JLIM = {j: MD.jnt_range[MD.joint(j).id].astype(float).tolist() for j in JOINTS}
+HLIM = {a: S.hand_limits(a) for a in ARMS} # actuator ctrlrange, action order
+ALIM = {} # joint_position limits (inside the joint ranges)
+for a in ARMS:
+ for j in ARM_JOINTS[a]:
+ ALIM[j] = JLIM[j]
+ for j, (lo, hi) in zip(HAND_JOINTS[a], HLIM[a]):
+ ALIM[j] = [max(float(lo), JLIM[j][0]), min(float(hi), JLIM[j][1])]
+POSE = ["x", "y", "z", "qw", "qx", "qy", "qz"]
+EE_LAYOUT = [] # per arm, right first
+for a in ARMS:
+ EE_LAYOUT += [f"{TCP[a]}_target_{k}" for k in POSE] + [f"{j}_target" for j in HAND_JOINTS[a]]
+JP_LAYOUT = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]]
+
+GROUPS = [
+ ("joint_pos", JOINTS, "measured joint positions (rad): per arm (right first) the 7 Panda joints, then the 16 Allegro "
+ "joints in the action's order"),
+ ("joint_vel", [f"{j}_vel" for j in JOINTS], "measured joint velocities (rad/s)"),
+ ("joint_effort", [f"{j}_effort" for j in JOINTS], "actuator efforts (N m): the arm's operational-space torques and the "
+ "hand's position-actuator forces"),
+ ("gripper_opening", [], "none: a 16-DoF Allegro hand, its finger joints are in joint_pos"),
+ ("tcp_pose", [f"{TCP[a]}_{k}" for a in ARMS for k in POSE], "measured tcp pose per arm (x y z m, quaternion wxyz, world)"),
+ ("tcp_target", [f"{TCP[a]}_target_{k}" for a in ARMS for k in POSE], "the tcp target the controller tracks now (the "
+ "ee_pose part of the last executed row)"),
+ ("hand_target", [f"{j}_target" for a in ARMS for j in HAND_JOINTS[a]], "the Allegro joint targets now (rad)"),
+]
+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)
+
+
+def _quat(xmat) -> np.ndarray:
+ q = np.zeros(4)
+ mujoco.mju_mat2Quat(q, np.asarray(xmat, dtype=np.float64).reshape(9))
+ return q
+
+
+# ------------------------------------------------------------------------------------------------- cameras
+CAMS = S.cameras()
+HAND_CAMS = [c for c in CAMS if c.startswith("handcam")]
+DEFAULT_CAMS = [S.default_camera()]
+GL2CV = np.diag([1.0, -1.0, -1.0, 1.0])
+
+
+def _intrinsic(cam: str) -> list:
+ fovy = math.radians(float(MD.cam_fovy[MD.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 _cam2world_gl(cam: str) -> np.ndarray:
+ i = MD.camera(cam).id
+ T = np.eye(4)
+ T[:3, :3] = D.cam_xmat[i].reshape(3, 3) # MuJoCo camera axes: OpenGL (x right, y up, z back)
+ T[:3, 3] = D.cam_xpos[i]
+ return T
+
+
+def _extrinsic(cam: str) -> np.ndarray:
+ return np.linalg.inv(_cam2world_gl(cam) @ GL2CV)[:3, :]
+
+
+def camera_info(cam: str) -> dict:
+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist(),
+ "image_size": [CAM_W, CAM_H]}
+
+
+def _mount(cam: str) -> dict:
+ i = MD.camera(cam).id
+ body = MD.body(int(MD.cam_bodyid[i])).name
+ if int(MD.cam_bodyid[i]) == 0:
+ return {"type": "static", "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist()}
+ T = np.eye(4) # body -> camera (OpenGL axes), then to OpenCV axes
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.cam_quat[i])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.cam_pos[i]
+ return {"type": "link", "parent_link": body, "link_T_cam_cv": (T @ GL2CV).tolist()}
+
+
+def _mounted(cam: str) -> str:
+ if cam.startswith("handcam"):
+ side = "the right" if cam.endswith("_right") else "the left" if cam.endswith("_left") else "the"
+ return f"on {side} hand's mount (moves with the hand)"
+ return {"front": "static, across the table, facing the robot", "back": "static, behind the robot, looking over the table",
+ "left": "static, at the robot's left", "right": "static, at the robot's right",
+ "top0": "static, above the table, looking down"}.get(cam, "static")
+
+
+# ------------------------------------------------------------------------------------------------- kinematics
+KD = mujoco.MjData(MD) # kinematics only: never stepped; the robot's joints are set, everything else stays put
+ARM_QI = {a: [JOINTS.index(j) for j in ARM_JOINTS[a]] for a in ARMS}
+
+
+def _fk(q) -> None:
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR] = np.asarray(q, dtype=np.float64)
+ mujoco.mj_kinematics(MD, KD)
+
+
+def _link_pose(name: str) -> list:
+ for a in ARMS:
+ if name == TCP[a]:
+ s = TCP_SITE[a]
+ return [*KD.site_xpos[s].tolist(), *_quat(KD.site_xmat[s]).tolist()]
+ b = MD.body(name).id
+ return [*KD.xpos[b].tolist(), *KD.xquat[b].tolist()]
+
+
+def tcp_from_arm_joints(a: str, q7) -> np.ndarray:
+ """The tcp pose (xyz + wxyz) of arm `a` with its 7 joints at q7 (the joint_position action's tcp target)."""
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR[ARM_QI[a]]] = q7
+ mujoco.mj_kinematics(MD, KD)
+ s = TCP_SITE[a]
+ return np.concatenate([KD.site_xpos[s], _quat(KD.site_xmat[s])])
+
+
+def do_kinematics(req: dict) -> dict:
+ """World frame. FK: every link of spec kinematics.links for q. IK: per tcp target, damped least squares over that
+ arm's 7 joints (position and orientation), within the joint ranges; the hand joints are taken from the seed."""
+ if req["op"] == "fk":
+ _fk(req["q"])
+ return L.fk_response({n: _link_pose(n) for n in req["links"]}, "world")
+ q = np.array(req["seed"] if req["seed"] is not None else D.qpos[QADR], dtype=np.float64)
+ errors = {}
+ jp, jr = np.zeros((3, MD.nv)), np.zeros((3, MD.nv))
+ for frame, pose in req["targets"].items():
+ a = next(x for x in ARMS if TCP[x] == frame)
+ idx = ARM_QI[a]
+ dofs = VADR[idx]
+ tp, tq = np.asarray(pose[:3]), np.asarray(pose[3:7])
+ lo = np.array([JLIM[JOINTS[i]][0] for i in idx]); hi = np.array([JLIM[JOINTS[i]][1] for i in idx])
+ for _ in range(req["max_iters"]):
+ _fk(q)
+ mujoco.mj_comPos(MD, KD) # the Jacobian needs cdof, which mj_kinematics alone leaves stale
+ s = TCP_SITE[a]
+ ep = tp - KD.site_xpos[s]
+ cq = _quat(KD.site_xmat[s])
+ dq = np.zeros(4); neg = np.zeros(4); er = np.zeros(3)
+ mujoco.mju_negQuat(neg, cq); mujoco.mju_mulQuat(dq, tq, neg); mujoco.mju_quat2Vel(er, dq, 1.0)
+ if np.linalg.norm(ep) < req["tol_pos_m"] and np.linalg.norm(er) < req["tol_rot_rad"]:
+ break
+ mujoco.mj_jacSite(MD, KD, jp, jr, s)
+ J = np.vstack([jp[:, dofs], jr[:, dofs]])
+ err = np.concatenate([ep, er])
+ step = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), err)
+ q[idx] = np.clip(q[idx] + step, lo, hi)
+ _fk(q)
+ s = TCP_SITE[a]
+ errors[frame] = (float(np.linalg.norm(tp - KD.site_xpos[s])), L.quat_angle(_quat(KD.site_xmat[s]), tq / np.linalg.norm(tq)))
+ ok = all(e[0] <= req["tol_pos_m"] and e[1] <= req["tol_rot_rad"] for e in errors.values())
+ return L.ik_response(q, ok, errors, "world", note="the tcp (attachment_site) of each arm; the hand joints are the seed's")
+
+
+# ------------------------------------------------------------------------------------------------- spec
+def _joint_spec(a: str) -> list:
+ out = []
+ for j, ai in zip(ARM_JOINTS[a], ARM_CTRL[a]):
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_ctrlrange[ai][1]), "group": f"{a}_arm"})
+ for j, ai in zip(HAND_JOINTS[a], HAND_CTRL[a]):
+ fl = bool(MD.actuator_forcelimited[ai]) and float(MD.actuator_forcerange[ai][1]) > 0
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_forcerange[ai][1]) if fl else None, "group": f"{a}_hand"})
+ return out
+
+
+def _tcp_spec(a: str) -> dict:
+ s = TCP_SITE[a]
+ T = np.eye(4)
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.site_quat[s])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.site_pos[s]
+ return {"parent_link": MD.body(int(MD.site_bodyid[s])).name, "link_T_frame": T.tolist(),
+ "definition": "DexJoCo's attachment_site: the flange where the Allegro hand is mounted, the point its "
+ "operational-space controller drives to the ee_pose target (not the fingertips)"}
+
+
+def _base(a: str) -> list:
+ b = D.body(f"link0{SFX[a]}")
+ return [*np.round(b.xpos, 6).tolist(), *np.round(b.xquat, 6).tolist()]
+
+
+GAINS = {}
+for _a in ARMS:
+ for _j, _ai in zip(HAND_JOINTS[_a], HAND_CTRL[_a]):
+ GAINS[_j] = {"stiffness": float(MD.actuator_gainprm[_ai][0]), "damping": float(MD.dof_damping[MD.jnt_dofadr[MD.joint(_j).id]])}
+ROBOT_NAME = "franka-allegro-bimanual" if BIM else "franka-allegro"
+try:
+ TASK_TEXT = open(TASK_TEXT_FILE).read().strip()
+except OSError:
+ TASK_TEXT = f"DexJoCo {TASK}"
+SPEC = {
+ "protocol": L.PROTOCOL,
+ "protocol_compat": list(L.COMPAT),
+ "simulator": "DexJoCo @ 8d23b0f on MuJoCo 3.4.0 (CPU physics, OSMesa rendering)",
+ "robot": ROBOT_NAME,
+ "task_text": TASK_TEXT,
+ "control_hz": CTRL_HZ,
+ "physics_substeps": SUBSTEPS,
+ "physics_hz": CTRL_HZ * SUBSTEPS,
+ "max_chunk_s": MAX_CHUNK_S,
+ "max_watch_s": MAX_WATCH_S,
+ "cameras": {c: {"rgb": True, "depth": True, "mounted": _mounted(c), "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),
+ "mount": _mount(c)} for c in CAMS},
+ "default_cameras": DEFAULT_CAMS,
+ "action_types": {
+ "ee_pose": {
+ "dim": ADIM, "layout": EE_LAYOUT,
+ "units": "per arm (right first): tcp target position (m, world frame), tcp target orientation (quaternion wxyz), "
+ "16 Allegro joint targets (rad)",
+ "frame": "world", "quaternion_order": "wxyz", "ee_frames": [TCP[a] for a in ARMS],
+ "hand_limits": {j: ALIM[j] for a in ARMS for j in HAND_JOINTS[a]},
+ "semantics": "DexJoCo's own action row. The arm tracks the tcp target through DexJoCo's operational-space "
+ "controller (it lags a moving target and stops where contact blocks it); the hand joints are "
+ "position-controlled. Rows are `dt` apart (a whole multiple of 1/50 s, at most 0.5 s); between rows "
+ "positions and joints move linearly and orientations by slerp (`linear`) or jump (`hold`); a row's "
+ "own values land exactly on its last control step. Hand targets outside the ranges are clamped by "
+ "the simulator and reported in `clipped`; a zero quaternion is a 400.",
+ },
+ "joint_position": {
+ "dim": ADIM, "layout": JP_LAYOUT, "units": "rad", "limits": {j: ALIM[j] for j in JP_LAYOUT},
+ "semantics": "per arm (right first): 7 Panda joint targets, then the 16 Allegro joint targets. The arm's "
+ "targets are turned into a tcp target by forward kinematics (as POST /kinematics fk) and the arm "
+ "tracks that pose through the same operational-space controller as ee_pose, whose null space "
+ "pulls towards DexJoCo's home posture: the tcp reaches FK(q), the measured joints may differ from q "
+ "in the arm's redundant direction. Rows `dt` apart, `linear` (in joint space) or `hold`; values "
+ "outside the limits are clipped and reported.",
+ },
+ "not_yet": ["joint_delta", "joint_velocity", "ee_delta", "joint_torque"],
+ },
+ "proprio_layout": PROPRIO_LAYOUT,
+ "proprio_groups": PROPRIO_GROUPS,
+ "static": {},
+ "world": {"frame": "DexJoCo's world frame: z up, metres; the robot" + ("s stand" if BIM else " stands")
+ + " at low x and reach" + ("" if BIM else "es") + " towards +x"
+ + (" (right arm at y < 0, left arm at y > 0)" if BIM else ""),
+ "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},
+ "episode": "one episode, no reset: it ends at the first success, at a task failure (see task_text), or when your time is over",
+ "robot_spec": {
+ "name": ROBOT_NAME,
+ "description": ("two Franka Panda arms side by side, each with a 16-DoF Allegro hand (right arm first)" if BIM
+ else "a Franka Panda arm with a 16-DoF Allegro hand"),
+ "base": {"type": "fixed", "pose": _base(ARMS[0]), **({"per_arm": {a: _base(a) for a in ARMS}} if BIM else {}),
+ "note": "pose of the arm's base link (link0), world frame, x y z + quaternion wxyz"},
+ "joints": [j for a in ARMS for j in _joint_spec(a)],
+ "grippers": {},
+ "controller": {"type": "arm: operational-space control of the tcp (torques); hand: joint position actuators",
+ "control_hz": CTRL_HZ, "physics_hz": CTRL_HZ * SUBSTEPS, "gains": GAINS,
+ "note": "arm: DexJoCo's opspace controller drives attachment_site to the tcp target (position gains "
+ "400 N/m, damping ratio 4, gravity compensation, null space towards the home posture), "
+ "torques limited to effort_limit; hand: position actuators (stiffness N m/rad) on joints "
+ "with their own damping (N m s/rad)"},
+ "tcp": {TCP[a]: _tcp_spec(a) for a in ARMS},
+ },
+ "kinematics": {"endpoint": "/kinematics", "joint_names": JOINTS, "frame": "world", "quaternion_order": "wxyz",
+ "links": KIN_LINKS, "tcp_frames": [TCP[a] for a in ARMS], "ee_frames": [TCP[a] for a in ARMS],
+ "ik_targets": [TCP[a] for a in ARMS], "ik": {"tol_pos_m": 0.001, "tol_rot_rad": 0.01, "max_iters": 300},
+ "note": "the arm links, the hand mount (the hand cameras' parent) and the tcp, world frame; ik solves "
+ "each tcp target over that arm's 7 joints"},
+ "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()
+
+
+# ------------------------------------------------------------------------------------------------- state and frames
+def ctrl_steps() -> int:
+ return int(S.steps)
+
+
+def proprio_row() -> np.ndarray:
+ tcp, tgt, hand = [], [], []
+ for a in ARMS:
+ s = TCP_SITE[a]
+ tcp += [D.site_xpos[s], _quat(D.site_xmat[s])]
+ t = S._arm_target(a)
+ tgt.append(t[:7]); hand.append(t[7:23])
+ return np.concatenate([D.qpos[QADR], D.qvel[VADR], D.actuator_force[EFF_ACT], *tcp, *tgt, *hand]).astype(np.float32)
+
+
+def grab(cams, want_depth: bool):
+ rgb, dep = {}, {}
+ for c in cams:
+ rgb[c] = S.render_frame(c, (CAM_H, CAM_W))
+ if want_depth:
+ r = S._renderer # the one renderer (a second OSMesa context reads back garbage)
+ r.enable_depth_rendering()
+ try:
+ r.update_scene(D, camera=c)
+ dep[c] = r.render().astype(np.float32).copy()
+ finally:
+ r.disable_depth_rendering()
+ return rgb, dep
+
+
+def extrinsics(cams) -> dict:
+ return {c: _extrinsic(c) for c in cams}
+
+
+def summary() -> dict:
+ n = int(E.get("episode_control_steps") or ctrl_steps())
+ 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"],
+ "task": TASK, "protocol": L.PROTOCOL, "n_actions": len(ROWS), "task_failure": int(str(E["reason"] or "").startswith("failure")),
+ **EP.final_fields()}
+
+
+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 finish(reason: str) -> None:
+ """The episode is over: record the live verdict and dump the trajectory 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()
+ E["success"] = bool(S.success)
+ 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()
+ S.save_trajectory(np.asarray(ROWS, dtype=np.float64).reshape(-1, ADIM), os.path.join(DATA, "trajectory.npz"),
+ {"source": "standard-mode episode", "reason": E["reason"]})
+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})
+ write_final()
+
+
+def ctrl_step(a, rec) -> bool:
+ """One executed control step (DexJoCo's own row), journaled. True when the call must stop here."""
+ a = np.asarray(a, dtype=np.float64)
+ running = S.step(a)
+ ROWS.append(a.copy())
+ stop = EP.journal(a)
+ rec.tick()
+ if not running:
+ finish(S.reason or "done")
+ 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 DEFAULT_CAMS
+ if not isinstance(cams, list) or any(c not in CAMS for c in cams):
+ raise ValueError(f"unknown cameras {cams}; cameras: {CAMS}")
+ return list(dict.fromkeys(cams))
+
+
+def meta_common(cams) -> dict:
+ n = ctrl_steps()
+ return {"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}}
+
+
+def _native_from_ee(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ """ee_pose rows are executed as sent (the recorded row is what the agent commanded); hand targets outside the
+ actuator ranges are clamped by MuJoCo itself (ctrllimited) and only reported."""
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ if float(np.linalg.norm(row[o + 3:o + 7])) < 1e-6:
+ raise ValueError(f"row {ri}: the {a} tcp quaternion has zero norm")
+ for j in range(16):
+ lo, hi = HLIM[a][j]
+ v = row[o + 7 + j]
+ if v < lo or v > hi:
+ clipped.append({"row": ri, "index": int(o + 7 + j), "reason": f"{EE_LAYOUT[o + 7 + j]} outside [{lo:.3f}, {hi:.3f}]: clamped by the simulator"})
+ return row
+
+
+def _clip_joints(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ lo = np.array([ALIM[j][0] for j in JP_LAYOUT]); hi = np.array([ALIM[j][1] for j in JP_LAYOUT])
+ out = np.clip(row, lo, hi)
+ for j in np.flatnonzero(out != row)[:20]:
+ clipped.append({"row": ri, "index": int(j), "reason": f"{JP_LAYOUT[j]} limit [{lo[j]:g}, {hi[j]:g}]"})
+ return out
+
+
+def _native_from_joints(q: np.ndarray) -> np.ndarray:
+ out = []
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ out += [tcp_from_arm_joints(a, q[o:o + 7]), q[o + 7:o + 23]]
+ return np.concatenate(out)
+
+
+def _check_chunk(typ: str, A: np.ndarray, dt: float, interp: str, video: str) -> int:
+ k = dt / DT
+ if A.ndim != 2 or A.shape[1] != ADIM:
+ raise ValueError(f"{typ} actions must be (T, {ADIM}), got {list(A.shape)}")
+ if A.shape[0] == 0:
+ raise ValueError("no rows")
+ 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")
+ return int(round(k))
+
+
+def do_submit(meta: dict, A: np.ndarray):
+ typ = meta.get("type")
+ if typ not in ("ee_pose", "joint_position"):
+ raise ValueError(f"type must be ee_pose or joint_position (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)
+ n = _check_chunk(typ, A, dt, interp, video)
+ clipped: list = []
+ if typ == "ee_pose":
+ A = np.stack([_native_from_ee(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ else:
+ A = np.stack([_clip_joints(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ rec = recorder(cams, fps, meta)
+ E["calls"] += 1
+ step0, before = E["step"], ctrl_steps()
+ rec.tick(force=True)
+ if typ == "ee_pose":
+ prev = np.asarray(S.hold_action(), dtype=np.float64)
+ else:
+ prev = np.concatenate([np.concatenate([D.qpos[QADR[ARM_QI[a]]], S._arm_target(a)[7:23]]) for a in ARMS])
+ for row in A:
+ E["step"] += 1
+ stop = False
+ for s in range(1, n + 1):
+ if interp == "hold" or s == n:
+ target = row # a row's own values land exactly on its last control step
+ else:
+ target = prev + (row - prev) * (s / n)
+ if typ == "ee_pose":
+ for k in range(len(ARMS)):
+ o = 23 * k
+ target[o + 3:o + 7] = M.quat_slerp(prev[o + 3:o + 7], row[o + 3:o + 7], s / n)
+ native = target if typ == "ee_pose" else _native_from_joints(target)
+ if ctrl_step(native, rec):
+ stop = True
+ break
+ prev = row
+ 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"], "type": typ, "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 = np.asarray(S.hold_action(), dtype=np.float64)
+ 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={"task": TASK, "instance_sha": S.instance_sha, "instance_ok": bool(S.instance_exact), "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} DexJoCo sim ready ({TASK}; 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/dexjoco-pinch-tongs-i00-standard/environment/sim/task_text.txt b/tasks/dexjoco-pinch-tongs-i00-standard/environment/sim/task_text.txt
new file mode 100644
index 0000000000..e9b68e0e38
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-standard/environment/sim/task_text.txt
@@ -0,0 +1,3 @@
+Pick up the tongs and open and close them three times while holding them up. A pinch counts each time the tongs' hinge goes from open (>= 0.1 rad) to closed (<= -0.07 rad). Success: at least three pinches counted and the tongs at least 0.10 m above the table, held for 30 consecutive control steps.
+
+The kitchen tongs lie on the table in front of the robot; their two arms are joined by a hinge (`tongs_hinge`).
diff --git a/tasks/dexjoco-pinch-tongs-i00-standard/instruction.md b/tasks/dexjoco-pinch-tongs-i00-standard/instruction.md
new file mode 100644
index 0000000000..6d9a503d8e
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-standard/instruction.md
@@ -0,0 +1,68 @@
+# DexJoCo · pinch_tongs — STANDARD MODE (robot as a service, eai-standard/2.2)
+
+You control a Franka Panda arm with a 16-DoF Allegro hand, **as if it were real hardware**: the simulator runs in a service you cannot open. You get
+one client and one episode. **Task:** Pick up the tongs and open and close them three times while holding them up. A pinch counts each time the tongs' hinge goes from open (>= 0.1 rad) to closed (<= -0.07 rad). Success: at least three pinches counted and the tongs at least 0.10 m above the table, held for 30 consecutive control steps.
+
+The kitchen tongs lie on the table in front of the robot; their two arms are joined by a hinge (`tongs_hinge`).
+
+## Rules (real-robot rules)
+- **No reset.** The episode starts when the service comes up and ends on success, on a task failure (see the task), when
+ your time is up, or on a simulator error. Knocked-over objects stay knocked over.
+- **No privileged state.** You see what the cameras see (RGB, and depth on request, with each camera's calibration) plus
+ the robot's own proprioception (joints, tcp poses, the current targets). No object poses, no success check:
+ `meta["done"]` / `meta["reason"]` tell you when the episode is over and why.
+- Steps are unlimited; your wall-clock budget (90 minutes) is the limit (`meta["time_left_s"]`). Actions and
+ simulated time are reported as cost. Do not stop before the task is solved.
+- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
+ `/app/output/gen.py` for the record (save it early, update it as you go).
+- **Nothing is put into your context automatically.** Images and videos come back as arrays/bytes in a Python object;
+ what you look at and where you store it is your code's decision.
+
+## Client (`/opt/tools/rcb_client.py`, protocol `eai-standard/2.2`)
+```python
+from rcb_client import Robot
+r = Robot() # connects (waits while the service starts)
+spec = r.spec() # action types, cameras (+ calibration), proprio layout, robot_spec, kinematics, budget
+obs = r.get_obs() # current frames of spec["default_cameras"]: obs.last[cam] -> uint8 (480, 640, 3)
+obs = r.get_obs(cameras=["front", "handcam_rgb"], depth=True) # + obs.last_depth[cam] -> float32 (480, 640) z-depth (m)
+obs.meta["proprio"] # {"layout": [...], "now": [...]}; obs.group("tcp_pose", now=True)
+obs.meta["cameras"] # per camera intrinsic_cv / extrinsic_cv / cam2world_gl for these frames
+obs = r.get_obs(seconds=2.0, video="mp4") # hold the current targets and watch for 2 s (max 30): obs.video[cam] = mp4 bytes
+
+res = r.submit("ee_pose", rows, dt=0.1) # rows: (T, 23) targets dt seconds apart, executed at 50 Hz with interpolation
+res = r.submit("joint_position", q_rows, dt=0.1) # (T, 23) joint targets instead (see below)
+res.meta["done"], res.meta["reason"], res.meta["clipped"], res.meta["control_steps_chunk"]
+res.video["front"]; res.last["front"]; res.proprio # mp4 of the chunk, last frame, float32 (N, P) proprio per frame
+res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, proprio.npy, ...
+r.fk(q); r.ik({"tcp": pose}, seed=q) # kinematics of the robot (stateless: no physics, no time)
+r.status() # calls, control steps, done, reason, elapsed time
+```
+Cameras: `front`, `back`, `left`, `right`, `top0` (static), `handcam_rgb` (on the hand mount; they move,
+so use the calibration that comes with each response; `spec["cameras"][cam]["mount"]` gives the static pose or the mount
+link). Resolution 640x480. Rendering runs on the CPU: ask only for the cameras you need; `video="none"` makes a chunk
+fastest. If a call fails with a connection error the service may have crashed: it resumes the same episode;
+`r.wait_ready()`, then check `r.status()` (`spec["on_service_error"]`).
+
+### Action type `ee_pose` (23) — DexJoCo's own action
+tcp target position (3, metres, world frame), tcp target orientation (4, quaternion wxyz), 16
+Allegro joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+target and stops where contact blocks it); the hand joints are position-controlled. Rows are `dt` apart (a whole multiple
+of 1/50 s, at most 0.5 s); between rows positions and joints move linearly and orientations by slerp
+(`interpolate="linear"`) or jump (`"hold"`); a chunk may cover at most 10 s. Hand targets outside the ranges
+(`spec["action_types"]["ee_pose"]["hand_limits"]`) are clamped by the simulator and listed in `meta["clipped"]`. Build
+the next row from the `tcp_target` and `hand_target` proprio groups to move smoothly.
+
+### Action type `joint_position` (23)
+7 Panda joint targets, then the 16 Allegro joint targets (rad). The service turns the arm's targets
+into a tcp target by forward kinematics and the same controller tracks it: the tcp reaches FK(q), but the measured arm
+joints may differ from q in the arm's redundant direction (the controller's null space pulls towards a home posture).
+Out-of-limit values are clipped and reported.
+
+## Conventions
+- World frame, metres, z up; the robot stands at low x and reaches towards +x; each
+ arm's base pose is in `spec["robot_spec"]["base"]`. No other world coordinates are given (D7: the cameras are
+ calibrated, depth is available). Quaternions are **WXYZ**.
+- The tcp (`tcp`) is the hand's mounting flange (`spec["robot_spec"]["tcp"]`), not the fingertips. Allegro joint
+ order: index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger = spread, 1-3 = flexion
+ from the knuckle out; thumb 12 = opposition).
+- Control runs at 50 Hz (10 physics substeps of 2 ms). There is no step budget: your wall-clock time is the limit.
diff --git a/tasks/dexjoco-pinch-tongs-i00-standard/solution/oracle_stream.py b/tasks/dexjoco-pinch-tongs-i00-standard/solution/oracle_stream.py
new file mode 100644
index 0000000000..19877300c1
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-standard/solution/oracle_stream.py
@@ -0,0 +1,43 @@
+"""Oracle (standard mode): streams the reference rows (the human demonstration's own actions, one per 1/50 s control step,
+float32-exact) as `ee_pose` 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
+
+A = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle_trajectory.npz"))["actions"].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(A), flush=True)
+t0, i = time.time(), 0
+while i < len(A):
+ chunk = A[i:i + per_chunk]
+ try:
+ res = r.submit("ee_pose", chunk, dt=dt, interpolate="hold", 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/dexjoco-pinch-tongs-i00-standard/solution/oracle_trajectory.npz b/tasks/dexjoco-pinch-tongs-i00-standard/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..8710cc5bde
Binary files /dev/null and b/tasks/dexjoco-pinch-tongs-i00-standard/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-pinch-tongs-i00-standard/solution/solve.sh b/tasks/dexjoco-pinch-tongs-i00-standard/solution/solve.sh
new file mode 100755
index 0000000000..1bd55d898f
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-standard/solution/solve.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+# Oracle (standard mode): streams the reference trajectory's rows (solution/oracle_trajectory.npz, one row per control
+# step) as `ee_pose` chunks through the client. Uses no privileged information at run time (only the pre-recorded rows);
+# the service's recorded trajectory is then exactly the privileged reference.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_stream.py /app/output/gen.py
+python /solution/oracle_stream.py
diff --git a/tasks/dexjoco-pinch-tongs-i00-standard/task.toml b/tasks/dexjoco-pinch-tongs-i00-standard/task.toml
new file mode 100644
index 0000000000..75b173eab6
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-standard/task.toml
@@ -0,0 +1,52 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator 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/dexjoco-pinch-tongs-i00-standard"
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): DexJoCo pinch_tongs (a Franka Panda arm with a 16-DoF Allegro hand) on the same frozen instance as dexjoco-pinch-tongs-i00-privileged. Pick up the tongs and open and close them three times while holding them up. The agent only gets a client: calibrated cameras (RGB, optional depth), the robot's joints and tcp poses, tcp-target + hand-joint chunks at 50 Hz, the robot's kinematics; one episode, no reset, no object state; the sim service records the episode, replays it in fresh processes and grades it."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "standard-mode", "robot-as-a-service", "pinch_tongs"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro"
+family = "pinch_tongs"
+mode = "standard"
+protocol = "eai-standard/2.2"
+oracle = "full"
+expert_time_estimate_hours = 2.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 = 3600
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
diff --git a/tasks/dexjoco-pinch-tongs-i00-standard/tests/Dockerfile b/tasks/dexjoco-pinch-tongs-i00-standard/tests/Dockerfile
new file mode 100644
index 0000000000..26bc699ebe
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-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.sh
diff --git a/tasks/dexjoco-pinch-tongs-i00-standard/tests/grade.py b/tasks/dexjoco-pinch-tongs-i00-standard/tests/grade.py
new file mode 100644
index 0000000000..003b933315
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-standard/tests/grade.py
@@ -0,0 +1,60 @@
+"""Standard-mode verifier (DexJoCo): 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 frozen 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"))),
+ "task_failure": int(bool(d.get("task_failure"))),
+ "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),
+ "calls": int(d.get("calls") or 0),
+ "elapsed_s": float(d.get("elapsed_s") or 0),
+ "video_rendered": int(bool(d.get("video"))),
+ # 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 frozen 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/dexjoco-pinch-tongs-i00-standard/tests/test.sh b/tasks/dexjoco-pinch-tongs-i00-standard/tests/test.sh
new file mode 100755
index 0000000000..bc608aa8b9
--- /dev/null
+++ b/tasks/dexjoco-pinch-tongs-i00-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
diff --git a/tasks/dexjoco-water-plant-i00-privileged/README.md b/tasks/dexjoco-water-plant-i00-privileged/README.md
new file mode 100644
index 0000000000..43b314bd7f
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-privileged/README.md
@@ -0,0 +1,49 @@
+# dexjoco-water-plant-i00-privileged
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | privileged |
+| Twin | `dexjoco-water-plant-i00-standard` |
+| Simulator / robot | `dexjoco` / `franka-allegro` |
+| Family / instance | `water_plant` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `water_plant` (a Franka Panda arm with a 16-DoF Allegro hand): Pick up the spray bottle, point its nozzle at the potted plant and squeeze the trigger. Success: the trigger is held pulled (trigger joint > 0.34 rad; it counts as released again below 0.25 rad) while the nozzle reference point is within 0.20 m of the plant horizontally and within +-0.20 m of the plant's height AND the spray points at the plant, all three for 30 consecutive control steps (0.6 s). The spray leaves the spray head horizontally forward: perpendicular to the bottle's long axis, on the side the trigger faces (the bottle's local +z; its long axis, bottom to head, is local +y). It points at the plant when that direction is within 45 degrees of the line from the nozzle to the plant, e.g. with the bottle held upright and its trigger side facing the plant. Pulling the trigger while the nozzle is outside the zone ends the episode as a failure.
+Privileged mode: the agent works in the simulator's container with live object poses, unlimited resets and thin motion
+primitives, and hands in one trajectory replayed open-loop from the frozen instance.
+
+## Difficulty
+First-pass rating: medium. Dexterous manipulation with a 16-DoF hand on a 7-DoF arm (23 action values per control step);
+the primitives only move tcp and hand-joint targets, so grasping, pressing and every other skill is the agent's. The
+reference (the human teleoperator's demonstration) takes 307 control steps (6.1 s at 50 Hz).
+
+## Reference solution
+`solution/oracle_trajectory.npz` = the human demonstration's own actions, rounded to float32 (the standard client's
+precision; the rounded rows still succeed) and replayed from the frozen instance until the episode ends in success
+(307 rows). The demonstration is public (DexJoCo-Datasets-Raw on Hugging Face), so agent egress is
+limited to the model APIs.
+
+## Verification
+Open-loop replay of `/app/output/trajectory.npz` from `tests/instance.npz`, twice in a fresh process in the verifier's own
+sandbox (no network); pass iff both episodes end in success, their final-state hashes agree and the rebuilt instance
+matches its recorded hash (`tests/grade.py`); plus `/logs/verifier/replay.mp4`. Oracle: success after 307 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `water_plant_demo_10_2026-02-05_19-50-27_886249` (DexJoCo-Datasets-Raw), restored with DexJoCo's own state restorer; instance sha `04f14553ced4b0ed` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Tooling notes
+DexJoCo's reset samples object poses from the global RNG and its state restorer edits the MuJoCo model (table height,
+fixed bodies), so `instance.npz` stores the full physics state (`mjSTATE_INTEGRATION`), the mocap targets, the controls,
+every numeric model array a task can change, and the env's Python-side task state. Its per-step camera rendering,
+real-time sleep, episode cap and hanoi's wall-clock auto-reset are disabled in the tooling (`rcb_dexjoco.py`).
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py` from `scripts/dexjoco/instances/water_plant/` (`make_instances.py`).
diff --git a/tasks/dexjoco-water-plant-i00-privileged/environment/Dockerfile b/tasks/dexjoco-water-plant-i00-privileged/environment/Dockerfile
new file mode 100644
index 0000000000..d736fe8a7d
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-privileged/environment/Dockerfile
@@ -0,0 +1,7 @@
+# Base image = DexJoCo on MuJoCo 3.4.0 (images/dexjoco/). Everything task-specific is copied here. CPU only.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY instance.npz /app/instance.npz
+COPY rcb_dexjoco.py /opt/tools/rcb_dexjoco.py
+ENV PYTHONPATH=/opt/tools
+RUN mkdir -p /app/output
+WORKDIR /app
diff --git a/tasks/dexjoco-water-plant-i00-privileged/environment/instance.npz b/tasks/dexjoco-water-plant-i00-privileged/environment/instance.npz
new file mode 100644
index 0000000000..c71cd35bcb
Binary files /dev/null and b/tasks/dexjoco-water-plant-i00-privileged/environment/instance.npz differ
diff --git a/tasks/dexjoco-water-plant-i00-privileged/environment/rcb_dexjoco.py b/tasks/dexjoco-water-plant-i00-privileged/environment/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-privileged/environment/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-water-plant-i00-privileged/instruction.md b/tasks/dexjoco-water-plant-i00-privileged/instruction.md
new file mode 100644
index 0000000000..029972b4d7
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-privileged/instruction.md
@@ -0,0 +1,91 @@
+# DexJoCo · water_plant — frozen instance
+
+You control a Franka Panda arm with a 16-DoF Allegro hand (DexJoCo on MuJoCo 3.4) via Python. **Task:** Pick up the spray bottle, point its nozzle at the potted plant and squeeze the trigger. Success: the trigger is held pulled (trigger joint > 0.34 rad; it counts as released again below 0.25 rad) while the nozzle reference point is within 0.20 m of the plant horizontally and within +-0.20 m of the plant's height AND the spray points at the plant, all three for 30 consecutive control steps (0.6 s). The spray leaves the spray head horizontally forward: perpendicular to the bottle's long axis, on the side the trigger faces (the bottle's local +z; its long axis, bottom to head, is local +y). It points at the plant when that direction is within 45 degrees of the line from the nozzle to the plant, e.g. with the bottle held upright and its trigger side facing the plant. Pulling the trigger while the nozzle is outside the zone ends the episode as a failure.
+
+The spray bottle stands on the table to the robot's right-front, the potted plant further along +y. The trigger is a hinge on the bottle's neck that the index and middle fingers can pull back. `s.objects()` gives the live poses of the task objects (`spray_bottle`, `spray_trigger`, `spray_nozzle`, `plant`, `table_top`). DexJoCo's success code (from
+`/opt/dexjoco/dexjoco/dexjoco/sim/envs/panda_water_plant_env.py`; `step()` ends the episode on success or on a task failure):
+```python
+def _compute_success(self):
+ site_id = self._model.site("ref_point").id
+ p_world = self._data.site_xpos[site_id]
+ obj_world_pos = self._data.body("plant").xpos
+
+ R = 0.2
+ HALF_H = 0.2
+ dx, dy, dz = p_world - obj_world_pos
+ inside = (dx * dx + dy * dy <= R * R) and (-HALF_H <= dz <= HALF_H)
+
+ failed_trigger_outside = (not inside) and self._trigger_pulled
+
+ if inside and self._trigger_pulled:
+ self._success_counter += 1
+ else:
+ self._success_counter = 0
+
+ success = self._success_counter >= _SUCCESS_STEPS_REQUIRED
+ return success, failed_trigger_outside
+```
+
+robot_coding_bench adds the aiming condition to DexJoCo's check: upstream's zone + trigger test alone passes with the bottle lying on the table and spraying away from the plant. The episode ends in success only when `_compute_success`'s zone + trigger condition and the aim below hold together for 30 consecutive steps (`status()['info']` reports `aim_deg` and `rcb_success_count`); DexJoCo's own `succeed` flag alone no longer ends it.
+```python
+WATER_AIM_MAX_DEG = 45.0
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+```
+
+This is a *fixed scene instance*: object poses, the table height and the robot's start pose never change between
+resets. You may reset and retry as many times as you want. Your deliverable is **one replayable trajectory**, not a
+general policy.
+
+## Deliverable
+Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below). It is replayed
+open-loop from the same initial state in a fresh process and scored 1 if its episode ends in success, else 0. Also
+leave the script that produced it at `/app/output/gen.py`. You have 90 minutes of wall clock: save a
+first trajectory early, improve it, and do not stop before the task is solved.
+
+## Tooling (already installed; run `python` from any directory)
+```python
+from rcb_dexjoco import Session
+s = Session("water_plant", instance="/app/instance.npz") # ~1 s: builds the env and loads the frozen state
+s.reset() # back to the frozen initial state (as often as you like; an exact snapshot restore)
+s.objects() # live task objects: name -> pos, quat_wxyz (bodies) / pos (sites) / qpos (joints)
+s.state() # DexJoCo's state dict: tcp_pose, gripper_pose (hand joints), INITIAL object poses, table height
+p = s.primitives() # thin wrappers of the low-level action; each has a docstring: help(p["move_ee"])
+p["move_ee"]("right", pos, quat_wxyz) # straight-line + slerp motion of an arm's tcp target, then settle
+p["set_hand"]("right", q16) # interpolate the 16 Allegro joint targets
+p["hold"](10); p["set_targets"](row, steps) # keep every target / send one raw action row
+p["get_ee_pose"]("right"); p["get_ee_target"]("right"); p["get_hand"]("right"); p["get_body_pose"](name)
+s.render_frame("front") # RGB uint8 (480, 640, 3); cameras: ['front', 'back', 'left', 'right', 'top0', 'handcam_rgb']; s.render_grid()
+s.step(action) # one control step (23 values, below) = 1/50 s; returns False once the episode is over
+s.record_start(); ...; actions = s.record_stop() # (T, 23) actions, one row per control step
+s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+s.replay(actions) # resets, replays open-loop until the episode ends, returns status -> self-check
+s.save_trajectory(actions, "/app/output/trajectory.npz")
+s.render_video(actions, "/app/output/check.mp4", cameras=["front"]) # replays from the frozen state into a video
+```
+The primitives are deliberately thin (tcp target moves, hand joint targets, hold): grasping, pressing, striking and
+every other skill are yours to build from them. `s.bodies()` lists every MuJoCo body for `p["get_body_pose"]`.
+
+CLI equivalent of the grader:
+`python /opt/tools/rcb_dexjoco.py replay --task water_plant --instance /app/instance.npz --traj /app/output/trajectory.npz`
+
+## Conventions
+- World frame, metres; z up; the robot stands at low x and reaches towards +x. The table top is at z = 0.964. Arm base (`link0`): link0 [-0.75, 0.0, 0.924]. Quaternions are **WXYZ**.
+- Action (23): tcp target position (3), tcp target orientation (4, wxyz), 16 Allegro
+ joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+ target and stops where contact blocks it); the hand joints are position-controlled. `s.hold_action()` is the no-op.
+ At the start the tcp target is [-0.443, -0.0, 1.517] / [0.0, -1.0, 0.0, -0.0025].
+- Allegro joint order: index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger =
+ spread, 1-3 = flexion from the knuckle out; thumb 12 = opposition).
+ Target ranges (rad, same for every finger slot, thumb last): low [-0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, -0.47, -0.2, -0.17, -0.23, 0.26, -0.1, -0.19, -0.16], high [0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 0.47, 1.61, 1.71, 1.62, 1.4, 1.16, 1.64, 1.72]; the simulator clamps
+ targets to them.
+- Control runs at 50 Hz (10 physics substeps of 2 ms). DexJoCo's own episode cap and real-time pacing are lifted: there
+ is no step budget, your wall-clock time is the limit (~390 control steps/s here). An episode ends at the
+ first success or task failure; `s.step` then refuses further actions until `s.reset()`.
diff --git a/tasks/dexjoco-water-plant-i00-privileged/solution/gen.py b/tasks/dexjoco-water-plant-i00-privileged/solution/gen.py
new file mode 100644
index 0000000000..0e1f7e3bc7
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-privileged/solution/gen.py
@@ -0,0 +1,4 @@
+# How solution/oracle_trajectory.npz was made (scripts/dexjoco/make_instances.py): the DexJoCo human demonstration's
+# own actions (replay.zarr data/action), rounded to float32, replayed from the frozen instance with Session.replay until
+# the episode ended in success (holding the last row a few steps where the rounded rows ended short of a hold count),
+# truncated there and saved with Session.save_trajectory.
diff --git a/tasks/dexjoco-water-plant-i00-privileged/solution/oracle_trajectory.npz b/tasks/dexjoco-water-plant-i00-privileged/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..f1a414a0c2
Binary files /dev/null and b/tasks/dexjoco-water-plant-i00-privileged/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-water-plant-i00-privileged/solution/solve.sh b/tasks/dexjoco-water-plant-i00-privileged/solution/solve.sh
new file mode 100755
index 0000000000..7909c90cb8
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-privileged/solution/solve.sh
@@ -0,0 +1,6 @@
+#!/bin/bash
+# Reference solution: the human demonstration's actions (float32), replayed through the task tooling until success.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_trajectory.npz /app/output/trajectory.npz
+cp /solution/gen.py /app/output/gen.py
diff --git a/tasks/dexjoco-water-plant-i00-privileged/task.toml b/tasks/dexjoco-water-plant-i00-privileged/task.toml
new file mode 100644
index 0000000000..ac1e852d4f
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-privileged/task.toml
@@ -0,0 +1,37 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator or the instance, not this.
+schema_version = "1.3"
+artifacts = ["/app/output/"]
+
+[task]
+name = "robot-coding-bench/dexjoco-water-plant-i00-privileged"
+description = "DexJoCo water_plant (a Franka Panda arm with a 16-DoF Allegro hand, MuJoCo): produce one replayable trajectory. Pick up the spray bottle, point its nozzle at the potted plant and squeeze the trigger. Frozen scene instance (the initial state of a DexJoCo human demonstration)."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "code-as-policy", "trajectory", "water_plant"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro"
+family = "water_plant"
+mode = "privileged"
+oracle = "full"
+expert_time_estimate_hours = 1.5
+
+[verifier]
+timeout_sec = 1800.0
+environment_mode = "separate" # the verifier runs in its own sandbox (tests/Dockerfile); the agent container is gone by then
+network_mode = "no-network"
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
+
+[verifier.environment]
+build_timeout_sec = 1800.0
diff --git a/tasks/dexjoco-water-plant-i00-privileged/tests/Dockerfile b/tasks/dexjoco-water-plant-i00-privileged/tests/Dockerfile
new file mode 100644
index 0000000000..a2620a4da8
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-privileged/tests/Dockerfile
@@ -0,0 +1,8 @@
+# Separate verifier sandbox (PROTOCOL §2.6): the same simulator image with the verifier's own copies of the tooling and
+# the frozen instance baked in. Nothing the agent did in its container reaches this one: Harbor uploads only the declared
+# artifacts (/app/output/), so a patched success check in the agent container cannot count.
+FROM ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2
+COPY grade.py instance.npz rcb_dexjoco.py test.sh /tests/
+RUN chmod +x /tests/test.sh && mkdir -p /app/output /logs/verifier
+ENV PYTHONPATH=/tests
+WORKDIR /tests
diff --git a/tasks/dexjoco-water-plant-i00-privileged/tests/grade.py b/tasks/dexjoco-water-plant-i00-privileged/tests/grade.py
new file mode 100644
index 0000000000..ad916e8bb9
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-privileged/tests/grade.py
@@ -0,0 +1,109 @@
+"""Verifier entry point for the privileged DexJoCo tasks: replay /app/output/trajectory.npz from the frozen instance and
+write Harbor rewards.
+
+ python /tests/grade.py --family water_plant --instance /tests/instance.npz --traj /app/output/trajectory.npz
+
+Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only; Harbor rejects strings), a replay video
+/logs/verifier/replay.mp4 (front camera + wrist camera) and replay.last.png. Replays `--repeat` times in this fresh
+process; success requires every replay to end its episode in success (DexJoCo's own rule: the episode ends at the first
+success or task failure) AND all final-state hashes to agree (MuJoCo on the CPU is bit-deterministic), and the frozen
+instance rebuilt here from tests/instance.npz must match its recorded hash.
+"""
+from __future__ import annotations
+import argparse, json, os, sys, time, traceback
+import numpy as np
+
+LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")
+
+
+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 self_reported_cost() -> dict:
+ # From the tooling's append-only log in the agent's container: SELF-REPORTED accounting, never evidence.
+ cost = {"agent_sessions": 0, "agent_resets": 0, "agent_sim_steps": 0, "agent_records": 0, "agent_replays": 0,
+ "agent_cost_self_reported": 1}
+ try:
+ with open("/app/output/rcb_session_log.jsonl") 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 == "session_end": cost["agent_sim_steps"] += min(int(float(e.get("sim_steps", 0) or 0)), 10**9)
+ elif ev == "record": cost["agent_records"] += 1
+ elif ev == "replay": cost["agent_replays"] += 1
+ except Exception: # noqa: BLE001 — one bad line must not sink the verdict
+ continue
+ except Exception: # noqa: BLE001
+ pass
+ return cost
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--family", required=True); ap.add_argument("--instance", required=True)
+ ap.add_argument("--traj", default="/app/output/trajectory.npz"); ap.add_argument("--repeat", type=int, default=2)
+ ap.add_argument("--no-video", action="store_true")
+ a = ap.parse_args()
+ cost = self_reported_cost()
+ os.environ["RCB_SESSION_LOG"] = "" # the verifier's own sessions are not the agent's cost
+ if not os.path.isfile(a.traj):
+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0, **cost}); return 0
+ s = None
+ try:
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # the verifier's own copy of the tooling
+ import rcb_dexjoco
+ rcb_dexjoco.SESSION_LOG = ""
+ from rcb_dexjoco import Session, MAX_STEPS
+ d = np.load(a.traj, allow_pickle=False)
+ if str(d["task"]) != a.family:
+ write(False, {"success": 0, "wrong_family": 1, "grader_error": 0, **cost}); return 0
+ acts = np.asarray(d["actions"], dtype=np.float64)
+ s = Session(a.family, instance=a.instance)
+ if (acts.ndim != 2 or acts.shape[1] != s.action_dim or acts.shape[0] > MAX_STEPS
+ or not np.all(np.isfinite(acts))):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0,
+ "n_actions": int(acts.shape[0]) if acts.ndim == 2 else 0, **cost}); return 0
+ t0 = time.time()
+ outs = []
+ for _ in range(a.repeat):
+ try:
+ outs.append(s.replay(acts))
+ except (ValueError, rcb_dexjoco.PrimitiveError):
+ write(False, {"success": 0, "bad_trajectory": 1, "grader_error": 0, "n_actions": int(len(acts)), **cost}); return 0
+ all_success = all(o["success"] for o in outs)
+ deterministic = len({o["state_sha"] for o in outs}) == 1
+ instance_ok = bool(s.instance_exact)
+ ok = all_success and deterministic and instance_ok
+ out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),
+ "instance_ok": int(instance_ok), "n_actions": int(len(acts)), "sim_steps": int(outs[0]["steps"]),
+ "task_failure": int(bool(outs[0]["reason"]) and not outs[0]["success"]),
+ "replay_wall_s": round(time.time() - t0, 1), "grader_error": 0, "video_rendered": 0, **cost}
+ if not a.no_video: # human-viewable replay (never affects the verdict)
+ try:
+ n = int(outs[0]["replayed_rows"])
+ s.render_video(acts[:n], os.path.join(LOG_DIR, "replay.mp4"), cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ import imageio.v2 as imageio
+ imageio.imwrite(os.path.join(LOG_DIR, "replay.last.png"), s.render_frame(s.default_camera(), (480, 640)))
+ out["video_rendered"] = int(os.path.isfile(os.path.join(LOG_DIR, "replay.mp4")))
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(ok, out)
+ except Exception: # noqa: BLE001
+ traceback.print_exc(file=sys.stderr)
+ write(False, {"success": 0, "grader_error": 1, **cost})
+ finally:
+ if s is not None:
+ s.close()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tasks/dexjoco-water-plant-i00-privileged/tests/instance.npz b/tasks/dexjoco-water-plant-i00-privileged/tests/instance.npz
new file mode 100644
index 0000000000..c71cd35bcb
Binary files /dev/null and b/tasks/dexjoco-water-plant-i00-privileged/tests/instance.npz differ
diff --git a/tasks/dexjoco-water-plant-i00-privileged/tests/rcb_dexjoco.py b/tasks/dexjoco-water-plant-i00-privileged/tests/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-privileged/tests/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-water-plant-i00-privileged/tests/test.sh b/tasks/dexjoco-water-plant-i00-privileged/tests/test.sh
new file mode 100755
index 0000000000..eb80b8bea0
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-privileged/tests/test.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in a fresh process.
+# 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/* # verdicts from an earlier run never survive (docs/PROTOCOL.md §2.6)
+mkdir -p /logs/verifier
+python /tests/grade.py --family water_plant --instance /tests/instance.npz --traj /app/output/trajectory.npz --repeat 2 \
+ 2> /logs/verifier/grade.log
diff --git a/tasks/dexjoco-water-plant-i00-standard/README.md b/tasks/dexjoco-water-plant-i00-standard/README.md
new file mode 100644
index 0000000000..c592841891
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-standard/README.md
@@ -0,0 +1,45 @@
+# dexjoco-water-plant-i00-standard
+
+| | |
+|---|---|
+| Benchmark | DexJoCo |
+| Mode | standard (`eai-standard/2.2`) |
+| Twin | `dexjoco-water-plant-i00-privileged` |
+| Simulator / robot | `dexjoco` / `franka-allegro` |
+| Family / instance | `water_plant` |
+| Oracle | `full` |
+| Agent time budget | 5400 s; tokens: protocol default (PROTOCOL §5) |
+| Base image | `ghcr.io/mll-lab-nu/eai-dexjoco:0.1.2` |
+
+## Task
+DexJoCo `water_plant` (a Franka Panda arm with a 16-DoF Allegro hand) on the same frozen instance as `dexjoco-water-plant-i00-privileged`: Pick up the spray bottle, point its nozzle at the potted plant and squeeze the trigger. Success: the trigger is held pulled (trigger joint > 0.34 rad; it counts as released again below 0.25 rad) while the nozzle reference point is within 0.20 m of the plant horizontally and within +-0.20 m of the plant's height AND the spray points at the plant, all three for 30 consecutive control steps (0.6 s). The spray leaves the spray head horizontally forward: perpendicular to the bottle's long axis, on the side the trigger faces (the bottle's local +z; its long axis, bottom to head, is local +y). It points at the plant when that direction is within 45 degrees of the line from the nozzle to the plant, e.g. with the bottle held upright and its trigger side facing the plant. Pulling the trigger while the nozzle is outside the zone ends the episode as a failure.
+Standard mode (eai-standard/2.2): the agent drives the robot through a client in one episode, with the robot's own
+sensors, calibrated cameras (RGB, optional depth) and the robot's kinematics.
+
+## Difficulty
+Same instance and success check as `dexjoco-water-plant-i00-privileged`. In standard mode the agent loses resets, the
+simulator and the object poses: it sees camera images and proprioception, acts in chunks of tcp-target + hand-joint rows
+(or joint targets), and gets one episode, so it has to close the loop on what the cameras show and recover from its own
+mistakes without starting over.
+
+## Reference solution
+`solution/oracle_stream.py` streams the privileged reference's rows (`solution/oracle_trajectory.npz`, 307 rows, float32-exact)
+through the client as `ee_pose` 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 307 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 307 control steps.
+
+## Details
+| | |
+|---|---|
+| Upstream | DexJoCo @ 8d23b0f (brave-eai/dexjoco, MIT) on MuJoCo 3.4.0; CPU physics, OSMesa rendering, no GPU |
+| Instance | the initial state of the human demonstration `water_plant_demo_10_2026-02-05_19-50-27_886249` (DexJoCo-Datasets-Raw); instance sha `04f14553ced4b0ed` |
+| Service | `environment/sim/server.py` (the adapter) on the shared 2.2 layer `rcb_limited.py` (`scripts/eai_standard/`); action types `ee_pose` and `joint_position`; cameras `front`, `back`, `left`, `right`, `top0`, `handcam_rgb` (640 x 480); `/kinematics` for the arm links, the hand mount and the tcp; crash recovery class `exact` |
+| Resources | 4 CPUs, 8 GB, no GPU |
+
+### Provenance
+Generated by `scripts/dexjoco/generate.py`, as its privileged twin.
diff --git a/tasks/dexjoco-water-plant-i00-standard/environment/Dockerfile b/tasks/dexjoco-water-plant-i00-standard/environment/Dockerfile
new file mode 100644
index 0000000000..a778c94561
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-standard/environment/Dockerfile
@@ -0,0 +1,9 @@
+# Standard mode: the agent container has NO simulator and no DexJoCo 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 /app
diff --git a/tasks/dexjoco-water-plant-i00-standard/environment/client-requirements.txt b/tasks/dexjoco-water-plant-i00-standard/environment/client-requirements.txt
new file mode 100644
index 0000000000..8aa73a968f
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-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.0
diff --git a/tasks/dexjoco-water-plant-i00-standard/environment/docker-compose.yaml b/tasks/dexjoco-water-plant-i00-standard/environment/docker-compose.yaml
new file mode 100644
index 0000000000..8b4a8b94ad
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-standard/environment/docker-compose.yaml
@@ -0,0 +1,24 @@
+# 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 OSMesa rendering; 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-dexjoco:0.1.2
+ 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_TASK: water_plant
+ RCB_INSTANCE: /srv/instance.npz
+ RCB_TOOL: /srv/rcb_dexjoco.py
+ RCB_DATA: /data
+ RCB_WALL_CLOCK_S: "5400"
+ RCB_STARTUP_TIMEOUT_S: "300" # the scene builds in a few seconds
+ PYTHONPATH: /srv
+ RCB_SESSION_LOG: "" # the sidecar's own Session must not write the agent-side interaction log
diff --git a/tasks/dexjoco-water-plant-i00-standard/environment/rcb1.py b/tasks/dexjoco-water-plant-i00-standard/environment/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-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/dexjoco-water-plant-i00-standard/environment/rcb_client.py b/tasks/dexjoco-water-plant-i00-standard/environment/rcb_client.py
new file mode 100644
index 0000000000..aa25b0e050
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-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/dexjoco-water-plant-i00-standard/environment/sim/finalize.sh b/tasks/dexjoco-water-plant-i00-standard/environment/sim/finalize.sh
new file mode 100755
index 0000000000..e0cf248720
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-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_dexjoco.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:?}"; TASK="${RCB_TASK:?}"
+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 --task "$TASK" --instance "$INSTANCE" --traj "$DATA/trajectory.npz" --repeat 1 \
+ --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"))
+PY
diff --git a/tasks/dexjoco-water-plant-i00-standard/environment/sim/instance.npz b/tasks/dexjoco-water-plant-i00-standard/environment/sim/instance.npz
new file mode 100644
index 0000000000..c71cd35bcb
Binary files /dev/null and b/tasks/dexjoco-water-plant-i00-standard/environment/sim/instance.npz differ
diff --git a/tasks/dexjoco-water-plant-i00-standard/environment/sim/rcb1.py b/tasks/dexjoco-water-plant-i00-standard/environment/sim/rcb1.py
new file mode 100644
index 0000000000..6938c57e38
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-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/dexjoco-water-plant-i00-standard/environment/sim/rcb_dexjoco.py b/tasks/dexjoco-water-plant-i00-standard/environment/sim/rcb_dexjoco.py
new file mode 100644
index 0000000000..6cdf37e1f1
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-standard/environment/sim/rcb_dexjoco.py
@@ -0,0 +1,796 @@
+"""
+rcb_dexjoco.py — task-local tooling for DexJoCo (brave-eai/dexjoco @ 8d23b0f, MuJoCo 3.4.0; Franka Panda + 16-DoF
+Allegro hand, one or two arms): frozen scene instance / privileged state / thin primitives / action recording /
+fresh-process deterministic replay. Same shape as rcb_robowits.py and rcb_traj.py (LIBERO), so agents and verifiers
+share one mental model.
+
+Concepts
+--------
+instance : one DexJoCo scene = the task's env after reset with the initial object poses and table height of one
+ recorded human demonstration restored (DexJoCo's own state restorer, demo state[0]). DexJoCo's reset
+ samples object poses from the global RNG, so the scene is not rebuilt from a seed: instance.npz stores the
+ full MuJoCo physics state, the mocap targets, the actuator controls and the env's Python-side task state
+ (success counters, trigger flags, ...). Session(instance=...) builds the env, resets it once and loads that
+ snapshot; every episode (reset, replay) starts from it. `state_sha` = sha1 over the physics state.
+trajectory : the (T, A) actions handed to the env, one row per control step (50 Hz control, 10 physics substeps of
+ 2 ms): single-arm A = 23 = [tcp target xyz (m, world), tcp target quat wxyz, 16 Allegro joint targets
+ (rad)]; bimanual A = 46 = [right 23, left 23]. The arm follows the target through DexJoCo's operational-
+ space controller; the hand joints are position-controlled. MuJoCo on the CPU is deterministic: the same
+ rows from the same snapshot give the same final state bit for bit (in-process and across processes).
+episode : as in DexJoCo's own evaluation, an episode ends at the first step where the task reports success, or where
+ it reports a task failure (e.g. water_plant: trigger pulled away from the plant; bimanual_hanoi: an
+ illegal tower). `success` = the episode ended in success. Replay stops at that step.
+budget : there is no step budget: the agent's wall clock is the limit. DexJoCo's 1000-1500-step episode caps and its
+ real-time pacing (a sleep to 30 Hz in every step) are lifted; MAX_STEPS only stops runaway trajectories.
+
+CLI
+---
+ python rcb_dexjoco.py make-instance --task water_plant --demo <demo>/replay.zarr --out instance.npz [--oracle-out oracle.npz]
+ python rcb_dexjoco.py replay --task water_plant --instance instance.npz --traj traj.npz [--repeat 2] [--video replay.mp4] [--out r.json]
+ python rcb_dexjoco.py render --task water_plant --instance instance.npz --traj traj.npz --out replay.mp4
+
+Python (what the agent gets)
+----------------------------
+ from rcb_dexjoco import Session
+ s = Session("water_plant", instance="/app/instance.npz") # ~1 s
+ s.reset() # back to the frozen instance state (unlimited)
+ s.state() # privileged state: tcp_pose, gripper_pose (hand joints), object poses, table height
+ p = s.primitives() # move_ee, set_hand, hold, get_ee_pose, get_hand, get_state, get_body_pose, ...
+ s.render_frame("front") # RGB (H, W, 3) uint8; s.cameras(), s.render_grid(), s.render_video(actions, path)
+ s.record_start(); ...; actions = s.record_stop() # (T, A) actions, one row per control step
+ s.status() # {'success', 'done', 'reason', 'steps', 'resets', 'state_sha', 'info'}
+ s.replay(actions) # resets, replays open-loop, returns status -> self-check before you hand in
+ s.save_trajectory(actions, "/app/output/trajectory.npz")
+"""
+from __future__ import annotations
+
+import os
+os.environ.setdefault("MUJOCO_GL", "osmesa")
+os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
+
+import argparse
+import copy
+import hashlib
+import json
+import sys
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+import numpy as np
+
+MAX_STEPS = 10_000_000 # runaway guard only; the wall clock is the budget
+# Order of the 16 hand values in an action row (and in the measured joints) per arm. DexJoCo's bimanual envs list the
+# LEFT hand's fingers mirrored: ring, middle, index, thumb.
+HAND_ORDER = {"right": ["index_0", "index_1", "index_2", "index_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "ring_0", "ring_1", "ring_2", "ring_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"],
+ "left": ["ring_0", "ring_1", "ring_2", "ring_3", "middle_0", "middle_1", "middle_2", "middle_3",
+ "index_0", "index_1", "index_2", "index_3", "thumb_0", "thumb_1", "thumb_2", "thumb_3"]}
+ACTION_LAYOUT = {23: "[tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16)]",
+ 46: "[right: tcp_xyz(3), tcp_quat_wxyz(4), allegro_joints(16), left: same 23]"}
+_SIMPLE = (bool, int, float, str, type(None), np.integer, np.floating, np.bool_, np.ndarray)
+# MjModel arrays that never change at run time and are large (assets, names): not part of the instance snapshot.
+_MODEL_SKIP = ("mesh_", "tex_", "hfield_", "skin_", "name_", "names", "paths", "text_", "flex_", "bvh_", "oct_")
+
+
+def _model_arrays(model) -> dict[str, np.ndarray]:
+ """Every numeric MjModel array a task can change (DexJoCo's reset and state restorers move fixed bodies, the table
+ and its legs by editing the model, which the physics state does not hold)."""
+ out = {}
+ for k in dir(model):
+ if k.startswith("_") or k.startswith(_MODEL_SKIP):
+ continue
+ try:
+ v = getattr(model, k)
+ except Exception: # noqa: BLE001
+ continue
+ if isinstance(v, np.ndarray) and v.dtype.kind in "fiub" and v.size:
+ out[k] = v
+ return out
+
+
+# Interaction log: every Session (any process) appends one line per session start/reset/record/replay/exit, with the
+# control steps consumed, to RCB_SESSION_LOG (default /app/output/rcb_session_log.jsonl, collected with the artifacts),
+# and to RCB_SESSION_LOG_KEEP (default /logs/agent/rcb_session_log.jsonl when that directory exists; the host's
+# rcb-log-mirror keeps an append-only copy). The verifier reports it as cost and sets RCB_SESSION_LOG="".
+SESSION_LOG = os.environ.get("RCB_SESSION_LOG", "/app/output/rcb_session_log.jsonl")
+SESSION_LOG_KEEP = os.environ.get("RCB_SESSION_LOG_KEEP", "/logs/agent/rcb_session_log.jsonl")
+
+
+def _slog(ev: str, **kw) -> None:
+ if not SESSION_LOG:
+ return
+ line = json.dumps({"ts": time.time(), "pid": os.getpid(), "ev": ev, **kw}) + "\n"
+ for path, must_exist in ((SESSION_LOG, False), (SESSION_LOG_KEEP, True)):
+ if not path or (must_exist and not os.path.isdir(os.path.dirname(path))):
+ continue
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "a") as f:
+ f.write(line)
+ except OSError:
+ pass
+
+
+# Task objects by readable name -> (kind, MuJoCo name). Live poses come from mjData (DexJoCo's state dict carries the
+# objects' INITIAL poses only). kind: body (pos + quat wxyz), site / geom (pos), joint (qpos).
+OBJECTS: dict[str, dict[str, tuple[str, str]]] = {
+ "water_plant": {"spray_bottle": ("body", "link_2"), "spray_trigger": ("joint", "joint_0"),
+ "spray_nozzle": ("site", "ref_point"), "plant": ("body", "plant"), "table_top": ("site", "table_top")},
+ "click_mouse": {"mouse": ("body", "link_3"), "mouse_button": ("joint", "mouse_joint_0"),
+ "mousepad": ("geom", "@_mousepad_geom_id"), "monitor": ("body", "display_link_1"),
+ "table_top": ("site", "table_top")},
+ "hammer_nail": {"hammer": ("body", "hammer_body"), "nail": ("body", "nail"), "nail_top": ("site", "nail_top_site"),
+ "wood_top": ("site", "wood_top"), "table_top": ("site", "table_top")},
+ "pick_bucket": {"bucket": ("body", "bucket"), "bucket_handle": ("joint", "bucket_joint_0"), "boxed_food": ("body", "boxed_food_0"),
+ "table_top": ("site", "table_top")},
+ "pinch_tongs": {"tongs": ("body", "link_1"), "tongs_hinge": ("joint", "joint_0"), "table_top": ("site", "table_top")},
+ "fold_glasses": {"glasses": ("body", "glass"), "temple_0": ("joint", "glass_joint_0"), "temple_1": ("joint", "glass_joint_1"),
+ "case": ("body", "open_box"), "table_top": ("site", "table_top")},
+ "bimanual_microwave_cook": {"hot_dog": ("body", "hot_dog"), "microwave": ("body", "microwave_object"),
+ "door_hinge": ("joint", "microjoint"), "door_handle": ("geom", "door_handle"),
+ "start_button": ("geom", "start_button"), "stop_button": ("geom", "stop_button"),
+ "table_top": ("site", "table_top")},
+ "bimanual_unlock_ipad": {"ipad": ("body", "ipad_body"), "ipad_screen": ("geom", "ipad_screen"), "stand": ("body", "ipad_stand"),
+ "table_top": ("site", "table_top")},
+ "bimanual_assembly": {"peg": ("body", "industreal_round_peg_8mm"), "peg_tip": ("site", "industreal_round_peg_8mm_tip_site"),
+ "tray": ("body", "industreal_tray_insert_round_peg_8mm"),
+ "socket": ("site", "industreal_tray_insert_round_peg_8mm_socket_site"), "table_top": ("site", "table_top")},
+ "bimanual_photograph": {"camera": ("body", "link_19"), "view_point": ("site", "view_direction_site"),
+ "shutter": ("geom", "camera_body_top_cap"), "logo": ("geom", "photograph_logo_disk"),
+ "target_region": ("geom", "photograph_target_region_visual"), "table_top": ("site", "table_top")},
+ "bimanual_hanoi": {"disk_small": ("body", "hanoi_disk_small"), "disk_medium": ("body", "hanoi_disk_medium"),
+ "disk_large": ("body", "hanoi_disk_large"), "post_a": ("site", "hanoi_post_a_site"),
+ "post_b": ("site", "hanoi_post_b_site"), "post_c": ("site", "hanoi_post_c_site")},
+}
+
+
+# Success checks robot_coding_bench tightens on top of DexJoCo's own (DexJoCo's check still has to pass; its task
+# failures still end the episode). water_plant: upstream only asks for the nozzle near the plant while the trigger is
+# pulled, which a bottle lying on the table and spraying away from the plant satisfies (two Opus 5.5 runs did exactly
+# that, spraying 84 and 114 degrees away). We also require the spray to point at the plant.
+WATER_AIM_MAX_DEG = 45.0 # the human demonstration sprays 33 degrees off the nozzle -> plant direction
+
+
+def water_aim_deg(model, data) -> float:
+ """Angle (deg) between the spray direction and the direction from the nozzle reference point to the plant. The spray
+ direction is the bottle body's +z axis, along which DexJoCo draws its spray cone: perpendicular to the bottle's long
+ axis (+y, bottom to spray head), out of the front of the head on the side the trigger faces."""
+ spray = data.body("link_2").xmat.reshape(3, 3)[:, 2]
+ to_plant = data.body("plant").xpos - data.site("ref_point").xpos
+ c = float(np.dot(spray, to_plant) / max(1e-9, np.linalg.norm(to_plant)))
+ return float(np.degrees(np.arccos(np.clip(c, -1.0, 1.0))))
+
+
+def _log(*a: Any) -> None:
+ print("[rcb_dexjoco]", *a, file=sys.stderr, flush=True)
+
+
+class PrimitiveError(RuntimeError):
+ pass
+
+
+def _task_config(task: str):
+ from dexjoco.tasks.mappings import CONFIG_MAPPING
+ if task not in CONFIG_MAPPING:
+ raise KeyError(f"unknown task {task!r}; known: {sorted(CONFIG_MAPPING)}")
+ return CONFIG_MAPPING[task]()
+
+
+def _plain(v: Any) -> bool:
+ if isinstance(v, _SIMPLE):
+ return True
+ if isinstance(v, (list, tuple)):
+ return all(_plain(x) for x in v)
+ if isinstance(v, dict):
+ return all(isinstance(k, (str, int)) and _plain(x) for k, x in v.items())
+ return False
+
+
+def quat_mul(a, b) -> np.ndarray:
+ w1, x1, y1, z1 = a; w2, x2, y2, z2 = b
+ return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
+ w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
+
+
+def quat_slerp(a, b, t: float) -> np.ndarray:
+ a = np.asarray(a, float) / np.linalg.norm(a); b = np.asarray(b, float) / np.linalg.norm(b)
+ d = float(np.dot(a, b))
+ if d < 0:
+ b, d = -b, -d
+ if d > 0.9995:
+ q = a + t * (b - a); return q / np.linalg.norm(q)
+ th = np.arccos(d); s = np.sin(th)
+ return (np.sin((1 - t) * th) * a + np.sin(t * th) * b) / s
+
+
+class Session:
+ """One DexJoCo env on a frozen instance. Every episode starts from the instance snapshot."""
+
+ def __init__(self, task: str, instance: str | Path | None = None, *, max_steps: int = MAX_STEPS,
+ image_size: tuple[int, int] = (480, 640)):
+ import mujoco
+ self._mj = mujoco
+ self.task = task
+ self.max_steps = int(max_steps)
+ self.cfg = _task_config(task)
+ # render_mode "none" keeps DexJoCo from rendering its cameras on every step (CPU rendering is ~100x the
+ # physics cost); frames are rendered on demand by render_frame().
+ self.env = self.cfg.get_environment(policy_mode=True, render_mode="none", randomize=False)
+ self.base = self.env.unwrapped
+ self.base.hz = float("inf") # no real-time pacing
+ self.model, self.data = self.base._model, self.base._data
+ if hasattr(self.base, "image_obs"):
+ self.base.image_obs = False # bimanual envs take image_obs=True by default, read per step
+ # Several envs render all their cameras inside every observation regardless of image_obs / render_mode
+ # (click_mouse, hammer_nail, pinch_tongs; pick_bucket has its image_obs test commented out). Rendering only
+ # reads mjData, so it is replaced by blank frames of the same count; render_frame() renders on demand.
+ try:
+ n = len(self.base.render())
+ except RuntimeError: # water_plant: render_mode "none" already stops its rendering
+ n = 0
+ if n:
+ blank = np.zeros((1, 1, 3), np.uint8)
+ self.base.render = lambda: tuple(blank for _ in range(n))
+ self.bimanual = task.startswith("bimanual_")
+ self.action_dim = 46 if self.bimanual else 23
+ self.base.reset()
+ self._renderer = None
+ self._image_size = image_size
+ self._rec: list[np.ndarray] | None = None
+ self.resets = 0
+ self._snapshot = None
+ self.instance_meta: dict[str, Any] = {}
+ if instance is not None:
+ self.load_instance(instance)
+ else:
+ self._snapshot = self.snapshot()
+ self._episode_reset()
+ self._total_steps = 0
+ _slog("session_start", task=task)
+ import atexit
+ atexit.register(lambda: _slog("session_end", task=task, resets=self.resets, sim_steps=self._total_steps + self.steps))
+
+ # ------------------------------------------------------------------ state snapshots
+ def snapshot(self) -> dict[str, Any]:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ attrs = {k: copy.deepcopy(v) for k, v in vars(self.base).items()
+ if not k.startswith("__") and _plain(v) and k not in ("hz", "render_mode")}
+ return {"physics": phys, "mocap_pos": self.data.mocap_pos.copy(), "mocap_quat": self.data.mocap_quat.copy(),
+ "ctrl": self.data.ctrl.copy(), "act": self.data.act.copy() if self.model.na else np.zeros(0),
+ "attrs": attrs, "model": {k: v.copy() for k, v in _model_arrays(self.model).items()}}
+
+ def restore(self, snap: dict[str, Any]) -> None:
+ mj = self._mj
+ live = _model_arrays(self.model)
+ for k, v in snap.get("model", {}).items():
+ if k in live and live[k].shape == v.shape:
+ live[k][...] = v
+ mj.mj_setState(self.model, self.data, np.asarray(snap["physics"]), mj.mjtState.mjSTATE_INTEGRATION)
+ self.data.mocap_pos[:] = snap["mocap_pos"]; self.data.mocap_quat[:] = snap["mocap_quat"]
+ self.data.ctrl[:] = snap["ctrl"]
+ for k, v in snap["attrs"].items():
+ setattr(self.base, k, copy.deepcopy(v))
+ mj.mj_forward(self.model, self.data)
+
+ def state_sha(self) -> str:
+ mj = self._mj
+ sz = mj.mj_stateSize(self.model, mj.mjtState.mjSTATE_INTEGRATION)
+ phys = np.empty(sz); mj.mj_getState(self.model, self.data, phys, mj.mjtState.mjSTATE_INTEGRATION)
+ h = hashlib.sha1(phys.tobytes())
+ for k, v in sorted(_model_arrays(self.model).items()):
+ h.update(k.encode()); h.update(np.ascontiguousarray(v).tobytes())
+ return h.hexdigest()[:16]
+
+ def save_instance(self, path: str | Path, meta: dict | None = None) -> None:
+ snap = self.snapshot()
+ np.savez_compressed(path, task=self.task, physics=snap["physics"], mocap_pos=snap["mocap_pos"],
+ **{"model__" + k: v for k, v in snap["model"].items()},
+ mocap_quat=snap["mocap_quat"], ctrl=snap["ctrl"], act=snap["act"],
+ attrs=json.dumps(_to_json(snap["attrs"])), attr_types=json.dumps(_types(snap["attrs"])),
+ sha=self.state_sha(), meta=json.dumps(meta or {}))
+
+ def load_instance(self, path: str | Path) -> None:
+ d = np.load(path, allow_pickle=False)
+ if str(d["task"]) != self.task:
+ raise ValueError(f"instance is for task {str(d['task'])!r}, not {self.task!r}")
+ attrs = _from_json(json.loads(str(d["attrs"])), json.loads(str(d["attr_types"])))
+ model = {k[len("model__"):]: d[k] for k in d.files if k.startswith("model__")}
+ self._snapshot = {"physics": d["physics"], "mocap_pos": d["mocap_pos"], "mocap_quat": d["mocap_quat"],
+ "ctrl": d["ctrl"], "act": d["act"], "attrs": attrs, "model": model}
+ self.instance_meta = json.loads(str(d["meta"]))
+ self.restore(self._snapshot)
+ self.instance_sha = str(d["sha"])
+ self.instance_exact = self.state_sha() == self.instance_sha
+ if not self.instance_exact:
+ _log(f"WARNING: restored state sha {self.state_sha()} != instance sha {self.instance_sha}")
+
+ # ------------------------------------------------------------------ episode
+ def _episode_reset(self) -> None:
+ self.restore(self._snapshot)
+ self.steps = 0
+ self.done = False
+ self.success = False
+ self.reason: str | None = None
+ self.last_info: dict[str, Any] = {}
+ self._rcb_count = 0 # robot_coding_bench's own hold counter (tightened checks)
+
+ def reset(self) -> None:
+ """Back to the frozen instance state (unlimited). Starts a new episode."""
+ _slog("reset", task=self.task, n=self.resets + 1, sim_steps_before=self.steps)
+ self._total_steps += self.steps
+ self._episode_reset()
+ self.resets += 1
+
+ def step(self, action) -> bool:
+ """One control step with a (A,) action row. Returns True while the episode is running."""
+ a = np.asarray(action, dtype=np.float64).reshape(-1)
+ if a.shape != (self.action_dim,):
+ raise ValueError(f"action must have {self.action_dim} values {ACTION_LAYOUT[self.action_dim]}, got {a.shape}")
+ if not np.all(np.isfinite(a)):
+ raise ValueError("action contains NaN or inf")
+ if self.done:
+ raise PrimitiveError(f"episode is over ({self.reason}); call reset()")
+ if self.steps >= self.max_steps:
+ raise PrimitiveError(f"runaway guard: {self.max_steps} steps")
+ for q in ((a[3:7],) if not self.bimanual else (a[3:7], a[26:30])):
+ n = np.linalg.norm(q)
+ if n < 1e-6:
+ raise ValueError("tcp quaternion has zero norm")
+ raw = {"right": a[:23], "left": a[23:46]} if self.bimanual else a
+ self.base.env_step = 0 # DexJoCo's episode cap is lifted (wall clock is the budget)
+ _, _, terminated, _, info = self.base.step(raw)
+ if getattr(self.base, "_pending_illegal_reset", False):
+ self.base._pending_illegal_deadline = float("inf") # hanoi: never auto-reset on a wall-clock timer
+ self.steps += 1
+ if self._rec is not None:
+ self._rec.append(a.astype(np.float64))
+ self.last_info = {k: _jsonable(v) for k, v in dict(info).items()}
+ succeed = bool(info.get("succeed", False))
+ if self.task == "water_plant":
+ # upstream's zone + trigger condition, held 30 steps, AND the spray aimed at the plant (WATER_AIM_MAX_DEG)
+ aim = water_aim_deg(self.model, self.data)
+ zone_and_trigger = int(self.base._success_counter) > 0
+ self._rcb_count = self._rcb_count + 1 if (zone_and_trigger and aim <= WATER_AIM_MAX_DEG) else 0
+ self.last_info.update({"aim_deg": round(aim, 2), "rcb_success_count": self._rcb_count, "upstream_succeed": succeed})
+ succeed = self._rcb_count >= 30
+ failed = bool(terminated) and not bool(info.get("succeed", False)) and bool(self.base._trigger_pulled)
+ terminated = failed # upstream's own success no longer ends the episode
+ if succeed:
+ self.done, self.success, self.reason = True, True, "success"
+ elif terminated:
+ self.done, self.reason = True, _failure_reason(self.task, info)
+ return not self.done
+
+ def hold_action(self) -> np.ndarray:
+ """The action that keeps the current tcp targets and hand joint targets."""
+ return np.concatenate([self._arm_target(arm) for arm in self.arms()])
+
+ def status(self) -> dict[str, Any]:
+ return {"success": bool(self.success), "done": bool(self.done), "reason": self.reason, "steps": int(self.steps),
+ "resets": int(self.resets), "state_sha": self.state_sha(), "info": self.last_info}
+
+ # ------------------------------------------------------------------ recording / replay
+ def record_start(self) -> None:
+ self._rec = []
+
+ def record_stop(self) -> np.ndarray:
+ rec, self._rec = self._rec or [], None
+ _slog("record", task=self.task, n_actions=len(rec), success=bool(self.success))
+ return np.asarray(rec, dtype=np.float64).reshape(-1, self.action_dim)
+
+ def save_trajectory(self, actions, path: str | Path, meta: dict | None = None) -> None:
+ A = np.asarray(actions, dtype=np.float64)
+ if A.ndim != 2 or A.shape[1] != self.action_dim:
+ raise ValueError(f"trajectory must be (T, {self.action_dim}), got {A.shape}")
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ np.savez(path, actions=A, task=self.task, instance_sha=getattr(self, "instance_sha", ""),
+ action_layout=ACTION_LAYOUT[self.action_dim], meta=json.dumps(meta or {}))
+
+ def replay(self, actions) -> dict[str, Any]:
+ """Reset to the instance and replay open-loop until the episode ends or the rows run out."""
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ n = 0
+ for row in A:
+ n += 1
+ if not self.step(row):
+ break
+ st = self.status(); st["replayed_rows"] = n; st["rows"] = int(len(A))
+ _slog("replay", task=self.task, n_actions=int(len(A)), success=st["success"])
+ return st
+
+ # ------------------------------------------------------------------ privileged state
+ def arms(self) -> tuple[str, ...]:
+ return ("right", "left") if self.bimanual else ("right",)
+
+ def state(self) -> dict[str, list]:
+ """DexJoCo's state dict (privileged): tcp_pose [xyz, quat wxyz] (per arm), gripper_pose (16 hand joints per arm),
+ each task object's pose [xyz, quat wxyz], table_delta_height."""
+ obs = self.base._compute_observation()
+ return {k: np.asarray(v, float).reshape(-1).round(6).tolist() for k, v in obs["state"].items()}
+
+ def objects(self) -> dict[str, dict[str, Any]]:
+ """Live privileged state of the task's objects: name -> {kind, pos, quat_wxyz} (bodies), {pos} (sites, geoms),
+ {qpos} (joints)."""
+ out: dict[str, dict[str, Any]] = {}
+ for name, (kind, ref) in OBJECTS.get(self.task, {}).items():
+ if kind == "body":
+ p, q = self.body_pose(ref); out[name] = {"kind": kind, "pos": p.round(5).tolist(), "quat_wxyz": q.round(5).tolist()}
+ elif kind == "site":
+ out[name] = {"kind": kind, "pos": self.data.site(ref).xpos.round(5).tolist()}
+ elif kind == "geom":
+ gid = int(getattr(self.base, ref[1:])) if ref.startswith("@") else self.model.geom(ref).id
+ out[name] = {"kind": kind, "pos": self.data.geom_xpos[gid].round(5).tolist()}
+ elif kind == "joint":
+ out[name] = {"kind": kind, "qpos": float(np.asarray(self.data.joint(ref).qpos).reshape(-1)[0])}
+ return out
+
+ def bodies(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_BODY, i) or f"body{i}" for i in range(self.model.nbody)]
+
+ def body_pose(self, name: str) -> tuple[np.ndarray, np.ndarray]:
+ b = self.data.body(name)
+ return b.xpos.copy(), b.xquat.copy()
+
+ def _mocap_id(self, arm: str) -> int:
+ if not self.bimanual:
+ return 0
+ attr = getattr(self.base, f"_mocap_{arm}_id", None)
+ if attr is not None:
+ return int(attr)
+ try:
+ return int(self.model.body(f"target_{arm}").mocapid)
+ except KeyError:
+ return 0 if arm == "right" else 1 # bimanual_unlock_ipad indexes mocap 0 / 1 directly
+
+ def _hand_ctrl_ids(self, arm: str) -> np.ndarray:
+ ids = np.asarray(self.base._allegro_ctrl_ids)
+ if not self.bimanual:
+ return ids
+ return ids[:16] if arm == "right" else ids[16:32]
+
+ def _arm_target(self, arm: str) -> np.ndarray:
+ i = self._mocap_id(arm)
+ return np.concatenate([self.data.mocap_pos[i], self.data.mocap_quat[i], self.data.ctrl[self._hand_ctrl_ids(arm)]])
+
+ def ee_pose(self, arm: str = "right") -> tuple[np.ndarray, np.ndarray]:
+ """Actual tcp pose (xyz, quat wxyz) of an arm (the controller tracks the mocap target with some lag)."""
+ st = self.base._compute_observation()["state"]
+ key = "tcp_pose" if not self.bimanual else "tcp_pose"
+ v = np.asarray(st[key], float).reshape(-1)
+ if self.bimanual:
+ v = v[:7] if arm == "right" else v[7:14]
+ return v[:3].copy(), v[3:7].copy()
+
+ def hand_joints(self, arm: str = "right") -> np.ndarray:
+ v = np.asarray(self.base._compute_observation()["state"]["gripper_pose"], float).reshape(-1)
+ return (v[:16] if arm == "right" else v[16:32]).copy() if self.bimanual else v[:16].copy()
+
+ def hand_limits(self, arm: str = "right") -> np.ndarray:
+ """(16, 2) joint-target ranges (rad) of an arm's Allegro hand, in the action's order (see HAND_ORDER)."""
+ return self.model.actuator_ctrlrange[self._hand_ctrl_ids(arm)].copy()
+
+ # ------------------------------------------------------------------ rendering (on demand)
+ def cameras(self) -> list[str]:
+ mj = self._mj
+ return [mj.mj_id2name(self.model, mj.mjtObj.mjOBJ_CAMERA, i) for i in range(self.model.ncam)]
+
+ def render_frame(self, camera: str | None = None, size: tuple[int, int] | None = None) -> np.ndarray:
+ mj = self._mj
+ h, w = size or self._image_size
+ if self._renderer is None or (self._renderer.height, self._renderer.width) != (h, w):
+ if self._renderer is not None:
+ # a second OSMesa context next to a live one reads back garbage: close the old one first
+ self._renderer.close(); self._renderer = None
+ self.model.vis.global_.offheight = max(self.model.vis.global_.offheight, h)
+ self.model.vis.global_.offwidth = max(self.model.vis.global_.offwidth, w)
+ self._renderer = mj.Renderer(self.model, height=h, width=w)
+ cam = camera if camera is not None else self.default_camera()
+ self._renderer.update_scene(self.data, camera=cam)
+ return self._renderer.render().copy()
+
+ def video_cameras(self) -> list[str]:
+ """The cameras of a replay video: the default static camera and the (right) hand camera."""
+ cams = [c for c in (self.default_camera(), "handcam_rgb", "handcam_rgb_right") if c in self.cameras()]
+ return list(dict.fromkeys(cams))[:2]
+
+ def default_camera(self) -> str:
+ cams = self.cameras()
+ for c in ("front", "agentview", "overview"):
+ if c in cams:
+ return c
+ return cams[0]
+
+ def render_grid(self, cameras: list[str] | None = None, size: tuple[int, int] = (240, 320), cols: int = 3) -> np.ndarray:
+ cams = cameras or self.cameras()
+ frames = [self.render_frame(c, size) for c in cams]
+ while len(frames) % cols:
+ frames.append(np.zeros_like(frames[0]))
+ rows = [np.concatenate(frames[i:i + cols], axis=1) for i in range(0, len(frames), cols)]
+ return np.concatenate(rows, axis=0)
+
+ def render_video(self, actions, path: str | Path, *, cameras: list[str] | None = None, every: int = 2, fps: int = 25,
+ size: tuple[int, int] = (240, 320)) -> dict[str, Any]:
+ import imageio.v2 as imageio
+ A = np.asarray(actions, dtype=np.float64)
+ self.reset()
+ cams = cameras or [self.default_camera()]
+ w = imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7, macro_block_size=8)
+ try:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ for i, row in enumerate(A):
+ running = self.step(row)
+ if i % every == 0 or not running:
+ w.append_data(np.concatenate([self.render_frame(c, size) for c in cams], axis=1))
+ if not running:
+ break
+ finally:
+ w.close()
+ return self.status()
+
+ # ------------------------------------------------------------------ primitives
+ def primitives(self) -> dict[str, Callable]:
+ s = self
+
+ def _run(targets: dict[str, np.ndarray], steps: int) -> dict:
+ for _ in range(max(1, int(steps))):
+ row = s.hold_action()
+ for arm, t in targets.items():
+ k = s.arms().index(arm) * 23
+ row[k:k + len(t)] = t if len(t) == 23 else np.concatenate([t, row[k + len(t):k + 23]])
+ if not s.step(row):
+ break
+ return s.status()
+
+ def get_objects():
+ """Live poses of the task objects (see Session.objects())."""
+ return s.objects()
+
+ def get_state():
+ """Privileged state dict: tcp_pose, gripper_pose (hand joints), object poses, table_delta_height."""
+ return s.state()
+
+ def get_ee_pose(arm: str = "right"):
+ return s.ee_pose(arm)
+
+ def get_ee_target(arm: str = "right"):
+ t = s._arm_target(arm); return t[:3].copy(), t[3:7].copy()
+
+ def get_hand(arm: str = "right"):
+ """Measured hand joint angles (16,)."""
+ return s.hand_joints(arm)
+
+ def get_hand_target(arm: str = "right"):
+ return s._arm_target(arm)[7:23].copy()
+
+ def get_body_pose(name: str):
+ """World pose (xyz, quat wxyz) of any MuJoCo body (see s.bodies())."""
+ return s.body_pose(name)
+
+ def hold(steps: int = 10):
+ """Keep every target for `steps` control steps."""
+ return _run({}, steps)
+
+ def move_ee(arm: str, pos, quat_wxyz=None, *, steps: int | None = None, max_speed: float = 0.25,
+ max_rot_speed: float = 1.5, settle: int = 10, hand=None):
+ """Move an arm's tcp target to (pos, quat) along a straight line + slerp, then hold `settle` steps.
+ steps defaults to what max_speed (m/s) and max_rot_speed (rad/s) allow at 50 Hz. `hand` (16,) optionally
+ interpolates the hand joint targets along the same path."""
+ p0, q0 = get_ee_target(arm)
+ p1 = np.asarray(pos, float); q1 = q0 if quat_wxyz is None else np.asarray(quat_wxyz, float)
+ q1 = q1 / np.linalg.norm(q1)
+ h0 = get_hand_target(arm); h1 = h0 if hand is None else np.asarray(hand, float)
+ if steps is None:
+ ang = 2 * np.arccos(min(1.0, abs(float(np.dot(q0 / np.linalg.norm(q0), q1)))))
+ steps = int(np.ceil(max(np.linalg.norm(p1 - p0) / (max_speed / 50), ang / (max_rot_speed / 50), 1)))
+ for i in range(1, steps + 1):
+ t = i / steps
+ tgt = np.concatenate([p0 + t * (p1 - p0), quat_slerp(q0, q1, t), h0 + t * (h1 - h0)])
+ st = _run({arm: tgt}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_hand(arm: str, q16, *, steps: int = 25, settle: int = 10):
+ """Interpolate an arm's 16 Allegro joint targets to q16 (rad) over `steps`, then hold `settle` steps."""
+ h0 = get_hand_target(arm); h1 = np.asarray(q16, float).reshape(16)
+ p, q = get_ee_target(arm)
+ for i in range(1, steps + 1):
+ st = _run({arm: np.concatenate([p, q, h0 + i / steps * (h1 - h0)])}, 1)
+ if st["done"]:
+ return st
+ return _run({}, settle) if settle else s.status()
+
+ def set_targets(row, steps: int = 1):
+ """Send one raw (A,) action row for `steps` control steps."""
+ r = np.asarray(row, float)
+ for _ in range(max(1, int(steps))):
+ if not s.step(r):
+ break
+ return s.status()
+
+ return {"get_objects": get_objects, "get_state": get_state, "get_ee_pose": get_ee_pose, "get_ee_target": get_ee_target, "get_hand": get_hand,
+ "get_hand_target": get_hand_target, "get_body_pose": get_body_pose, "hold": hold, "move_ee": move_ee,
+ "set_hand": set_hand, "set_targets": set_targets}
+
+ def close(self) -> None:
+ try:
+ self.env.close()
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------- helpers
+def _failure_reason(task: str, info: dict) -> str:
+ if info.get("illegal_state"):
+ return "failure: " + str(info.get("illegal_reason") or "illegal state")
+ if task == "water_plant":
+ return "failure: trigger pulled away from the plant"
+ if task == "bimanual_unlock_ipad":
+ return "failure: wrong passcode"
+ return "failure: task terminated"
+
+
+def _jsonable(v: Any) -> Any:
+ if isinstance(v, np.ndarray):
+ return v.round(6).tolist()
+ if isinstance(v, (np.floating,)):
+ return round(float(v), 6)
+ if isinstance(v, (np.integer,)):
+ return int(v)
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ 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 _types(attrs: dict) -> dict:
+ def t(v):
+ if isinstance(v, np.ndarray):
+ return {"nd": str(v.dtype), "shape": list(v.shape)}
+ if isinstance(v, (np.bool_, np.integer, np.floating)):
+ return {"np": str(np.asarray(v).dtype)}
+ if isinstance(v, bool):
+ return "bool"
+ if isinstance(v, int):
+ return "int"
+ if isinstance(v, float):
+ return "float"
+ if isinstance(v, tuple):
+ return {"tuple": [t(x) for x in v]}
+ if isinstance(v, list):
+ return {"list": [t(x) for x in v]}
+ if isinstance(v, dict):
+ return {"dict": {str(k): t(x) for k, x in v.items()}, "keys": [type(k).__name__ for k in v]}
+ return type(v).__name__
+ return {k: t(v) for k, v in attrs.items()}
+
+
+def _to_json(attrs: dict) -> dict:
+ def j(v):
+ if isinstance(v, np.ndarray):
+ return v.tolist()
+ if isinstance(v, (np.bool_,)):
+ return bool(v)
+ if isinstance(v, np.integer):
+ return int(v)
+ if isinstance(v, np.floating):
+ return float(v)
+ if isinstance(v, (list, tuple)):
+ return [j(x) for x in v]
+ if isinstance(v, dict):
+ return {str(k): j(x) for k, x in v.items()}
+ return v
+ return {k: j(v) for k, v in attrs.items()}
+
+
+def _from_json(vals: dict, types: dict) -> dict:
+ def f(v, t):
+ if isinstance(t, dict) and "np" in t:
+ return np.asarray(v, dtype=t["np"])[()]
+ if isinstance(t, dict) and "nd" in t:
+ return np.asarray(v, dtype=t["nd"]).reshape(t["shape"])
+ if isinstance(t, dict) and "tuple" in t:
+ return tuple(f(x, tt) for x, tt in zip(v, t["tuple"]))
+ if isinstance(t, dict) and "list" in t:
+ return [f(x, tt) for x, tt in zip(v, t["list"])]
+ if isinstance(t, dict) and "dict" in t:
+ out = {}
+ for (k, x), kt in zip(v.items(), t["keys"]):
+ out[int(k) if kt == "int" else k] = f(x, t["dict"][k])
+ return out
+ if t == "bool":
+ return bool(v)
+ if t == "int":
+ return int(v)
+ if t == "float":
+ return float(v)
+ return v
+ return {k: f(v, types[k]) for k, v in vals.items()}
+
+
+def _load_traj(path: str) -> np.ndarray:
+ return np.asarray(np.load(path, allow_pickle=False)["actions"], dtype=np.float64)
+
+
+# ---------------------------------------------------------------------- CLI
+def cmd_make_instance(a) -> None:
+ import zarr
+ from dexjoco.tasks.state_restorers import restore_initial_state
+ s = Session(a.task)
+ root = zarr.open(a.demo, mode="r")
+ state0 = np.asarray(root["data"]["state"][0]).ravel()
+ s.base.reset()
+ restore_initial_state(s.env, a.task, s.cfg, state0)
+ s._snapshot = s.snapshot()
+ s._episode_reset()
+ meta = {"source": "DexJoCo-Datasets-Raw demo, initial state restored with dexjoco.tasks.state_restorers",
+ "demo": a.demo_name or os.path.basename(os.path.dirname(os.path.abspath(a.demo))), "dexjoco": "8d23b0f"}
+ s.save_instance(a.out, meta)
+ _log("instance", a.out, "sha", s.state_sha())
+ if a.oracle_out:
+ A = np.asarray(root["data"]["action"], dtype=np.float64)
+ s2 = Session(a.task, instance=a.out)
+ st = s2.replay(A)
+ s2.save_trajectory(A[:st["replayed_rows"]], a.oracle_out, {"source": "demo actions", "demo": meta["demo"]})
+ print(json.dumps({"oracle": a.oracle_out, **{k: st[k] for k in ("success", "reason", "replayed_rows", "rows", "state_sha")}}))
+
+
+def cmd_replay(a) -> None:
+ """Replay a trajectory from the frozen instance, `--repeat` times (each in a new Session). `--out` writes the result
+ as JSON (the standard-mode collect hook runs one replay per fresh process); `--video` renders the first replay
+ (at most ~1500 frames, after the verdict fields are known; it never changes them)."""
+ A = _load_traj(a.traj)
+ runs, instance_ok, video = [], True, False
+ for i in range(a.repeat):
+ s = Session(a.task, instance=a.instance)
+ instance_ok = instance_ok and bool(s.instance_exact)
+ st = s.replay(A)
+ runs.append({k: st[k] for k in ("success", "reason", "steps", "state_sha", "replayed_rows", "rows")})
+ if a.video and i == 0:
+ try:
+ n = int(st["replayed_rows"])
+ s.render_video(A[:n], a.video, cameras=s.video_cameras(), every=max(2, -(-n // 1500)))
+ video = os.path.isfile(a.video)
+ except Exception: # noqa: BLE001
+ import traceback
+ traceback.print_exc(file=sys.stderr)
+ s.close()
+ out = {"n_actions": int(len(A)), "replays": runs, "all_success": all(r["success"] for r in runs),
+ "deterministic": len({r["state_sha"] for r in runs}) == 1, "success": bool(runs[0]["success"]),
+ "state_sha": runs[0]["state_sha"], "reason": runs[0]["reason"], "steps": runs[0]["steps"],
+ "instance_ok": instance_ok, "video": video}
+ print(json.dumps(out))
+ if a.out:
+ with open(a.out, "w") as f:
+ json.dump(out, f)
+
+
+def cmd_render(a) -> None:
+ s = Session(a.task, instance=a.instance)
+ print(json.dumps(s.render_video(_load_traj(a.traj), a.out, every=a.every)))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ sub = ap.add_subparsers(dest="cmd", required=True)
+ m = sub.add_parser("make-instance"); m.add_argument("--task", required=True); m.add_argument("--demo", required=True)
+ m.add_argument("--demo-name"); m.add_argument("--out", required=True); m.add_argument("--oracle-out")
+ r = sub.add_parser("replay"); r.add_argument("--task", required=True); r.add_argument("--instance", required=True)
+ r.add_argument("--traj", required=True); r.add_argument("--repeat", type=int, default=2); r.add_argument("--video")
+ r.add_argument("--out", help="also write the result to this JSON file")
+ v = sub.add_parser("render"); v.add_argument("--task", required=True); v.add_argument("--instance", required=True)
+ v.add_argument("--traj", required=True); v.add_argument("--out", required=True); v.add_argument("--every", type=int, default=2)
+ a = ap.parse_args()
+ {"make-instance": cmd_make_instance, "replay": cmd_replay, "render": cmd_render}[a.cmd](a)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/dexjoco-water-plant-i00-standard/environment/sim/rcb_limited.py b/tasks/dexjoco-water-plant-i00-standard/environment/sim/rcb_limited.py
new file mode 100644
index 0000000000..1ce1171787
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-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/dexjoco-water-plant-i00-standard/environment/sim/run.sh b/tasks/dexjoco-water-plant-i00-standard/environment/sim/run.sh
new file mode 100755
index 0000000000..49d4d045d4
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-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; done
diff --git a/tasks/dexjoco-water-plant-i00-standard/environment/sim/server.py b/tasks/dexjoco-water-plant-i00-standard/environment/sim/server.py
new file mode 100644
index 0000000000..ca5b61fc5c
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-standard/environment/sim/server.py
@@ -0,0 +1,625 @@
+"""eai-standard/2.2 sim service for DexJoCo (docs/STANDARD_MODE_2_2.md): the adapter of the shared layer rcb_limited.py;
+the simulator is rcb_dexjoco.Session (DexJoCo on MuJoCo 3.4, CPU physics, OSMesa rendering).
+HTTP surface: GET /spec, GET /status, POST /observe, POST /submit, POST /kinematics. Every call is logged to
+/data/episode.jsonl.
+
+The robot is a Franka Panda with a 16-DoF Allegro hand, or two of them side by side (right arm first). One control step
+= 1/50 s (10 physics substeps of 2 ms). Two action types:
+ ee_pose DexJoCo's own row, per arm: the tcp target pose (xyz m, quaternion wxyz, world frame) that its
+ operational-space controller tracks + 16 Allegro joint targets (rad);
+ joint_position per arm: 7 arm joint targets + 16 Allegro joint targets; the arm's targets are turned into a tcp target
+ by forward kinematics (the controller tracks the tcp pose, not the joints).
+Either way, the executed (journaled, recorded) row is DexJoCo's own row, so the recorded trajectory replays in the
+privileged tooling unchanged. As in DexJoCo's evaluation the episode ends at the first success or task failure;
+otherwise when the agent's time is over (the collect hook's SIGUSR1).
+
+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 instance 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")
+TASK = os.environ.get("RCB_TASK", "water_plant")
+INSTANCE = os.environ.get("RCB_INSTANCE", os.path.join(os.path.dirname(os.path.abspath(__file__)), "instance.npz"))
+TASK_TEXT_FILE = os.environ.get("RCB_TASK_TEXT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "task_text.txt"))
+WALL_CLOCK_S = float(os.environ.get("RCB_WALL_CLOCK_S", "5400"))
+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 = 640, 480
+CTRL_HZ = 50.0
+DT = 1.0 / CTRL_HZ
+SUBSTEPS = 10
+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"] = "" # the sidecar's Session is not the agent's interaction log
+import rcb_dexjoco as M # noqa: E402
+import mujoco # noqa: E402
+
+M.SESSION_LOG = ""
+BIM = TASK.startswith("bimanual_")
+ADIM = 46 if BIM else 23
+EP = L.Episode(DATA, dim=ADIM, resume="exact")
+EP.startup() # start count, back-off after failed starts, the startup watchdog until scene_built()
+S = M.Session(TASK, instance=INSTANCE, image_size=(CAM_H, CAM_W))
+MD, D = S.model, S.data
+ARMS = S.arms()
+SFX = {a: (f"_{a}" if BIM else "") for a in ARMS}
+ROWS: list = [] # every executed row (a resume replays them first): trajectory.npz
+
+# ------------------------------------------------------------------------------------------------- the robot
+ARM_JOINTS = {a: [f"joint{i}{SFX[a]}" for i in range(1, 8)] for a in ARMS}
+HAND_CTRL = {a: np.asarray(S._hand_ctrl_ids(a)) for a in ARMS}
+HAND_JOINTS = {a: [MD.joint(int(MD.actuator_trnid[i, 0])).name for i in HAND_CTRL[a]] for a in ARMS} # action order
+ARM_CTRL = {a: [MD.actuator(f"actuator{i}{SFX[a]}").id for i in range(1, 8)] for a in ARMS}
+JOINTS = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]] # kinematics q = proprio joint_pos columns
+QADR = np.array([MD.jnt_qposadr[MD.joint(j).id] for j in JOINTS])
+VADR = np.array([MD.jnt_dofadr[MD.joint(j).id] for j in JOINTS])
+EFF_ACT = np.array([i for a in ARMS for i in list(ARM_CTRL[a]) + list(HAND_CTRL[a])])
+TCP_SITE = {a: MD.site(f"attachment_site{SFX[a]}").id for a in ARMS}
+TCP = {a: f"tcp{SFX[a]}" for a in ARMS}
+MOUNT_BODY = {a: f"attachment{SFX[a]}" for a in ARMS}
+LINKS = {a: [f"link{i}{SFX[a]}" for i in range(0, 8) if mujoco.mj_name2id(MD, mujoco.mjtObj.mjOBJ_BODY, f"link{i}{SFX[a]}") >= 0]
+ + [MOUNT_BODY[a]] for a in ARMS}
+KIN_LINKS = [n for a in ARMS for n in LINKS[a] + [TCP[a]]]
+JLIM = {j: MD.jnt_range[MD.joint(j).id].astype(float).tolist() for j in JOINTS}
+HLIM = {a: S.hand_limits(a) for a in ARMS} # actuator ctrlrange, action order
+ALIM = {} # joint_position limits (inside the joint ranges)
+for a in ARMS:
+ for j in ARM_JOINTS[a]:
+ ALIM[j] = JLIM[j]
+ for j, (lo, hi) in zip(HAND_JOINTS[a], HLIM[a]):
+ ALIM[j] = [max(float(lo), JLIM[j][0]), min(float(hi), JLIM[j][1])]
+POSE = ["x", "y", "z", "qw", "qx", "qy", "qz"]
+EE_LAYOUT = [] # per arm, right first
+for a in ARMS:
+ EE_LAYOUT += [f"{TCP[a]}_target_{k}" for k in POSE] + [f"{j}_target" for j in HAND_JOINTS[a]]
+JP_LAYOUT = [j for a in ARMS for j in ARM_JOINTS[a] + HAND_JOINTS[a]]
+
+GROUPS = [
+ ("joint_pos", JOINTS, "measured joint positions (rad): per arm (right first) the 7 Panda joints, then the 16 Allegro "
+ "joints in the action's order"),
+ ("joint_vel", [f"{j}_vel" for j in JOINTS], "measured joint velocities (rad/s)"),
+ ("joint_effort", [f"{j}_effort" for j in JOINTS], "actuator efforts (N m): the arm's operational-space torques and the "
+ "hand's position-actuator forces"),
+ ("gripper_opening", [], "none: a 16-DoF Allegro hand, its finger joints are in joint_pos"),
+ ("tcp_pose", [f"{TCP[a]}_{k}" for a in ARMS for k in POSE], "measured tcp pose per arm (x y z m, quaternion wxyz, world)"),
+ ("tcp_target", [f"{TCP[a]}_target_{k}" for a in ARMS for k in POSE], "the tcp target the controller tracks now (the "
+ "ee_pose part of the last executed row)"),
+ ("hand_target", [f"{j}_target" for a in ARMS for j in HAND_JOINTS[a]], "the Allegro joint targets now (rad)"),
+]
+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)
+
+
+def _quat(xmat) -> np.ndarray:
+ q = np.zeros(4)
+ mujoco.mju_mat2Quat(q, np.asarray(xmat, dtype=np.float64).reshape(9))
+ return q
+
+
+# ------------------------------------------------------------------------------------------------- cameras
+CAMS = S.cameras()
+HAND_CAMS = [c for c in CAMS if c.startswith("handcam")]
+DEFAULT_CAMS = [S.default_camera()]
+GL2CV = np.diag([1.0, -1.0, -1.0, 1.0])
+
+
+def _intrinsic(cam: str) -> list:
+ fovy = math.radians(float(MD.cam_fovy[MD.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 _cam2world_gl(cam: str) -> np.ndarray:
+ i = MD.camera(cam).id
+ T = np.eye(4)
+ T[:3, :3] = D.cam_xmat[i].reshape(3, 3) # MuJoCo camera axes: OpenGL (x right, y up, z back)
+ T[:3, 3] = D.cam_xpos[i]
+ return T
+
+
+def _extrinsic(cam: str) -> np.ndarray:
+ return np.linalg.inv(_cam2world_gl(cam) @ GL2CV)[:3, :]
+
+
+def camera_info(cam: str) -> dict:
+ return {"intrinsic_cv": _intrinsic(cam), "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist(),
+ "image_size": [CAM_W, CAM_H]}
+
+
+def _mount(cam: str) -> dict:
+ i = MD.camera(cam).id
+ body = MD.body(int(MD.cam_bodyid[i])).name
+ if int(MD.cam_bodyid[i]) == 0:
+ return {"type": "static", "extrinsic_cv": _extrinsic(cam).tolist(), "cam2world_gl": _cam2world_gl(cam).tolist()}
+ T = np.eye(4) # body -> camera (OpenGL axes), then to OpenCV axes
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.cam_quat[i])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.cam_pos[i]
+ return {"type": "link", "parent_link": body, "link_T_cam_cv": (T @ GL2CV).tolist()}
+
+
+def _mounted(cam: str) -> str:
+ if cam.startswith("handcam"):
+ side = "the right" if cam.endswith("_right") else "the left" if cam.endswith("_left") else "the"
+ return f"on {side} hand's mount (moves with the hand)"
+ return {"front": "static, across the table, facing the robot", "back": "static, behind the robot, looking over the table",
+ "left": "static, at the robot's left", "right": "static, at the robot's right",
+ "top0": "static, above the table, looking down"}.get(cam, "static")
+
+
+# ------------------------------------------------------------------------------------------------- kinematics
+KD = mujoco.MjData(MD) # kinematics only: never stepped; the robot's joints are set, everything else stays put
+ARM_QI = {a: [JOINTS.index(j) for j in ARM_JOINTS[a]] for a in ARMS}
+
+
+def _fk(q) -> None:
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR] = np.asarray(q, dtype=np.float64)
+ mujoco.mj_kinematics(MD, KD)
+
+
+def _link_pose(name: str) -> list:
+ for a in ARMS:
+ if name == TCP[a]:
+ s = TCP_SITE[a]
+ return [*KD.site_xpos[s].tolist(), *_quat(KD.site_xmat[s]).tolist()]
+ b = MD.body(name).id
+ return [*KD.xpos[b].tolist(), *KD.xquat[b].tolist()]
+
+
+def tcp_from_arm_joints(a: str, q7) -> np.ndarray:
+ """The tcp pose (xyz + wxyz) of arm `a` with its 7 joints at q7 (the joint_position action's tcp target)."""
+ KD.qpos[:] = D.qpos
+ KD.qpos[QADR[ARM_QI[a]]] = q7
+ mujoco.mj_kinematics(MD, KD)
+ s = TCP_SITE[a]
+ return np.concatenate([KD.site_xpos[s], _quat(KD.site_xmat[s])])
+
+
+def do_kinematics(req: dict) -> dict:
+ """World frame. FK: every link of spec kinematics.links for q. IK: per tcp target, damped least squares over that
+ arm's 7 joints (position and orientation), within the joint ranges; the hand joints are taken from the seed."""
+ if req["op"] == "fk":
+ _fk(req["q"])
+ return L.fk_response({n: _link_pose(n) for n in req["links"]}, "world")
+ q = np.array(req["seed"] if req["seed"] is not None else D.qpos[QADR], dtype=np.float64)
+ errors = {}
+ jp, jr = np.zeros((3, MD.nv)), np.zeros((3, MD.nv))
+ for frame, pose in req["targets"].items():
+ a = next(x for x in ARMS if TCP[x] == frame)
+ idx = ARM_QI[a]
+ dofs = VADR[idx]
+ tp, tq = np.asarray(pose[:3]), np.asarray(pose[3:7])
+ lo = np.array([JLIM[JOINTS[i]][0] for i in idx]); hi = np.array([JLIM[JOINTS[i]][1] for i in idx])
+ for _ in range(req["max_iters"]):
+ _fk(q)
+ mujoco.mj_comPos(MD, KD) # the Jacobian needs cdof, which mj_kinematics alone leaves stale
+ s = TCP_SITE[a]
+ ep = tp - KD.site_xpos[s]
+ cq = _quat(KD.site_xmat[s])
+ dq = np.zeros(4); neg = np.zeros(4); er = np.zeros(3)
+ mujoco.mju_negQuat(neg, cq); mujoco.mju_mulQuat(dq, tq, neg); mujoco.mju_quat2Vel(er, dq, 1.0)
+ if np.linalg.norm(ep) < req["tol_pos_m"] and np.linalg.norm(er) < req["tol_rot_rad"]:
+ break
+ mujoco.mj_jacSite(MD, KD, jp, jr, s)
+ J = np.vstack([jp[:, dofs], jr[:, dofs]])
+ err = np.concatenate([ep, er])
+ step = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), err)
+ q[idx] = np.clip(q[idx] + step, lo, hi)
+ _fk(q)
+ s = TCP_SITE[a]
+ errors[frame] = (float(np.linalg.norm(tp - KD.site_xpos[s])), L.quat_angle(_quat(KD.site_xmat[s]), tq / np.linalg.norm(tq)))
+ ok = all(e[0] <= req["tol_pos_m"] and e[1] <= req["tol_rot_rad"] for e in errors.values())
+ return L.ik_response(q, ok, errors, "world", note="the tcp (attachment_site) of each arm; the hand joints are the seed's")
+
+
+# ------------------------------------------------------------------------------------------------- spec
+def _joint_spec(a: str) -> list:
+ out = []
+ for j, ai in zip(ARM_JOINTS[a], ARM_CTRL[a]):
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_ctrlrange[ai][1]), "group": f"{a}_arm"})
+ for j, ai in zip(HAND_JOINTS[a], HAND_CTRL[a]):
+ fl = bool(MD.actuator_forcelimited[ai]) and float(MD.actuator_forcerange[ai][1]) > 0
+ out.append({"name": j, "type": "revolute", "unit": "rad", "position_limits": JLIM[j], "velocity_limit": None,
+ "effort_limit": float(MD.actuator_forcerange[ai][1]) if fl else None, "group": f"{a}_hand"})
+ return out
+
+
+def _tcp_spec(a: str) -> dict:
+ s = TCP_SITE[a]
+ T = np.eye(4)
+ R = np.zeros(9)
+ mujoco.mju_quat2Mat(R, MD.site_quat[s])
+ T[:3, :3] = R.reshape(3, 3)
+ T[:3, 3] = MD.site_pos[s]
+ return {"parent_link": MD.body(int(MD.site_bodyid[s])).name, "link_T_frame": T.tolist(),
+ "definition": "DexJoCo's attachment_site: the flange where the Allegro hand is mounted, the point its "
+ "operational-space controller drives to the ee_pose target (not the fingertips)"}
+
+
+def _base(a: str) -> list:
+ b = D.body(f"link0{SFX[a]}")
+ return [*np.round(b.xpos, 6).tolist(), *np.round(b.xquat, 6).tolist()]
+
+
+GAINS = {}
+for _a in ARMS:
+ for _j, _ai in zip(HAND_JOINTS[_a], HAND_CTRL[_a]):
+ GAINS[_j] = {"stiffness": float(MD.actuator_gainprm[_ai][0]), "damping": float(MD.dof_damping[MD.jnt_dofadr[MD.joint(_j).id]])}
+ROBOT_NAME = "franka-allegro-bimanual" if BIM else "franka-allegro"
+try:
+ TASK_TEXT = open(TASK_TEXT_FILE).read().strip()
+except OSError:
+ TASK_TEXT = f"DexJoCo {TASK}"
+SPEC = {
+ "protocol": L.PROTOCOL,
+ "protocol_compat": list(L.COMPAT),
+ "simulator": "DexJoCo @ 8d23b0f on MuJoCo 3.4.0 (CPU physics, OSMesa rendering)",
+ "robot": ROBOT_NAME,
+ "task_text": TASK_TEXT,
+ "control_hz": CTRL_HZ,
+ "physics_substeps": SUBSTEPS,
+ "physics_hz": CTRL_HZ * SUBSTEPS,
+ "max_chunk_s": MAX_CHUNK_S,
+ "max_watch_s": MAX_WATCH_S,
+ "cameras": {c: {"rgb": True, "depth": True, "mounted": _mounted(c), "resolution": [CAM_W, CAM_H], "intrinsic_cv": _intrinsic(c),
+ "mount": _mount(c)} for c in CAMS},
+ "default_cameras": DEFAULT_CAMS,
+ "action_types": {
+ "ee_pose": {
+ "dim": ADIM, "layout": EE_LAYOUT,
+ "units": "per arm (right first): tcp target position (m, world frame), tcp target orientation (quaternion wxyz), "
+ "16 Allegro joint targets (rad)",
+ "frame": "world", "quaternion_order": "wxyz", "ee_frames": [TCP[a] for a in ARMS],
+ "hand_limits": {j: ALIM[j] for a in ARMS for j in HAND_JOINTS[a]},
+ "semantics": "DexJoCo's own action row. The arm tracks the tcp target through DexJoCo's operational-space "
+ "controller (it lags a moving target and stops where contact blocks it); the hand joints are "
+ "position-controlled. Rows are `dt` apart (a whole multiple of 1/50 s, at most 0.5 s); between rows "
+ "positions and joints move linearly and orientations by slerp (`linear`) or jump (`hold`); a row's "
+ "own values land exactly on its last control step. Hand targets outside the ranges are clamped by "
+ "the simulator and reported in `clipped`; a zero quaternion is a 400.",
+ },
+ "joint_position": {
+ "dim": ADIM, "layout": JP_LAYOUT, "units": "rad", "limits": {j: ALIM[j] for j in JP_LAYOUT},
+ "semantics": "per arm (right first): 7 Panda joint targets, then the 16 Allegro joint targets. The arm's "
+ "targets are turned into a tcp target by forward kinematics (as POST /kinematics fk) and the arm "
+ "tracks that pose through the same operational-space controller as ee_pose, whose null space "
+ "pulls towards DexJoCo's home posture: the tcp reaches FK(q), the measured joints may differ from q "
+ "in the arm's redundant direction. Rows `dt` apart, `linear` (in joint space) or `hold`; values "
+ "outside the limits are clipped and reported.",
+ },
+ "not_yet": ["joint_delta", "joint_velocity", "ee_delta", "joint_torque"],
+ },
+ "proprio_layout": PROPRIO_LAYOUT,
+ "proprio_groups": PROPRIO_GROUPS,
+ "static": {},
+ "world": {"frame": "DexJoCo's world frame: z up, metres; the robot" + ("s stand" if BIM else " stands")
+ + " at low x and reach" + ("" if BIM else "es") + " towards +x"
+ + (" (right arm at y < 0, left arm at y > 0)" if BIM else ""),
+ "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},
+ "episode": "one episode, no reset: it ends at the first success, at a task failure (see task_text), or when your time is over",
+ "robot_spec": {
+ "name": ROBOT_NAME,
+ "description": ("two Franka Panda arms side by side, each with a 16-DoF Allegro hand (right arm first)" if BIM
+ else "a Franka Panda arm with a 16-DoF Allegro hand"),
+ "base": {"type": "fixed", "pose": _base(ARMS[0]), **({"per_arm": {a: _base(a) for a in ARMS}} if BIM else {}),
+ "note": "pose of the arm's base link (link0), world frame, x y z + quaternion wxyz"},
+ "joints": [j for a in ARMS for j in _joint_spec(a)],
+ "grippers": {},
+ "controller": {"type": "arm: operational-space control of the tcp (torques); hand: joint position actuators",
+ "control_hz": CTRL_HZ, "physics_hz": CTRL_HZ * SUBSTEPS, "gains": GAINS,
+ "note": "arm: DexJoCo's opspace controller drives attachment_site to the tcp target (position gains "
+ "400 N/m, damping ratio 4, gravity compensation, null space towards the home posture), "
+ "torques limited to effort_limit; hand: position actuators (stiffness N m/rad) on joints "
+ "with their own damping (N m s/rad)"},
+ "tcp": {TCP[a]: _tcp_spec(a) for a in ARMS},
+ },
+ "kinematics": {"endpoint": "/kinematics", "joint_names": JOINTS, "frame": "world", "quaternion_order": "wxyz",
+ "links": KIN_LINKS, "tcp_frames": [TCP[a] for a in ARMS], "ee_frames": [TCP[a] for a in ARMS],
+ "ik_targets": [TCP[a] for a in ARMS], "ik": {"tol_pos_m": 0.001, "tol_rot_rad": 0.01, "max_iters": 300},
+ "note": "the arm links, the hand mount (the hand cameras' parent) and the tcp, world frame; ik solves "
+ "each tcp target over that arm's 7 joints"},
+ "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()
+
+
+# ------------------------------------------------------------------------------------------------- state and frames
+def ctrl_steps() -> int:
+ return int(S.steps)
+
+
+def proprio_row() -> np.ndarray:
+ tcp, tgt, hand = [], [], []
+ for a in ARMS:
+ s = TCP_SITE[a]
+ tcp += [D.site_xpos[s], _quat(D.site_xmat[s])]
+ t = S._arm_target(a)
+ tgt.append(t[:7]); hand.append(t[7:23])
+ return np.concatenate([D.qpos[QADR], D.qvel[VADR], D.actuator_force[EFF_ACT], *tcp, *tgt, *hand]).astype(np.float32)
+
+
+def grab(cams, want_depth: bool):
+ rgb, dep = {}, {}
+ for c in cams:
+ rgb[c] = S.render_frame(c, (CAM_H, CAM_W))
+ if want_depth:
+ r = S._renderer # the one renderer (a second OSMesa context reads back garbage)
+ r.enable_depth_rendering()
+ try:
+ r.update_scene(D, camera=c)
+ dep[c] = r.render().astype(np.float32).copy()
+ finally:
+ r.disable_depth_rendering()
+ return rgb, dep
+
+
+def extrinsics(cams) -> dict:
+ return {c: _extrinsic(c) for c in cams}
+
+
+def summary() -> dict:
+ n = int(E.get("episode_control_steps") or ctrl_steps())
+ 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"],
+ "task": TASK, "protocol": L.PROTOCOL, "n_actions": len(ROWS), "task_failure": int(str(E["reason"] or "").startswith("failure")),
+ **EP.final_fields()}
+
+
+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 finish(reason: str) -> None:
+ """The episode is over: record the live verdict and dump the trajectory 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()
+ E["success"] = bool(S.success)
+ 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()
+ S.save_trajectory(np.asarray(ROWS, dtype=np.float64).reshape(-1, ADIM), os.path.join(DATA, "trajectory.npz"),
+ {"source": "standard-mode episode", "reason": E["reason"]})
+ L._write_json(os.path.join(DATA, "episode.json"), {**summary(), "live_sha": E["live_sha"]})
+ write_final()
+
+
+def ctrl_step(a, rec) -> bool:
+ """One executed control step (DexJoCo's own row), journaled. True when the call must stop here."""
+ a = np.asarray(a, dtype=np.float64)
+ running = S.step(a)
+ ROWS.append(a.copy())
+ stop = EP.journal(a)
+ rec.tick()
+ if not running:
+ finish(S.reason or "done")
+ 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 DEFAULT_CAMS
+ if not isinstance(cams, list) or any(c not in CAMS for c in cams):
+ raise ValueError(f"unknown cameras {cams}; cameras: {CAMS}")
+ return list(dict.fromkeys(cams))
+
+
+def meta_common(cams) -> dict:
+ n = ctrl_steps()
+ return {"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}}
+
+
+def _native_from_ee(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ """ee_pose rows are executed as sent (the recorded row is what the agent commanded); hand targets outside the
+ actuator ranges are clamped by MuJoCo itself (ctrllimited) and only reported."""
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ if float(np.linalg.norm(row[o + 3:o + 7])) < 1e-6:
+ raise ValueError(f"row {ri}: the {a} tcp quaternion has zero norm")
+ for j in range(16):
+ lo, hi = HLIM[a][j]
+ v = row[o + 7 + j]
+ if v < lo or v > hi:
+ clipped.append({"row": ri, "index": int(o + 7 + j), "reason": f"{EE_LAYOUT[o + 7 + j]} outside [{lo:.3f}, {hi:.3f}]: clamped by the simulator"})
+ return row
+
+
+def _clip_joints(row: np.ndarray, ri: int, clipped: list) -> np.ndarray:
+ lo = np.array([ALIM[j][0] for j in JP_LAYOUT]); hi = np.array([ALIM[j][1] for j in JP_LAYOUT])
+ out = np.clip(row, lo, hi)
+ for j in np.flatnonzero(out != row)[:20]:
+ clipped.append({"row": ri, "index": int(j), "reason": f"{JP_LAYOUT[j]} limit [{lo[j]:g}, {hi[j]:g}]"})
+ return out
+
+
+def _native_from_joints(q: np.ndarray) -> np.ndarray:
+ out = []
+ for k, a in enumerate(ARMS):
+ o = 23 * k
+ out += [tcp_from_arm_joints(a, q[o:o + 7]), q[o + 7:o + 23]]
+ return np.concatenate(out)
+
+
+def _check_chunk(typ: str, A: np.ndarray, dt: float, interp: str, video: str) -> int:
+ k = dt / DT
+ if A.ndim != 2 or A.shape[1] != ADIM:
+ raise ValueError(f"{typ} actions must be (T, {ADIM}), got {list(A.shape)}")
+ if A.shape[0] == 0:
+ raise ValueError("no rows")
+ 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")
+ return int(round(k))
+
+
+def do_submit(meta: dict, A: np.ndarray):
+ typ = meta.get("type")
+ if typ not in ("ee_pose", "joint_position"):
+ raise ValueError(f"type must be ee_pose or joint_position (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)
+ n = _check_chunk(typ, A, dt, interp, video)
+ clipped: list = []
+ if typ == "ee_pose":
+ A = np.stack([_native_from_ee(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ else:
+ A = np.stack([_clip_joints(np.asarray(r, dtype=np.float64), i, clipped) for i, r in enumerate(A)])
+ rec = recorder(cams, fps, meta)
+ E["calls"] += 1
+ step0, before = E["step"], ctrl_steps()
+ rec.tick(force=True)
+ if typ == "ee_pose":
+ prev = np.asarray(S.hold_action(), dtype=np.float64)
+ else:
+ prev = np.concatenate([np.concatenate([D.qpos[QADR[ARM_QI[a]]], S._arm_target(a)[7:23]]) for a in ARMS])
+ for row in A:
+ E["step"] += 1
+ stop = False
+ for s in range(1, n + 1):
+ if interp == "hold" or s == n:
+ target = row # a row's own values land exactly on its last control step
+ else:
+ target = prev + (row - prev) * (s / n)
+ if typ == "ee_pose":
+ for k in range(len(ARMS)):
+ o = 23 * k
+ target[o + 3:o + 7] = M.quat_slerp(prev[o + 3:o + 7], row[o + 3:o + 7], s / n)
+ native = target if typ == "ee_pose" else _native_from_joints(target)
+ if ctrl_step(native, rec):
+ stop = True
+ break
+ prev = row
+ 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"], "type": typ, "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 = np.asarray(S.hold_action(), dtype=np.float64)
+ 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={"task": TASK, "instance_sha": S.instance_sha, "instance_ok": bool(S.instance_exact), "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} DexJoCo sim ready ({TASK}; 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/dexjoco-water-plant-i00-standard/environment/sim/task_text.txt b/tasks/dexjoco-water-plant-i00-standard/environment/sim/task_text.txt
new file mode 100644
index 0000000000..abeb9cff53
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-standard/environment/sim/task_text.txt
@@ -0,0 +1,3 @@
+Pick up the spray bottle, point its nozzle at the potted plant and squeeze the trigger. Success: the trigger is held pulled (trigger joint > 0.34 rad; it counts as released again below 0.25 rad) while the nozzle reference point is within 0.20 m of the plant horizontally and within +-0.20 m of the plant's height AND the spray points at the plant, all three for 30 consecutive control steps (0.6 s). The spray leaves the spray head horizontally forward: perpendicular to the bottle's long axis, on the side the trigger faces (the bottle's local +z; its long axis, bottom to head, is local +y). It points at the plant when that direction is within 45 degrees of the line from the nozzle to the plant, e.g. with the bottle held upright and its trigger side facing the plant. Pulling the trigger while the nozzle is outside the zone ends the episode as a failure.
+
+The spray bottle stands on the table to the robot's right-front, the potted plant further along +y. The trigger is a hinge on the bottle's neck that the index and middle fingers can pull back.
diff --git a/tasks/dexjoco-water-plant-i00-standard/instruction.md b/tasks/dexjoco-water-plant-i00-standard/instruction.md
new file mode 100644
index 0000000000..b91273c334
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-standard/instruction.md
@@ -0,0 +1,68 @@
+# DexJoCo · water_plant — STANDARD MODE (robot as a service, eai-standard/2.2)
+
+You control a Franka Panda arm with a 16-DoF Allegro hand, **as if it were real hardware**: the simulator runs in a service you cannot open. You get
+one client and one episode. **Task:** Pick up the spray bottle, point its nozzle at the potted plant and squeeze the trigger. Success: the trigger is held pulled (trigger joint > 0.34 rad; it counts as released again below 0.25 rad) while the nozzle reference point is within 0.20 m of the plant horizontally and within +-0.20 m of the plant's height AND the spray points at the plant, all three for 30 consecutive control steps (0.6 s). The spray leaves the spray head horizontally forward: perpendicular to the bottle's long axis, on the side the trigger faces (the bottle's local +z; its long axis, bottom to head, is local +y). It points at the plant when that direction is within 45 degrees of the line from the nozzle to the plant, e.g. with the bottle held upright and its trigger side facing the plant. Pulling the trigger while the nozzle is outside the zone ends the episode as a failure.
+
+The spray bottle stands on the table to the robot's right-front, the potted plant further along +y. The trigger is a hinge on the bottle's neck that the index and middle fingers can pull back.
+
+## Rules (real-robot rules)
+- **No reset.** The episode starts when the service comes up and ends on success, on a task failure (see the task), when
+ your time is up, or on a simulator error. Knocked-over objects stay knocked over.
+- **No privileged state.** You see what the cameras see (RGB, and depth on request, with each camera's calibration) plus
+ the robot's own proprioception (joints, tcp poses, the current targets). No object poses, no success check:
+ `meta["done"]` / `meta["reason"]` tell you when the episode is over and why.
+- Steps are unlimited; your wall-clock budget (90 minutes) is the limit (`meta["time_left_s"]`). Actions and
+ simulated time are reported as cost. Do not stop before the task is solved.
+- There is nothing to hand in: the service records your episode as the trajectory and grades it. Leave your script at
+ `/app/output/gen.py` for the record (save it early, update it as you go).
+- **Nothing is put into your context automatically.** Images and videos come back as arrays/bytes in a Python object;
+ what you look at and where you store it is your code's decision.
+
+## Client (`/opt/tools/rcb_client.py`, protocol `eai-standard/2.2`)
+```python
+from rcb_client import Robot
+r = Robot() # connects (waits while the service starts)
+spec = r.spec() # action types, cameras (+ calibration), proprio layout, robot_spec, kinematics, budget
+obs = r.get_obs() # current frames of spec["default_cameras"]: obs.last[cam] -> uint8 (480, 640, 3)
+obs = r.get_obs(cameras=["front", "handcam_rgb"], depth=True) # + obs.last_depth[cam] -> float32 (480, 640) z-depth (m)
+obs.meta["proprio"] # {"layout": [...], "now": [...]}; obs.group("tcp_pose", now=True)
+obs.meta["cameras"] # per camera intrinsic_cv / extrinsic_cv / cam2world_gl for these frames
+obs = r.get_obs(seconds=2.0, video="mp4") # hold the current targets and watch for 2 s (max 30): obs.video[cam] = mp4 bytes
+
+res = r.submit("ee_pose", rows, dt=0.1) # rows: (T, 23) targets dt seconds apart, executed at 50 Hz with interpolation
+res = r.submit("joint_position", q_rows, dt=0.1) # (T, 23) joint targets instead (see below)
+res.meta["done"], res.meta["reason"], res.meta["clipped"], res.meta["control_steps_chunk"]
+res.video["front"]; res.last["front"]; res.proprio # mp4 of the chunk, last frame, float32 (N, P) proprio per frame
+res.save("/app/runs/003") # meta.json, <cam>.mp4, last/<cam>.jpg, proprio.npy, ...
+r.fk(q); r.ik({"tcp": pose}, seed=q) # kinematics of the robot (stateless: no physics, no time)
+r.status() # calls, control steps, done, reason, elapsed time
+```
+Cameras: `front`, `back`, `left`, `right`, `top0` (static), `handcam_rgb` (on the hand mount; they move,
+so use the calibration that comes with each response; `spec["cameras"][cam]["mount"]` gives the static pose or the mount
+link). Resolution 640x480. Rendering runs on the CPU: ask only for the cameras you need; `video="none"` makes a chunk
+fastest. If a call fails with a connection error the service may have crashed: it resumes the same episode;
+`r.wait_ready()`, then check `r.status()` (`spec["on_service_error"]`).
+
+### Action type `ee_pose` (23) — DexJoCo's own action
+tcp target position (3, metres, world frame), tcp target orientation (4, quaternion wxyz), 16
+Allegro joint targets (rad). The arm tracks the target through DexJoCo's operational-space controller (it lags a moving
+target and stops where contact blocks it); the hand joints are position-controlled. Rows are `dt` apart (a whole multiple
+of 1/50 s, at most 0.5 s); between rows positions and joints move linearly and orientations by slerp
+(`interpolate="linear"`) or jump (`"hold"`); a chunk may cover at most 10 s. Hand targets outside the ranges
+(`spec["action_types"]["ee_pose"]["hand_limits"]`) are clamped by the simulator and listed in `meta["clipped"]`. Build
+the next row from the `tcp_target` and `hand_target` proprio groups to move smoothly.
+
+### Action type `joint_position` (23)
+7 Panda joint targets, then the 16 Allegro joint targets (rad). The service turns the arm's targets
+into a tcp target by forward kinematics and the same controller tracks it: the tcp reaches FK(q), but the measured arm
+joints may differ from q in the arm's redundant direction (the controller's null space pulls towards a home posture).
+Out-of-limit values are clipped and reported.
+
+## Conventions
+- World frame, metres, z up; the robot stands at low x and reaches towards +x; each
+ arm's base pose is in `spec["robot_spec"]["base"]`. No other world coordinates are given (D7: the cameras are
+ calibrated, depth is available). Quaternions are **WXYZ**.
+- The tcp (`tcp`) is the hand's mounting flange (`spec["robot_spec"]["tcp"]`), not the fingertips. Allegro joint
+ order: index finger 0-3, middle 4-7, ring 8-11, thumb 12-15 (joint 0 of a finger = spread, 1-3 = flexion
+ from the knuckle out; thumb 12 = opposition).
+- Control runs at 50 Hz (10 physics substeps of 2 ms). There is no step budget: your wall-clock time is the limit.
diff --git a/tasks/dexjoco-water-plant-i00-standard/solution/oracle_stream.py b/tasks/dexjoco-water-plant-i00-standard/solution/oracle_stream.py
new file mode 100644
index 0000000000..19877300c1
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-standard/solution/oracle_stream.py
@@ -0,0 +1,43 @@
+"""Oracle (standard mode): streams the reference rows (the human demonstration's own actions, one per 1/50 s control step,
+float32-exact) as `ee_pose` 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
+
+A = np.load(os.path.join(os.path.dirname(os.path.abspath(__file__)), "oracle_trajectory.npz"))["actions"].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(A), flush=True)
+t0, i = time.time(), 0
+while i < len(A):
+ chunk = A[i:i + per_chunk]
+ try:
+ res = r.submit("ee_pose", chunk, dt=dt, interpolate="hold", 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/dexjoco-water-plant-i00-standard/solution/oracle_trajectory.npz b/tasks/dexjoco-water-plant-i00-standard/solution/oracle_trajectory.npz
new file mode 100644
index 0000000000..f1a414a0c2
Binary files /dev/null and b/tasks/dexjoco-water-plant-i00-standard/solution/oracle_trajectory.npz differ
diff --git a/tasks/dexjoco-water-plant-i00-standard/solution/solve.sh b/tasks/dexjoco-water-plant-i00-standard/solution/solve.sh
new file mode 100755
index 0000000000..1bd55d898f
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-standard/solution/solve.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+# Oracle (standard mode): streams the reference trajectory's rows (solution/oracle_trajectory.npz, one row per control
+# step) as `ee_pose` chunks through the client. Uses no privileged information at run time (only the pre-recorded rows);
+# the service's recorded trajectory is then exactly the privileged reference.
+set -e
+mkdir -p /app/output
+cp /solution/oracle_stream.py /app/output/gen.py
+python /solution/oracle_stream.py
diff --git a/tasks/dexjoco-water-plant-i00-standard/task.toml b/tasks/dexjoco-water-plant-i00-standard/task.toml
new file mode 100644
index 0000000000..47843b4509
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-standard/task.toml
@@ -0,0 +1,52 @@
+# Generated by scripts/dexjoco/generate.py -- edit the generator 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/dexjoco-water-plant-i00-standard"
+description = "STANDARD MODE (robot as a service, eai-standard/2.2): DexJoCo water_plant (a Franka Panda arm with a 16-DoF Allegro hand) on the same frozen instance as dexjoco-water-plant-i00-privileged. Pick up the spray bottle, point its nozzle at the potted plant and squeeze the trigger. The agent only gets a client: calibrated cameras (RGB, optional depth), the robot's joints and tcp poses, tcp-target + hand-joint chunks at 50 Hz, the robot's kinematics; one episode, no reset, no object state; the sim service records the episode, replays it in fresh processes and grades it."
+authors = [{ name = "Chi Gui" }]
+keywords = ["robotics", "dexjoco", "mujoco", "allegro", "dexterous-manipulation", "standard-mode", "robot-as-a-service", "water_plant"]
+
+[metadata]
+author_name = "Chi Gui"
+task_type = "trajectory"
+simulator = "dexjoco"
+robot = "franka-allegro"
+family = "water_plant"
+mode = "standard"
+protocol = "eai-standard/2.2"
+oracle = "full"
+expert_time_estimate_hours = 1.5
+
+[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 = 3600
+
+[agent]
+timeout_sec = 5400.0
+network_mode = "allowlist" # the reference demonstrations are public on Hugging Face (PROTOCOL §2.7)
+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 = 8192
diff --git a/tasks/dexjoco-water-plant-i00-standard/tests/Dockerfile b/tasks/dexjoco-water-plant-i00-standard/tests/Dockerfile
new file mode 100644
index 0000000000..26bc699ebe
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-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.sh
diff --git a/tasks/dexjoco-water-plant-i00-standard/tests/grade.py b/tasks/dexjoco-water-plant-i00-standard/tests/grade.py
new file mode 100644
index 0000000000..003b933315
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-standard/tests/grade.py
@@ -0,0 +1,60 @@
+"""Standard-mode verifier (DexJoCo): 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 frozen 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"))),
+ "task_failure": int(bool(d.get("task_failure"))),
+ "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),
+ "calls": int(d.get("calls") or 0),
+ "elapsed_s": float(d.get("elapsed_s") or 0),
+ "video_rendered": int(bool(d.get("video"))),
+ # 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 frozen 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/dexjoco-water-plant-i00-standard/tests/test.sh b/tasks/dexjoco-water-plant-i00-standard/tests/test.sh
new file mode 100755
index 0000000000..bc608aa8b9
--- /dev/null
+++ b/tasks/dexjoco-water-plant-i00-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