# Imported robot motions

Lucky Engine Web can run prepared **mjlab fused G1 policies** with ONNX Runtime in its physics worker. The policy reads the simulated robot state and drives its actuators; this is physical policy execution, not animation playback.

Application: https://web.luckyrobots.com. Feature preview (`codex/mjlab-policy-import`):
https://codex-mjlab-policy-import-lucky-engine-web-team.dvrmysr.workers.dev

This native Worker Preview uses the existing main Worker and the existing
preview D1/R2 resources. It shares those preview accounts/projects with other
previews; it does not change production code or production storage. Sign in with
your preview account, or register and use the existing approval flow.

## Try the included G1 motion

1. Sign in and find **G1 learned motion** under **Your projects**, or search for G1 in **Community projects**. The official starter is authored by Lucky Robots.
2. Click its card to read the description, then **Open** to create your own attributed copy with the compatible Unitree G1, its trained aiming policy and a scene camera. The inner **Project contents** panel shows only the scene, robots, camera and scripts in the open project; project browsing and starter discovery happen in the outer library.
3. Select **Unitree G1** in the hierarchy and open the **Inspector** tab. Its **Learned motions** section shows the attached policy.
4. Press **Play**. The robot performs a two-second aiming stance and pivot. Playback stops at the end of the reference. **Reset** restores the exact entry pose, velocities and policy clock.
5. Press **Record scene** to collect a fresh run. Choose the existing HD/photographic options as needed; slower rendering waits without skipping policy steps.
6. Download the dataset or MP4. **Save scene** includes both the robot and attached ONNX model, so reopening the ZIP on another browser restores the controller.

“Reference finished” means the reference clip ended. It is not a successful task assessment. The included motion is not a velocity-controlled walker, a jump policy or a validated transition from arbitrary poses.

## Import your own supported policy

Select a compatible robot, then use **Learned motions → Import ONNX / policy ZIP**. Choose a prepared fused `.onnx`, or a ZIP containing exactly one supported fused model. The library can retain several motions; select one and click **Attach motion**. Disable or detach it before using joint sliders, scripts or another controller on that robot.

The importer does not infer missing controller settings from an arbitrary ONNX file. The prepared export must state its observation layout, joint order, action scales, PD gains, initial velocities, reference duration and physics/control rate. Attachment checks the compiled robot's named joints, native position actuators and limits. It rejects mismatches rather than silently changing the robot.

The first contract supports:

- A floating-base G1 with 29 controlled joints and the expected pelvis IMU site/torso reference.
- Float32 `[1,101]` fused input and 29 raw actions, with embedded reference outputs.
- Model-internal normalization; no external history stack, recurrent state or inferred clipping.
- Explicit 2 ms or 5 ms physics step and an integral number of physics steps per policy action.
- Frame-zero root/joint pose and velocities. Placement translation and yaw are applied consistently to initial state and observations.

The supplied example uses 5 ms MuJoCo steps and 50 Hz policy inference: four physical steps per action. Because timestep is a scene setting, policies sharing a scene must agree on it.

## Prepare an mjlab export

`scripts/prepare-mjlab-policy.py` makes a metadata-only derivative of an existing fused ONNX graph, plus a robot-only MJCF ZIP. It does not train a policy, change weights, or convert reference animation into a trained controller.

```bash
python scripts/prepare-mjlab-policy.py \
  --model aiming.onnx \
  --controller controller.full-precision.json \
  --initial-state initial-state.json \
  --scene robot/scene.xml \
  --output-model aiming.web.onnx \
  --output-robot g1-policy-robot.zip \
  --report web-transport.json
```

Run this in a Python environment with `onnx` installed (the existing mjlab environment works). Use the **saved training run's** nominal robot and full-precision controller configuration, not an unrelated G1 asset or rounded catalog gains. `controller.full-precision.json` contains joint_names, default_joint_pos, action_scale, kp, kd, armature, effort, physics_dt, policy_hz, decimation and source_sha256. `initial-state.json` contains joint_names, qpos, qvel, last_action and time_s. The checked-in numeric baseline describes the included example and its provenance in [MJLAB-POLICY-BASELINE.md](MJLAB-POLICY-BASELINE.md).

Import the generated robot ZIP through the robot importer, select that robot, and import its prepared ONNX. Legacy fused models missing `physics_dt` or `initial_qvel` need preparation first; bare actors with a different observation contract are rejected.

## Local agents: HTTP and MCP

The same registered operations are available through `/api/v1/execute` and the existing MCP interface. Authenticate with an app API key, create/connect a browser runtime, and use the current runtime generation/revision and a unique idempotency key for mutations. The connection guide at `/agents` documents that flow.

1. Upload policy bytes to `/api/v1/artifacts` using a Bearer app API key.
2. `asset.import` with `{ "artifactId": "…", "kind": "motion", "name": "aiming.web.onnx" }` returns a content-addressed `assetId` and validated contract.
3. `motion.list` returns stored motion names, IDs and contracts.
4. `motion.attach` with `{ "robotId": "…", "assetId": "…", "enabled": true }` binds the policy and reloads physics. Use `assetId: null` to detach.
5. Use `simulation.command` to play, pause, step or reset. `runtime.inspect` includes each motion's state, reference frame, model hash and last observations/actions.
6. `recording.run` records the physical rollout. `project.save` persists the portable policy with the project.

Importing the complete included `.lucky.zip` with `asset.import` kind `project` is the quickest agent test. No paid model call is needed to execute the imported policy.

## Recording and validation

Inference is awaited at its fixed physics tick in both Play and Record. Recording retains every applied MuJoCo control vector, each policy inference's input/output/hash/tick, and the initial qpos/qvel/act state. RGB, depth, segmentation and action/state rows share the existing 30 fps schedule. Sensor times lie on that frame grid; physical states are sampled at `ceil(frame * physics_hz / 30)` and carry their actual physical time.

Raw-control replay bypasses policy inference and restores the recorded initial state. Ending a clip does not set episode success. Incompatible models, non-finite outputs, clock discontinuities and detected falls stop execution with an error.

Runtime topology changes (spawning bodies or changing physics components) invalidate an active motion's compiled robot binding. Reset restores the authored scene, revalidates the binding and restores the exact policy entry state. Continuing a motion across a mid-episode model rebuild is unsupported.

`npm run test:motions` checks real CPU/WASM inference and physical rollout
parity, incompatible-model failures, timing, portable assets and exact
raw-control replay. `npm run build:agent && npm run test:motions-ui` exercises
standalone ONNX import, Play/Reset, cloud and ZIP saves, authenticated agent
import/attachment/stepping, and an actual browser H.264 recording. The browser
test records 61 frames at 256×256/30 fps and checks all 100 recorded inference
outputs against the CPU reference; it does not benchmark HD rendering speed.

This first integration does **not** implement arbitrary ONNX adapters, generic velocity commands, a locomotion/jump catalog, automatic policy blending, recovery controllers, or training inside the web application. Additional trained mjlab motions can use this path when their robot and export contract match; each still needs physical validation.
