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

# Code Control

> Let an agent control a robot by writing Python: one kernel per episode, and the same checked moves as direct control.

In code control, the agent writes Python. Each piece of code runs as a **cell** in a kernel that lives for the whole episode, and the code moves the robot with `robot.move`. That call takes the same keyframes as the `move` tool of [Direct Control](https://docs.rua.hud.ai/interfaces/direct-control.md) and runs the same checks. Between moves the code can loop, branch, compute and look at images. No trained robot policy sits in between. The examples use one arm on a table.

## One cell, then a look

Each call runs one cell. The reply has what the cell printed, its error if it raised, the value of its last expression, and the state of every part. Images come back only when the cell asks for one with `show`. The agent reads the reply, then writes the next cell.

## Two tools

| Tool | What it does |
| - | - |
| `python(code, note)` | Runs one cell in the episode's kernel. |
| `view_image(path)` | Shows an image the kernel saved, by its path. |

`done` and `hindsight` are direct control's own tools and work the same way. By default there is no `move` tool, and the agent moves the robot from inside a cell. With the `hybrid` setting on, the `move` tool of Direct Control is served beside `python`. See [Moves and code in one episode](#moves-and-code-in-one-episode).

## A kernel that lasts the episode

Names, imports, threads and files in the working directory carry over from one cell to the next, so the agent can set up a helper once and use it for the rest of the episode. A new episode gets a new kernel and an empty working directory. Nothing carries over between episodes.

Three names are ready in every cell: `robot`, `np` (numpy) and `show`. The agent may import anything installed in the env. The system prompt documents every call the settings serve and gives the robot's parts and ranges. The same manual is in a `MANUAL.md` file in the working directory.

## What the code can call

| Call | What it does |
| - | - |
| `robot.spec` | The robot's parts with their ranges, units and frames, as the `move` tool states them. |
| `robot.observe()` | The robot's state and every camera, now. It plays nothing. |
| `robot.move(keyframes)` | Moves the robot and returns when the motion has ended, with a `MoveResult`. |
| `robot.preview(keyframes)` | Checks keyframes as `robot.move` would and moves nothing, with a `Preview`. |
| `show(image)` | Puts an image in the reply and saves it as `images/NNN.png`. |

`robot.move` takes what `move` takes. Each keyframe has a time `t` in seconds from the start of the call and names the parts it moves, in metres and degrees, in the robot's base frame. The result has the call's `status`, `elapsed_s`, `steps`, and each part's measured state, with its `gap` to the target for the parts the call named.

```python theme={"dark"}
view = robot.observe()
show(view.cameras["front"], "before")

result = robot.move([{"t": 3.0, "arm": {"x": 0.35, "z": 0.15}}])
print(result.arm["gap"])
```

## A move is checked like a direct control move

A move that is malformed or asks for something the robot cannot do raises, and the robot does not move. `robot.Refused` means the call is outside what the spec allows. `robot.Vetoed` means the robot cannot do the motion as asked, such as one that is too fast, and its `min_duration_s` is the least time the call needs. Both carry the same reason text that direct control gives. The code can catch the error and try again, or let it end the cell and let the agent read it.

```python theme={"dark"}
try:
    robot.move([{"t": 0.05, "arm": {"z": 0.15}}])
except robot.Vetoed as veto:
    print(veto.reason)
    robot.move([{"t": veto.min_duration_s * 1.5, "arm": {"z": 0.15}}])
```

A retry with more time fixes a speed veto and not a joint limit or a pose out of reach. A cell can read the reason before it decides.

## Checking a move first

`robot.preview(keyframes)` asks the question `robot.move` would answer, from where the robot is now, and plays nothing. The robot, the episode and the values a part holds stay as they are. A refusal or a veto does not raise: it comes back as `ok=False`, with the reason and, for a speed veto, the `min_duration_s` that fixes it. When it is `ok`, the preview also has the planned `steps` and `duration_s`, the planned `end` value of each part, and the `path` of every tick.

```python theme={"dark"}
frames = [{"t": 0.05, "arm": {"z": 0.15}}]
plan = robot.preview(frames)
if not plan.ok and plan.min_duration_s:
    frames[0]["t"] = plan.min_duration_s * 1.5
    plan = robot.preview(frames)
print(plan.ok, plan.steps, plan.duration_s)
print(plan.end)
if plan.ok:
    robot.move(frames)
```

```text theme={"dark"}
True 3 0.2
{'arm': {'x': 0.3, 'y': 0.0, 'z': 0.15, 'roll': 180.0, 'pitch': 0.0, 'yaw': 0.0}, 'gripper': {'grip': 0.0}}
```

The first preview was vetoed, because 0.05 s is too fast for a 0.3 m rise. The second plays three ticks, 0.2 s. Previews are cheap: they spend no simulated time. Use them to try a few timings before one `robot.move`. A preview does not remember the last one, so every preview starts from the state now, not from the end of the one before.

## An example

The agent below lifts a cube in three cells, as a scripted run does on a sim. The first looks, the second moves above the cube, and the third lowers the hand, closes the gripper and lifts.

```python theme={"dark"}
# cell 1
view = robot.observe()
show(view.cameras["front"], "before")
view.state["arm"]["pose"]
```

```python theme={"dark"}
# cell 2
robot.move([{"t": 3.0, "arm": {"x": 0.35, "y": 0.0, "z": 0.15,
                               "roll": 180, "pitch": 0, "yaw": 0}, "gripper": 0.0}])
```

```python theme={"dark"}
# cell 3
robot.move([{"t": 2.0, "arm": {"z": 0.02}}])
robot.move([{"t": 1.0, "gripper": 1.0}])
robot.move([{"t": 2.0, "arm": {"z": 0.12}}])
```

The reply to cell 1 has the pose it returned, the state of the robot, and the image under its caption:

```text theme={"dark"}
Out: {'x': 0.3, 'y': 0.0, 'z': 0.12, 'roll': 180.0, 'pitch': 0.0, 'yaw': 0.0}
{"elapsed_s": 0.0, "steps": 0, "parts": {"arm": {"frame": "base", "pose": {"x": 0.3, "y": 0.0, "z": 0.12, "roll": 180.0, "pitch": 0.0, "yaw": 0.0}, "joints": {"j1": 0.0, "j2": 105.8, "j3": 92.3, "j4": -76.5, "j5": 0.0, "j6": -0.0}}, "gripper": {"grip": 0.0}}}
image images/001.png: before
```

Cell 3 played three moves in one call to `python`, so its body says `"elapsed_s": 5.0, "steps": 75`. A cell that raises ends with a traceback of its own lines and the reason. Here the hand is at x 0.35, z 0.15 and a cell asks for z 0.3 in 0.1 s:

```text theme={"dark"}
Traceback (most recent call last):
  File "<cell 3>", line 1, in <module>
    robot.move([{'t': 0.1, 'arm': {'z': 0.3}}])
robot.Vetoed: arm, keyframe 1: position moves too fast between t=0 s and t=0.1 s, peak 2.25 against a limit of 0.5 m/s. Give that segment at least 0.46 s instead of 0.10 s. With every segment that is too fast stretched the same way, the whole call lasts at least 0.46 s instead of 0.10 s.
```

## Seeing

The agent sees an image only when a cell calls `show`, which puts it in the reply under a caption that names its saved path. The agent's context keeps the most recent images. Older ones stay on disk, and `view_image` brings one back. A long reply is cut in the middle and the full text is saved in `outputs/`, and the reply names the file.

## Moves and code in one episode

Some motions need no code. With the `hybrid` setting on, the agent also has direct control's `move` tool, with the same keyframes, checks and replies, and the system prompt says so. The agent calls `move` for a motion that needs no code and `python` for the rest. Both play on the same robot and record to the same trace, and each starts where the other stopped. This call and cell lift the cube:

```python theme={"dark"}
move(keyframes=[{"t": 2.0, "arm": {"x": 0.35, "y": 0.0, "z": 0.15,
                                   "roll": 180, "pitch": 0, "yaw": 0}, "gripper": 0.0}])
```

```python theme={"dark"}
robot.move([{"t": 2.0, "arm": {"z": 0.02}}])
robot.move([{"t": 1.0, "gripper": 1.0}])
robot.move([{"t": 2.0, "arm": {"z": 0.12}}])
```

A part a move leaves out holds the value the last move set, whichever of the two set it. The two take turns: a `move` call made while a cell is running starts when the cell ends, and a cell waits for a `move` call that is playing. A refused or vetoed `move` call comes back as a reply with its reason, where `robot.move` raises. Either way the robot does not move. The `move` reply carries the camera images that a cell's reply would not.

## Reacting between ticks

`robot.move` plays a whole motion before it returns. For a controller that reads the state every tick, `robot.step(targets)` plays one control tick toward `targets` and returns. It is off by default: set the `step` setting, and without it `robot.step` does not exist. `targets` is one keyframe without `t`, in the same units. This cell lowers the hand 2 mm below where it measures it, tick by tick, until it is at 0.1 m:

```python theme={"dark"}
for _ in range(100):
    height = robot.observe().state["arm"]["pose"]["z"]
    if height <= 0.1:
        break
    last = robot.step({"arm": {"z": height - 0.002}})
print(last.step, round(last.t, 2), last.state["arm"]["pose"]["z"])
```

A step is checked like a move, one tick at a time, and a tick that is not allowed raises and plays nothing. Its reason says what one tick allows:

```text theme={"dark"}
robot.Vetoed: arm: position changes by 0.202 m in one step, past the limit of 0.5 m/s. The largest change one step allows is 0.03333 m.
```

The speed check compares with the previous command, not with where the robot is, so a robot that lags does not hide a jump. A part a step leaves out keeps its last command, including a base's velocity. A velocity part keeps its last velocity after a cell ends, raises or is interrupted, until a later step or move changes it, so stop a base by commanding velocity 0.

## Pixels to world points

An env can give its cameras calibration. Then each `Camera` from `robot.observe()` also has `K` (the intrinsics), `pose` (camera to world) and `depth`, so code can turn a pixel into a point the robot can move to. This cell finds the red cube in the front camera and returns its position in the robot's base frame:

```python theme={"dark"}
cam = robot.observe().cameras["front"]
r, g = cam.rgb[:, :, 0].astype(int), cam.rgb[:, :, 1].astype(int)
ys, xs = np.nonzero((r > 90) & (r > 2 * g))
u, v = xs.mean(), ys.mean()
z = np.nanmedian(cam.depth[ys, xs])
point = cam.pose @ np.append(np.linalg.inv(cam.K) @ [u, v, 1.0] * z, 1.0)
print(point[:3])
```

The channels are cast to `int` first, because `uint8` arithmetic wraps. Depth is the distance to the nearest surface, so the point lies on the face of the cube toward the camera. A camera on the robot has a new `pose` in every observation, so read it from the observation whose image you use. A camera whose env gives no calibration has `None` in these fields.

## Model services

An env can also point Code Control at model services, small HTTP servers that run beside it. Each one turns on a helper in the kernel. `segment` finds objects in an image, `track` follows points through frames, and a depth service fills in `depth` for a camera that has none. rua does not ship the models. The kernel itself opens no network connection. A helper sends its request to the control, which calls the service.

```python theme={"dark"}
found = segment(robot.observe().cameras["front"], "red cube")
if len(found):
    ys, xs = np.nonzero(found.masks[0])
    centre = (xs.mean(), ys.mean())
```

`segment` returns masks, boxes, scores and labels in the order the model ranks them, and `len(found)` is the number of objects. A helper whose service is not configured is not in the kernel, not in the system prompt and not in `MANUAL.md`. A service that is down or too slow raises `robot.ServiceError`. The robot and the kernel are not affected, so the cell can carry on without it. A model's answer is an estimate, so the agent should check a mask by eye with `show` before it relies on it.

## Limitations

* **A move blocks.** `robot.move` returns when the motion has ended, so the code cannot react to a change in the scene mid-move. Look between moves, as in direct control.
* **The sandbox needs bubblewrap.** Where bubblewrap launches, the kernel runs under it with no network, a read-only root and capped memory and file size. Where it does not, such as in Docker's default profile or on Modal, the kernel runs as a plain process of the container and the container is the isolation. Every episode result records the mode that ran.
* **Calibration comes from the env.** An env that supplies none leaves a camera's `depth`, `K` and `pose` as `None`, and the code locates objects from the image alone.
* **Long cells.** A cell that runs past `cell_timeout_s`, 300 s by default, is interrupted.
* **Same open limits as direct control.** The agent is not told a budget, a turn count or a time limit. Dynamic scenes and reaction are open.

For the setup, see the [guide](https://docs.rua.hud.ai/guides/code-control.md). For every setting, see the [reference](https://docs.rua.hud.ai/reference/code-control.md).


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