Skip to main content
CodeControl serves a robot to an agent that writes Python. The interface is Code Control and the guide is Code Control.
Values are in metres, degrees and a grip from 0 (open) to 1 (closed), as in Direct Control.

CodeControl

CodeControl is a DirectControl that serves python and view_image instead of move. It takes the same embodiments, and a cell’s robot.move goes through direct control’s own move tool, so it has the same checks, playback and recording. An episode starts with the endpoint’s reset and ends with its result. Each episode gets its own kernel and an empty workspace, and the kernel starts with the first python call.

Tools

move is served only when hybrid is on. See hybrid. Otherwise the agent moves the robot with robot.move in a cell.

The python reply

A reply has these blocks, in order. A block that has nothing in it is left out.
  1. What the cell printed, to stdout and stderr, including what a subprocess printed.
  2. The error, if the cell raised, with the traceback cut to the cell’s own frames. A cell is named <cell 3>.
  3. Out: and the value of the cell’s last expression, if it is not None.
  4. A line naming the images that were saved and not shown, when the cell showed more than max_images_per_cell.
  5. Notices: the cell ran past cell_timeout_s, or the kernel exited. See timeouts.
  6. One JSON body: elapsed_s and steps the cell played, then parts (each part’s measured value, as in a move reply), state (the embodiment’s readouts, when it has any), and "episode": "ended" when the episode has ended. A body that could not read the robot has state_error instead of the parts.
  7. For each image the cell showed: a caption line image images/001.png and the caption the cell gave, then the image.
Text past output_chars is cut in the middle:
The whole text is saved to that file. A shown image is saved whole to images/NNN.png. When a reply’s images together would not fit in one MCP message, they are shrunk by one factor, and the caption ends (shown at 410x410; the saved file is larger).

In the kernel

The kernel is a Python process that lives for one episode. Names, imports, threads and files in the working directory carry over between cells. The working directory is the workspace, and HOME is set to it. The agent may import anything installed in the env’s Python. The kernel starts with a cleaned environment: PATH, HOME, TMPDIR, MPLCONFIGDIR, LANG and PYTHONUNBUFFERED, and none of the env’s variables, so a token in the env’s environment does not reach it. The workspace holds MANUAL.md, which documents every call the settings serve (the system prompt carries the same text), an images/ folder, and an outputs/ folder.

robot

keyframes is the move tool’s: a list of {"t": seconds, "<part>": ...}, with every limit and check of the move tool. A numpy number or array in it is converted. Anything else that is not a number, a string, a list or a dict is a TypeError. robot takes a call only while a cell is running. A thread that a cell leaves behind gets robot.CellEnded if it calls the robot after the cell has ended.

Spec

spec.parts maps each part name to {"space", "frame", "dims"}, and dims maps each dimension name to {"low", "high", "unit"}. The unit is m, deg, m/s, deg/s or "" for a grip.

Observation

The observation never carries a feature that the contract marks privileged.

Camera

A field is None unless the camera source gives it. depth and depth_source can also come from a depth service.

MoveResult

The JSON body of a move reply, as attributes: status (completed, cut_short or ended), elapsed_s, steps, parts, state, reason and settle. A part is also an attribute, so result.arm is result.parts["arm"]. A part that the move named has a gap to its target. A MoveResult has no images.

Preview

StepResult

A step returns no images. Use robot.observe() for the cameras.

Errors

A move that does not play raises, and the robot does not move. All of these are subclasses of robot.MoveError, which has the reason as .reason. robot.ServiceError is raised by a model service that gives no usable answer. It is not a MoveError: the robot is unaffected. It has .reason and .service, the name of the service. A robot.move that is cut short by the call limit is not an error. It returns with status cut_short.

Cameras

CodeControl takes calibration from a camera source that the env passes as cameras=. Nothing in the robot’s contract carries calibration, so an env that serves direct control alone is unchanged. The source is a function from one observation’s arrays, by feature name, to the fields it knows for each camera it can calibrate. A camera is named by its name in the contract, front for observation/front.
Each camera’s dict may hold K, pose, frame, depth and depth_source. pose needs frame, and depth needs depth_source. A field the source leaves out is None. The source runs, in a worker thread, only when a cell calls robot.observe(), so a depth image is rendered only when a cell asks for an observation. A source that names a camera the robot does not have, a field that is not one of these, or a value of the wrong shape or kind makes robot.observe() raise a ValueError that names the camera. examples/yam/cameras.py is a worked source for one in-process MuJoCo sim. A sim that runs in a spawned process needs a source of its own.

preview

robot.preview(keyframes) takes what robot.move takes and runs the same checks in the same order, against a fresh observation of the robot: the schema and ranges, the speed and acceleration vetoes, and the embodiment’s realize. It stops before the first tick. No recording is opened, no frame is pushed, and no held value changes, so the episode is as it was. Nothing is raised for a refusal or a veto. ok is True exactly when the same robot.move would not raise, and reason and min_duration_s are what it would raise with. Once the episode has ended, a preview says the episode has ended. A preview counts as a call to the robot in robot_calls.total and never as rejected. The python tool’s description names robot.preview while the setting is on, and the manual, in the system prompt and in MANUAL.md, has a section for it.

step

robot.step(targets) plays exactly one control tick, 1 / robot.spec.control_rate seconds, and returns. targets is one keyframe without t: a dict of parts and dimensions in the units of robot.spec, with the ranges of the move tool’s per_tick mode. A t in it is refused. Each step is checked in this order, and the first failure raises and plays nothing.
  1. The schema and the ranges, which raise robot.Refused.
  2. Speed, against the previous command and not the measured value. The first step of an episode has no previous command and starts from the measured value.
  3. Acceleration, on position parts: how much the speed changes from the previous step to this one.
  4. The embodiment’s own checks, such as reach, joint limits and self-collision.
A failure of 2 to 4 raises robot.Vetoed. Its reason is worded for one tick and names the largest change one step allows. It has no keyframe, time or min_duration_s. A part or dimension a step leaves out keeps its last command, and a velocity part keeps its last velocity until a step changes it. A step after done is refused, and a step after the episode has ended raises robot.EpisodeOver. A velocity part keeps its last velocity when a cell ends, raises or is interrupted, until a later step or move changes it. To stop, step or move to velocity 0. The simulator only advances while a step or move plays, so a held velocity resumes when the next one plays.

Model services

segment, track and learned depth call HTTP services that you run and configure with settings. The kernel opens no connection to them. A helper sends its request to the control over the kernel’s socket, and the control posts to the URL with a deadline and retries and returns the decoded answer. A helper whose service is not configured is not in the kernel’s namespace, not in the system prompt and not in MANUAL.md. A URL is http or https. A setting on without its URL raises a ValueError. service_timeout_s (60 s) is the whole deadline of one call, and service_retries (2) is how many more tries a failed call gets inside it. A 429 or a 5xx is retried after a pause of 0.25 s that doubles. A connection that fails is retried the same way. Any other status raises at once, with the status and the start of the body. No environment proxy is used. A call that runs out of time raises robot.ServiceError.

segment

image is a Camera, an array or a PIL image. Give exactly one of text (a short noun phrase), points (a list of [x, y] pixels, with point_labels of 1 for on the object and 0 for off it), or box ([x0, y0, x1, y1]). Anything else is a ValueError. Segments has masks ((n, height, width) bool at the image’s size), boxes ((n, 4) pixels), scores ((n,)), labels (a list of strings) and len(). No object found gives n = 0.

track

frames are at least two images of one camera, in time order and all the same size. points is a list of [x, y] pixels in frame query_frame. Tracks has tracks ((frames, points, 2) pixels) and visible ((frames, points) bool). Where a point is not visible its track is the model’s guess.

Learned depth

With a depth service on, robot.observe() fills depth for each camera that has none, and sets depth_source to "learned". A camera with sensor depth keeps it. The service gets the image and K when the env gives it. An answer is kept for a camera while its image does not change, and forgotten at the start of an episode. A depth service that fails makes robot.observe() raise robot.ServiceError.

The wire protocol of a service

Every call is POST <url> with a JSON body, and the service answers 200 with a JSON body. An Image is {"format": "png", "data": "<base64>"} at the camera’s size. A mask is a PNG of that size where a non-zero pixel is in the mask. Pixels are [x, y] from the top left. An answer that does not match raises robot.ServiceError and says what was expected.

Hybrid

With hybrid on, the move tool is served beside python, and overview tells the agent so and the manual has a section for it. The tool is direct control’s own, so a call plays the same checks and returns the same reply, with the camera frames. robot.move is the same motion called from a cell.
  • Both set the same commands. A part a call leaves out holds the value the last call set, whichever of the two set it.
  • Calls and cells take turns, in the order they asked. A move call starts only when no cell is running, and a cell starts only when no move call is playing. While it waits for a long cell, the server sends a progress message every 60 s.
  • A refused or vetoed move call is a reply with the reason, like direct control’s. robot.move raises.
  • A tick played by either is recorded once, in call order, in one recording.
  • note follows the notes setting, as it does for python.

show

show(image, caption=None) saves the image as images/NNN.png, numbered across the episode, and returns the path. The reply shows it unless the cell has already shown max_images_per_cell images. The path of a later image is in the reply’s note and the file is saved either way. image is a height by width array (grey), a height by width by 3 or 4 array, a PIL image, or a Camera. An array is uint8, a float array that is read as 0 to 1, or a boolean mask. Anything else is a ValueError.

Timeouts

A cell that runs longer than cell_timeout_s is interrupted with KeyboardInterrupt, which the control asks for over a socket so it works under a sandbox. If the kernel stops within 5 s, the namespace survives and the reply says so. If it does not, the kernel is killed, the reply says the namespace is gone, and the next cell starts a new kernel with the files of the workspace still there. A request the interrupted cell had in flight is cancelled. While a cell runs, the server sends a progress message every 60 s, so a long cell does not look like a dead connection to the client.

Settings

Each setting is its value in overrides, else its variable in environ (the process environment unless given), else its default. Direct control’s settings read RUA_DC_<NAME> and the rest read RUA_CC_<NAME>. CODE_SETTINGS holds the defaults of the rest. An unknown name, an unknown RUA_CC_ or RUA_DC_ variable, or a value that does not parse raises a ValueError that names it. CodeControl and create_code_agent take settings= and resolve it this way.

The sandbox

The kernel runs in one of two modes. Under bwrap the kernel also caps itself with hard limits: sandbox_memory_mb of data, so an allocation past it raises MemoryError in the cell, and sandbox_file_mb for any one file written. Core dumps are off. A cell cannot lift the limits. The sandbox setting picks the mode:
  • none always runs as none.
  • bwrap runs under bubblewrap, or raises a RuntimeError when CodeControl is built, with the reason it cannot launch.
  • auto runs a short probe launch, with a 10 s limit, and takes bwrap when it works and none when it does not.
Bubblewrap needs unprivileged user namespaces and a mountable /proc. Docker’s default seccomp profile refuses both, and so does gVisor, which is how containers run on Modal. There auto runs as none. The model services of the env are reached through the control, so the kernel needs no network for them. The mode that ran, and why auto fell back, are in the episode result.

The episode result

control.result_extra() returns what to merge into an episode’s result, so that a run records how the agent used the interface. The env passes it on with await endpoint.result(**control.result_extra()). uncorrected counts the rejected moves that come after the last move that played. A cancelled call counts as a call. An episode with uncorrected above 0 ended with the agent’s last move still rejected.

create_code_agent

Builds a HUD gateway agent, which needs HUD_API_KEY, with Code Control’s system prompt. spec comes from embodiment.spec(). The prompt covers the tools, the parts and their ranges, the frames and what a reply shows. It names no budget, no turn count and no time limit, and max_turns caps the model’s turns without telling it. images_kept works with Claude agents only today. Any other agent type raises a ValueError unless images_kept is None. rua.code.agent.overview(settings, spec) takes the resolved settings and returns the prompt alone: the overview of the tools, the robot’s parts and ranges, and the manual of every call the settings serve. examples/yam/code_llm.py runs language-model episodes on the YAM example sim and checks the result: