> ## 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.

# Writing a Bridge

> Serve a custom simulator with a RobotBridge subclass: the three hooks, the contract, grading, and running it spawned, remote, or in-process with RobotEndpoint.

When a simulator isn't gym-shaped, or you want control over grading, subclass `RobotBridge`. A bridge
implements three synchronous hooks and declares a contract; the base class serves the robot wire, the control
channel, the slots and the lockstep barrier.

## A bridge

This bridge is a gripper that tracks its commanded `(x, y)` exactly. It succeeds once `x >= 0.5` with the
gripper closed. Save it as `sim.py`:

```python sim.py theme={"dark"}
import numpy as np

from rua.sim import RobotBridge

CONTRACT = {
    "control_rate": 10,
    "features": {
        "observation/image": {"role": "observation", "type": "rgb"},
        "observation/state": {"role": "observation", "names": ["x", "y", "grip"]},
        "action": {
            "role": "action",
            "type": "ee_abs",
            "names": ["x", "y", "grip"],
            "stats": {"min": [-1.0, -1.0, 0.0], "max": [1.0, 1.0, 1.0]},
        },
    },
}


class PointArm(RobotBridge):
    """A gripper that tracks its commanded (x, y) exactly; success is x >= 0.5 with grip closed."""

    def __init__(self) -> None:
        super().__init__()
        self.contract = CONTRACT
        self.state = np.zeros(3)

    def reset(self, **task_args) -> str:
        self.state = np.zeros(3)
        self.success = False
        return "move x to 0.5, then close the gripper"

    def step(self, action) -> None:
        self.state = np.asarray(action[0], dtype=np.float64)  # [N, A] -> this env's row
        self.success = bool(self.state[0] >= 0.5 and self.state[2] >= 0.9)

    def get_observation(self):
        data = {
            "observation/image": np.zeros((1, 64, 64, 3), dtype=np.uint8),
            "observation/state": self.state[None].astype(np.float32),
        }
        return data, np.array([self.success])
```

The hooks always see a batch, even with one env:

| Hook | Receives / returns |
| - | - |
| `reset(**task_args) -> str` | The task args from `sim.reset(...)`, minus `max_ticks`. Returns the prompt. |
| `step(action)` | A float32 `[num_envs, A]` array: one row per slot, a hold row for any slot not acting. |
| `get_observation()` | `(data, terminated)`: a dict of `[num_envs, ...]` arrays and a `[num_envs]` bool array. Return `None` when there is nothing to observe yet. |

The bridge slices each slot's row out of `data` before sending it, so a client sees per-env arrays: an
`[H, W, 3]` frame and an `[A]` state.

## Grading

`sim.result()` calls the bridge's `result()`, on the sim thread so grading never races a step. The default
reads three attributes your hooks update:

```python theme={"dark"}
{"score": 1.0 if self.success else 0.0, "success": bool(self.success), "total_reward": float(self.total_reward)}
```

Override `result()` for richer grading; every key you return reaches the template. A vectorized bridge with
per-slot scores overrides `result_slots()` instead, returning one dict per slot. By default it repeats
`result()` for every slot.

`hold_action()` is the row a non-acting slot plays at the barrier: zeros, as wide as the action feature.
Override it when zero is not a safe action for your robot.

## Running it

A bridge reaches a HUD environment through a `RobotEndpoint`, which the environment's hooks start and stop.
There are three ways to build one.

### Spawned from the class

Pass the class (or an instance) and the endpoint runs `python -m rua.sim.bridge sim.py:PointArm` as a
child process, which it owns and terminates on `stop()`.

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

from rua.sim import RobotEndpoint
from sim import PointArm

env = Environment(name="arm")
sim = RobotEndpoint(PointArm).attach(env)


@env.initialize
async def up() -> None:
    await sim.start()
    for capability in await sim.capabilities():
        env.add_capability(capability)


@env.shutdown
async def down() -> None:
    await sim.stop()


@env.template()
async def reach(max_ticks: int | None = 200):
    ep = await sim.reset(max_ticks=max_ticks)
    yield {"prompt": ep["prompt"]}
    yield await sim.result()
```

The class must be defined at module level, since the child re-imports it by path. When you pass an instance,
its constructor arguments travel to the child as JSON: for each parameter of your `__init__`, the endpoint reads
the attribute of the same name (or with a leading underscore). Callables are skipped, and a value that isn't
JSON-serializable raises `TypeError`. `contract`, `metadata` and `num_envs` set on the instance after
construction travel too.

### Spawned from a command

`RobotEndpoint.spawn(cmd)` runs any command that serves a bridge and prints its control port as a
`HUD_SIM_PORT=<port>` line on stdout. Everything else the child prints passes through.

```python theme={"dark"}
sim = RobotEndpoint.spawn(["python", "-m", "rua.sim.bridge", "sim.py:PointArm"])
```

### Remote

`RobotEndpoint.remote(host, port)` attaches to a sim process something else runs, such as a GPU machine, and
leaves it running on `stop()`. Run the sim there with `python -m rua.sim.bridge sim.py:PointArm`, or
call `PointArm().serve(host=..., port=...)` yourself.

```python theme={"dark"}
sim = RobotEndpoint.remote("10.0.0.5", 7000)
```

> [!WARNING]
>
> The robot capability publishes the bridge's own WebSocket address, `ws://127.0.0.1:<port>` by default, and the
> control dials exactly that. A remote sim on another machine must bind its WebSocket to an address the env's
> process can reach (the `host=` argument of `RobotBridge.__init__`, which your subclass has to accept and forward). rua has
> no option to publish an address other than the one the bridge binds.

## The sim thread

`serve()` blocks: it runs the wire and control channel on a background thread while the calling thread
becomes the **sim thread**. Every hook (`reset`, `step`, `get_observation`, `result`) runs there, in order, so a
simulator that must own the main thread works. While serving, a hook must be synchronous; an `async def` hook
raises `TypeError`. If Omniverse Kit is loaded, the sim thread also pumps its app update between hooks.

## Episodes and the barrier

The base class runs the [slot protocol](https://docs.rua.hud.ai/start/concepts.md#slots-and-tokens) for you:

* The first claim when every slot is free calls your `reset` once for the whole batch.
* Each tick, `step` runs once every live, claimed slot has sent an action.
* A slot whose `terminated` is true, or that hit its `max_ticks`, drops out of the barrier; its peers keep
  stepping.
* A slot silent for `step_timeout` seconds (30 by default, a class attribute) is told it timed out, closed,
  and dropped.
* If `step` or `get_observation` raises, every connected slot receives the traceback and is closed.

## Serving extra capabilities

Override `capabilities(name)` to publish more than the robot wire, for example a tool server the sim process
runs. The endpoint publishes everything it returns:

```python theme={"dark"}
from hud.capabilities import Capability


class ToolArm(PointArm):
    async def capabilities(self, name: str = "robot"):
        tools = Capability.mcp(name="sim-tools", url="http://127.0.0.1:8040/mcp")  # your server
        return [*await super().capabilities(name), tools]
```

`metadata` is a dict sent as the first frame on every robot connection, for clients that want it.


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