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

# Sim

> Reference for rua.sim: RobotBridge, GymBridge, RobotEndpoint and attach_gym, with every hook, attribute, control call and default.

`rua.sim` serves a simulator. The guides are [Serving a gym env](https://docs.rua.hud.ai/guides/serving-a-gym-env.md) and
[Writing a bridge](https://docs.rua.hud.ai/guides/writing-a-bridge.md).

```python theme={"dark"}
from rua.sim import GymBridge, RobotBridge, RobotEndpoint, attach_gym
```

`DirectControl` has [its own page](https://docs.rua.hud.ai/reference/direct-control.md), and so has [`CodeControl`](https://docs.rua.hud.ai/reference/code-control).

## `RobotBridge`

```python theme={"dark"}
class RobotBridge(ABC):
    def __init__(self, *, host: str = "127.0.0.1", port: int = 0) -> None
```

Serves a sim over the `robot` WebSocket (`rua/0`) plus a JSON-RPC control channel. `host` and `port` are the
WebSocket's address; port `0` binds an ephemeral port on `start()`.

### Hooks

Every hook is synchronous and, under `serve()`, runs on the sim thread.

| Hook | Description |
| - | - |
| `reset(**kwargs) -> str` | Abstract. Reset the sim for a new episode; return the task prompt. Called once per batch, on the first claim while every slot is free. Never receives `max_ticks`. |
| `step(action)` | Abstract. Advance by one batched float32 action `[num_envs, A]`. |
| `get_observation()` | Abstract. Return `(data, terminated)`, with `[num_envs, ...]` arrays and a `[num_envs]` bool array, or `None` if not ready. |
| `result() -> dict` | The episode's score: `{"score": 1.0 if success else 0.0, "success": ..., "total_reward": ...}` from the attributes below. |
| `result_slots() -> list[dict]` | One score dict per slot. Default: `result()` copied to every slot. |
| `hold_action() -> ndarray` | The row a non-acting slot plays: zeros shaped like the action feature's `shape`, else as wide as its `names`, else `(1,)`. |

### Attributes

| Attribute | Type | Default | Description |
| - | - | - | - |
| `contract` | `dict` | `{}` | The [contract](https://docs.rua.hud.ai/reference/contract.md). Set it before serving. |
| `num_envs` | `int` | `1` | Slot count. |
| `metadata` | `dict` | `{}` | Sent, plus `"claim_required": True`, as the first frame on every robot connection. |
| `step_timeout` | `float` (class) | `30.0` | Seconds to wait for a claim frame, and for a silent slot's action before dropping it. |
| `success` | `bool` | `False` | Read by the default `result()`; reset before each batch reset. |
| `total_reward` | `float` | `0.0` | Read by the default `result()`; reset before each batch reset. |
| `task_description` | `str` | `""` | The prompt `reset` last returned. |
| `terminated` | `bool` | `False` | Reset before each batch reset; nothing in the base class reads it. |

### Methods

| Method | Description |
| - | - |
| `serve(*, host="127.0.0.1", port=0)` | Serve until SIGTERM or Ctrl-C, binding the control channel to `host:port` and printing `HUD_SIM_PORT=<port>`. Blocks; the calling thread becomes the sim thread. |
| `await start()` / `await stop()` | Bind / close the robot WebSocket and its tick loop. `start` is idempotent. |
| `await serve_control(host="127.0.0.1", port=0) -> asyncio.Server` | Serve the control channel only. |
| `url` (property) | The WebSocket's `ws://host:port`. Raises before `start()` binds an ephemeral port. |
| `await ensure_contract() -> dict` | The contract; `GymBridge` derives it on demand. |
| `await capabilities(name="robot") -> list[Capability]` | What the bridge serves: `[robot_capability(name=name, url=self.url, contract=...)]`. Override to add more. |

The control channel's methods, and the slot and barrier rules, are on the
[Capabilities](https://docs.rua.hud.ai/reference/capabilities.md#the-control-channel) page.

## `GymBridge`

```python theme={"dark"}
GymBridge(target: Any, *, fps: int | None = None, contract: str | Path | None = "contract.json", **defaults: Any)
```

A `RobotBridge` that serves any gym-style env. `attach_gym` runs it in a sim process.

| Argument | Description |
| - | - |
| `target` | A factory, a gymnasium registry id, or an `EnvSpec` as JSON (a string starting with `{`). |
| `fps` | Control-rate override. |
| `contract` | Path of the contract file to load or write. `None` derives it in memory. |
| `**defaults` | Task-arg defaults. `host` and `port` are popped and passed to `RobotBridge.__init__`. |

Build args (the factory's named parameters, plus `defaults`' keys when it takes `**kwargs`; only `num_envs` for
a registry target) rebuild the env when they change. Other task args are episodic: `seed` goes to
`env.reset(seed=...)` and the rest to `env.reset(options=...)`. A registry target with `num_envs` is built with
`gymnasium.make_vec`, else `gymnasium.make`.

| Behavior | Rule |
| - | - |
| Batched | The env (or its `unwrapped`) has `num_envs`, or is a gymnasium `VectorEnv`. |
| Prompt | First non-empty `unwrapped.cfg.task_description`, `unwrapped.cfg.instruction`, `unwrapped.task_description`, `unwrapped.instruction`; else `k=v, ...` of the task args; else `"run the task"`. |
| Cameras | Flattened leaves of rank 3 (4 batched) with last dim 1, 3 or 4. |
| State | Flattened numeric leaves of rank ≤ 1 (≤ 2 batched). Other leaves are dropped. |
| Reward on the wire | The last step's reward, as a `reward` entry in each observation. |
| Actions | Reshaped to `action_space.shape`; cast to an integer space's dtype; a torch tensor on `unwrapped.device` when observations were torch. |
| Success | `info["success"]`, `info["is_success"]` or `info["task_success"]`; else Isaac Lab's `termination_manager.get_term("success")`. |
| Grade per slot | `score` is success when any success signal was seen this episode, else the summed reward; plus `success` and `total_reward`. |
| Control rate | `fps`, else the contract's `control_rate`, else `metadata["render_fps"]`, else `1 / unwrapped.step_dt`, else 10. |

`start()` builds the env once to derive the contract when no contract file exists, and raises `RuntimeError`
when a build arg has no default anywhere. `sample_observation()` returns one per-env `(state, frames)` sample.

## `attach_gym`

```python theme={"dark"}
attach_gym(env: hud.Environment, target: Any, *, name: str = "robot", **kwargs: Any) -> RobotEndpoint
```

Serves `target` as the capability `name` on `env`. It builds a spawning `RobotEndpoint` for
`python -m rua.sim.gym ...`, calls `endpoint.attach(env)`, and registers an `@env.initialize` hook that
starts it and publishes every capability it reports, and an `@env.shutdown` hook that stops it.

| `kwargs` key | Description |
| - | - |
| `fps` | Control-rate override. |
| `contract` | Contract file path, default `"contract.json"`; `None` for none. |
| `bridge` | A `GymBridge` subclass, passed to the sim process by source path. |
| anything else | A task-arg default (for example `num_envs=8`), JSON-encoded on the command line. |

`target` may be a module-level callable (passed as `path.py:name`), a registry id, or a constructed registry env
(passed as its spec JSON and closed). Anything else raises `ValueError`.

## `RobotEndpoint`

```python theme={"dark"}
RobotEndpoint(
    bridge: type[RobotBridge] | RobotBridge | None = None,
    *,
    cmd: Sequence[str] | None = None,
    host: str | None = None,
    port: int | None = None,
    connect_timeout_s: float = 900.0,
)
```

The env server's handle on a sim process.

| Construction | Mode |
| - | - |
| `RobotEndpoint(BridgeClass)` or `RobotEndpoint(instance)` | Spawns `python -m rua.sim.bridge <file>:<Class> [--init JSON]`. The class must be module-level. |
| `RobotEndpoint.spawn(cmd, *, connect_timeout_s=900.0)` | Spawns `cmd`, which must print `HUD_SIM_PORT=<port>`. |
| `RobotEndpoint.remote(host, port, *, connect_timeout_s=900.0)` | Attaches to a running sim's control channel. |

For an instance, constructor parameters of the subclass (not `host` / `port`) are read back from attributes of
the same name or with a leading underscore and sent as JSON. Callables are skipped; values that don't serialize
raise `TypeError`. `contract`, `metadata` and `num_envs` (when not 1) are sent too.

| Method | Description |
| - | - |
| `attach(env) -> RobotEndpoint` | Register `release_claim` as an `@env.task_teardown` hook. Returns the endpoint. |
| `add_direct_control(control)` | Serve a `DirectControl` beside the wire. `DirectControl.attach` calls this. |
| `await start()` | Spawn the sim (spawned modes), read its port, and connect, retrying every 2 s for up to `connect_timeout_s`. A failed start stops the child. |
| `await stop()` | Stop direct controls, free any slots still claimed, close the link, and terminate the sim's process group when this endpoint spawned it. |
| `await url() -> str` | The bridge's WebSocket address. |
| `await contract() -> dict` | The bridge's contract. |
| `await capabilities(name="robot") -> list[Capability]` | The bridge's capabilities, plus one `mcp` capability per attached `DirectControl`. |
| `await reset(**task_args) -> dict` | Claim a slot: `{"prompt": str, "token": str}`. Retries every 50 ms while every slot is taken. `max_ticks` must be a positive `int`. |
| `await result(*, token=None, **extra) -> dict` | Grade and free the slot, merged with `extra`. `token` may be omitted with one claimed slot. |
| `await release_claim()` | Free the current task session's slot if `result` never ran; up to 3 attempts of 10 s each. |

Spawned sims inherit stderr; their stdout is forwarded line by line.


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