> ## Documentation Index
> Fetch the complete documentation index at: https://docs.rua.hud.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Serving a Gym Env

> Serve any gym-style simulator as a HUD robot environment with attach_gym: targets, build and episodic args, contract files, grading, Direct Control, and vectorized envs.

`attach_gym` turns any gym-style env into a HUD environment's `robot` capability. It needs nothing from the
env beyond `reset`, `step` and `close`: rua probes the observation and action shapes, derives a contract, runs
the env in its own sim process, and grades each episode from what the env reports.
To let an LLM drive the env with the `move` tool, see [Drive it with Direct Control](#drive-it-with-direct-control).

```python sim.py theme={"dark"}
import gymnasium as gym
import numpy as np
from gymnasium import spaces


class Reach(gym.Env):
    metadata = {"render_fps": 10}

    def __init__(self, goal: float = 0.5):
        self.goal = goal
        self.observation_space = spaces.Box(-1.0, 1.0, (2,), np.float32)
        self.action_space = spaces.Box(-1.0, 1.0, (1,), np.float32)
        self.x = 0.0

    def reset(self, *, seed=None, options=None):
        super().reset(seed=seed)
        self.x = 0.0
        return np.array([self.x, self.goal], np.float32), {}

    def step(self, action):
        self.x = float(np.clip(action[0], -1.0, 1.0))
        reached = abs(self.x - self.goal) < 0.05
        obs = np.array([self.x, self.goal], np.float32)
        return obs, -abs(self.x - self.goal), reached, False, {"success": reached}


def make_env(goal: float = 0.5):
    return Reach(goal)
```

```python env.py theme={"dark"}
from hud import Environment

from rua.sim import attach_gym
from sim import make_env

env = Environment(name="reach")
sim = attach_gym(env, make_env)


@env.template()
async def reach(goal: float = 0.5, seed: int = 0):
    ep = await sim.reset(goal=goal, seed=seed)
    yield {"prompt": ep["prompt"]}
    yield await sim.result()
```

`attach_gym` returns the [`RobotEndpoint`](https://docs.rua.hud.ai/reference/sim#robotendpoint) and registers its lifecycle on
the environment: the sim process starts in `@env.initialize` and publishes its capabilities, stops in
`@env.shutdown`, and a task that ends without calling `sim.result()` has its slot freed in
`@env.task_teardown`. Nothing runs until the environment serves.

## Choosing a target

The second argument says how the sim process builds the env. Only text crosses into that process, so each
kind is reduced to something it can rebuild:

| Target | Example | Crosses as |
| - | - | - |
| A module-level factory | `attach_gym(env, make_env)` | Its source path, `sim.py:make_env` |
| A gymnasium registry id | `attach_gym(env, "CartPole-v1")` | The id |
| A constructed registry env | `attach_gym(env, gym.make("CartPole-v1"))` | Its `EnvSpec` as JSON; the instance is closed |

A lambda, a nested function, or an env that wasn't made from the registry raises `ValueError`.

## Build args and episodic args

Each key the template passes to `sim.reset(...)` is one of two kinds:

* **Build args** are the factory's own parameters (`goal` in `make_env` above). When one changes, the sim closes
  the env and builds a new one. For a registry target, the only build arg is `num_envs`.
* **Episodic args** are everything else. `seed` goes to `env.reset(seed=...)`, and the rest go to
  `env.reset(options={...})`.

Extra keyword arguments to `attach_gym` are defaults that fill in task args a task leaves out. A factory
that takes `**kwargs` treats those defaults as build args too.

```python theme={"dark"}
sim = attach_gym(env, make_env, num_envs=8, robot="panda")
```

A factory parameter with no default, and no `attach_gym` default either, raises at start: the sim must build
the env once to derive the contract, and nothing could supply that value yet. Give it a default, pass it to
`attach_gym`, or pre-write the contract file.

## The prompt

`sim.reset(...)` returns the env's instruction as the prompt. The sim looks for a non-empty string at
`unwrapped.cfg.task_description`, `unwrapped.cfg.instruction`, `unwrapped.task_description` or
`unwrapped.instruction`, in that order. Without one, the prompt lists the task args (`goal=0.5, seed=0`), or
reads `run the task` when there are none.

## Observations and actions

The sim flattens a nested dict observation into slash-separated keys (`{"obs": {"cam": ...}}` becomes
`obs/cam`) and sorts each leaf by shape:

| Leaf | Becomes |
| - | - |
| Channel-last image: rank 3 (rank 4 when batched), last dim 1, 3 or 4 | A camera |
| Numeric, rank 1 or less (rank 2 or less when batched) | State |
| Anything else | Dropped |

A non-dict observation becomes a single state feature named `obs`. The last step's reward also rides along
as a `reward` entry, which `RobotClient` lifts out next to `terminated`.

Actions arrive as flat float32 rows. The sim reshapes each to the env's `action_space.shape`, casts to the
space's dtype when that is an integer type, and converts to a torch tensor on the env's `device` when the env
returned torch observations.

## The contract file

`contract` defaults to `"contract.json"`, resolved against the sim process's working directory. When the file
exists, the sim loads it and skips the probe. When it doesn't, the sim builds the env once, derives a minimal
contract from a sample observation, and writes it there:

```json contract.json theme={"dark"}
{
  "control_rate": 10,
  "features": {
    "obs": {"role": "observation", "names": ["obs_0", "obs_1"]},
    "action": {"role": "action", "names": ["act_0"]}
  }
}
```

Each observation feature takes its leaf's name (`obs` for a non-dict observation, or `state`, `cam/front` and so
on for a dict). Edit `names` to relabel the trace's plots; the file always wins over the probe. Pass an absolute path to keep
it next to your env, or `contract=None` to derive it in memory without writing.

```python theme={"dark"}
from pathlib import Path

sim = attach_gym(env, make_env, contract=str(Path(__file__).parent / "contract.json"))
```

The control rate comes from `fps=` when given, then the contract's `control_rate`, then the env's
`metadata["render_fps"]`, then Isaac's `step_dt`, and defaults to 10 Hz.

## Grading

`sim.result()` returns one dict per episode:

```python theme={"dark"}
{"score": 1.0, "success": True, "total_reward": -1.0}
```

* `success` is whether the env reported success when the episode finished. The sim reads the first of
  `info["success"]`, `info["is_success"]` or `info["task_success"]` that is set, and falls back to an Isaac Lab
  env's `termination_manager.get_term("success")`.
* `total_reward` sums the env's rewards until the episode finished.
* `score` is `success` as `1.0` or `0.0` when the env has reported a success signal this episode, and
  `total_reward` otherwise.

With `max_ticks`, the dict also carries `max_ticks`, and `"ended_by": "max_ticks"` when the cap ended it.
Extra keyword arguments to `sim.result(...)` are merged in.

## Drive it with Direct Control

`attach_gym` on its own serves only the `robot` wire. To let an LLM move the env with the `move` tool, add
[`DirectControl`](https://docs.rua.hud.ai/interfaces/direct-control). It needs to know what the env's action means, and a gym
`action_space` gives only a shape and bounds. That meaning lives in the contract, and the contract `attach_gym`
derives leaves it out, so you write the file yourself. This one is complete for the `Reach` env above:

```json contract.json theme={"dark"}
{
  "control_rate": 10,
  "features": {
    "obs": {"role": "observation", "names": ["x", "goal"]},
    "action": {
      "role": "action",
      "type": "ee_abs",
      "names": ["x"],
      "stats": {"min": [-1.0], "max": [1.0]}
    }
  }
}
```

An existing `contract.json` always wins over the probe, so `attach_gym` serves it as written.

### The contract's fields

| Field | What it says | Why direct control needs it |
| - | - | - |
| `control_rate` | Control ticks per second. Use the rate the env is stepped at. | Paces each `move` and times the trace. |
| `features.obs` | The observation, named as the sim names it: `obs` for a non-dict observation, the leaf's name for a dict. `names` labels each value. | Tells `state=` (below) which arrays exist. |
| `action.type` | What an action value is: `ee_abs` for the absolute position of the end effector, `ee_del` for a change in it per step, or `joint_pos` for joint positions. | A `move` is a path of poses. Direct control turns it into rows of actions, and only the type says how. Without it, `ContractEmbodiment` raises `a contract embodiment serves the action kinds [...], not None`. |
| `action.names` | One name per action column, in order. `x`, `y` and `z` are the hand's position, and a name containing `grip` the gripper. Rotation is a block of adjacent names: a quaternion `<stem>.qx`, `.qy`, `.qz`, `.qw`, or `<stem>_euler.x`, `.y`, `.z`, `<stem>_rotvec.rx`, `.ry`, `.rz` or `<stem>_axis_angle.rx`, `.ry`, `.rz`. A call then sets it as `roll`, `pitch` and `yaw`. | These become the dimensions an agent names in a `move`: the arm's `x` here, so `{"arm": {"x": 0.5}}`. A name that is none of these, such as the derived `act_0` or a bare `roll`, raises `no standard dimension`. Positions are metres in the robot's base frame, so the env's action should be in metres. |
| `action.stats` | `min` and `max`, one value per action column. | Sets each dimension's range. A call that names a value outside it, such as `"x": 2.0` here, is refused with the maximum, and nothing moves. Without `stats` (or `limits`, which wins when both are given), `ContractEmbodiment` raises `KeyError: 'stats'`. |

Speed limits are not in the contract. You give them to `ContractEmbodiment` as `max_speed`, by quantity:
`position` in metres per second, plus `rotation` and `grip` when the action has those columns and `joint` for a
`joint_pos` action. Set each to the fastest the env's controller can follow. A call that would move faster is
vetoed with the time it needs, and a missing quantity raises `max_speed needs ['position']`. `Reach` jumps to
whatever it is told, so `0.5` here only bounds how fast the agent may move.

### The `state=` mapping

Each tick, `ContractEmbodiment` needs the robot's current pose, in the same layout as the action: here one value,
`x`. By default it takes the one observation that is as wide as the action. `Reach` observes `[x, goal]`, two
values for a one-value action, so none qualifies and it raises
`no single observation is as wide as the action (1): pass state=...`. Pass `state=` a function from the
observation dict (arrays by feature name, from the contract) to that pose. Here `lambda obs: obs["obs"][:1]`
keeps `x` and drops `goal`.

### The environment and the call

```python env.py theme={"dark"}
import json
import math
from pathlib import Path

from hud import Environment

from rua.direct import DirectControl
from rua.embodiments.contract import ContractEmbodiment
from rua.sim import attach_gym
from sim import make_env

contract = Path(__file__).parent / "contract.json"
env = Environment(name="reach")
sim = attach_gym(env, make_env, contract=str(contract))
embodiment = ContractEmbodiment(
    json.loads(contract.read_text()),
    state=lambda obs: obs["obs"][:1],
    max_speed={"position": 0.5},
)
DirectControl(embodiment).attach(sim)


@env.template()
async def reach(goal: float = 0.5, seed: int = 0):
    ep = await sim.reset(goal=goal, seed=seed)
    yield {"prompt": ep["prompt"]}
    yield await sim.result()
```

An agent opens the `control` capability and calls `move`:

```python run.py theme={"dark"}
import asyncio

from hud import Task
from hud.agents.base import Agent
from hud.eval.run import rollout
from hud.runtime import LocalRuntime


class Scripted(Agent):
    async def __call__(self, run):
        control = await run.client.open("control")
        move = {"keyframes": [{"t": 2.0, "arm": {"x": 0.5}}], "note": "reach the goal"}
        result = await control.call_tool("move", move)
        print(result.content[0].text)
        run.trace.content = "done"


async def main():
    task = Task(env="reach", id="reach")
    trace = await rollout(task, Scripted(), runtime=LocalRuntime("env.py"))
    print("reward:", trace.reward)


asyncio.run(main())
```

```text theme={"dark"}
{"status": "ended", "elapsed_s": 1.7, "steps": 17, "parts": {"arm": {"frame": "base", "pose": {"x": 0.4696}, "gap": {"pos_mm": 30.4}}}}
[env] result: success=True total_reward=-4.732
reward: 1.0
```

The `Reach` env ends the episode within 0.05 of the goal, so the move stops at `0.4696`. A call that moves too
fast, such as `"t": 1.0` here, is vetoed with the time it needs. Direct control holds one connection without a
token, so it drives a single env, not a [vectorized](#vectorized-envs) one.

## Vectorized envs

An env that exposes `num_envs` (or is a gymnasium `VectorEnv`) is **batched**: every array carries a leading
`[N]` dimension, and the sim serves one slot per env. Add a factory to `sim.py` with a `num_envs` parameter that
returns a `VectorEnv`, and pass `num_envs` as a default:

```python sim.py theme={"dark"}
def make_vec_env(goal: float = 0.5, num_envs: int = 1):
    return gym.vector.SyncVectorEnv([lambda: Reach(goal) for _ in range(num_envs)])
```

```python env.py theme={"dark"}
from hud import Environment

from rua.sim import attach_gym
from sim import make_vec_env

env = Environment(name="reach-vec")
sim = attach_gym(env, make_vec_env, num_envs=2)


@env.template()
async def reach(goal: float = 0.5):
    ep = await sim.reset(goal=goal)
    yield {"prompt": ep["prompt"], "bindings": {"robot": {"token": ep["token"]}}}
    yield await sim.result(token=ep["token"])
```

Two things change from the single-env template:

* The **token** goes to the client through `bindings`, so its connection drives its own slot, and to
  `sim.result(token=...)`, so the right slot is graded.
* Concurrent episodes must share **one environment placement** to share the sim. Run them with HUD's
  `Shared` runtime, at most `num_envs` wide:

```python theme={"dark"}
from hud import Task, Taskset
from hud.runtime import LocalRuntime, Shared

job = await Taskset("reach-vec", [Task(env="reach-vec", id="reach")]).run(
    agent,
    runtime=Shared(LocalRuntime("env.py"), width=2),
    group=2,
    max_concurrent=2,
)
print([trace.reward for trace in job.traces])  # [1.0, 1.0]
```

`agent` is any HUD agent that opens the `robot` capability and drives its slot with `RobotClient`. Direct control and code control hold one connection without a token, so they drive single-env sims.

All slots in a batch share one reset, so concurrent claims must pass identical task args; a claim with
different args raises `ValueError`. When no slot can be claimed, `sim.reset` retries until one can; a freed
slot only becomes claimable again once every slot in the batch is free.

When an env reports a finished episode's last frame in `info["final_obs"]` (Isaac Lab, or gymnasium's
same-step autoreset), the sim serves that frame for the finished rows instead of the post-reset one.

## Serving more than the wire

`bridge=` swaps in a `GymBridge` subclass by source path, for a sim process that serves more than the robot
wire. Every capability the bridge returns from `capabilities()` is published next to `robot`, such as an MCP
tool server running in the sim process. See [Writing a bridge](https://docs.rua.hud.ai/guides/writing-a-bridge.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.