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.
sim.py
env.py
attach_gym returns the 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:
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 tosim.reset(...) is one of two kinds:
- Build args are the factory’s own parameters (
goalinmake_envabove). When one changes, the sim closes the env and builds a new one. For a registry target, the only build arg isnum_envs. - Episodic args are everything else.
seedgoes toenv.reset(seed=...), and the rest go toenv.reset(options={...}).
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.
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:
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:
contract.json
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.
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:
successis whether the env reported success when the episode finished. The sim reads the first ofinfo["success"],info["is_success"]orinfo["task_success"]that is set, and falls back to an Isaac Lab env’stermination_manager.get_term("success").total_rewardsums the env’s rewards until the episode finished.scoreissuccessas1.0or0.0when the env has reported a success signal this episode, andtotal_rewardotherwise.
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. 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:
contract.json
contract.json always wins over the probe, so attach_gym serves it as written.
The contract’s fields
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
env.py
control capability and calls move:
run.py
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 one.
Vectorized envs
An env that exposesnum_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:
sim.py
env.py
- The token goes to the client through
bindings, so its connection drives its own slot, and tosim.result(token=...), so the right slot is graded. - Concurrent episodes must share one environment placement to share the sim. Run them with HUD’s
Sharedruntime, at mostnum_envswide:
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.