Skip to content

hylo.codeagents.scenes

Package: hylo-code-agents · Core contracts

scenes

The scene builder workflow (RFC-0006 part 8): task text -> scene file -> checked -> solved with privileged state.

hylo scene build "put the ball in the cup" --out runs/scenes/ball-cup [--model SPEC] [--attempts 6]
hylo scene solve runs/scenes/ball-cup [--model SPEC] [--turns 30] [--seed 0] [--no-video]
hylo scene check runs/scenes/ball-cup/scene.json

build: a chat model writes a hylo.scene/v0.1 file (hylo.core.scene) from the task text; the scene checker (scene_check.py: schema, static, physics, reach) answers with a numbered list of problems, which go back to the model until the scene passes or the attempt budget is spent. Writes DIR/scene.json (the last attempt), DIR/attempts/NN.json and DIR/build.json (per attempt: problems, tokens, latency; totals; built or not).

solve: code.llm on mujoco.panda_scene with the scene, with PRIVILEGED state: the env runs with privileged_obs: true (part of the env params, so of any digest) and the toolkit is PrivilegedSceneTools, which adds robot.scene() (simulator object poses, extents, joint states), robot.object_points(name) and robot.scene_table(). The trace names the toolkit and every turn's code. Writes DIR/solve/trace (the episode trace), DIR/solve/turns.jsonl, DIR/solve.json (outcome, turns, usage, wall time) and DIR/front.mp4 (front camera, when imageio-ffmpeg is installed).

Free mode (scene_free.py): hylo scene build --free TASK --out DIR has the model write a Python scene program (hylo.freescene/v0.1: any robot of panda / aloha / g1, any MuJoCo feature, its own success function) instead of a scene file; check and solve recognise a directory holding scene.py (or a .py path) and use the free checker (scene_free_check.py) and the free-scene privileged toolkit.

SPEC is a chat-model spec (JSON or shorthand, see hylo.reasoners.llm.chat); default: Ollama qwen3.5:35b-a3b. Task-agnostic: nothing here knows a task; the prompt teaches the format with two examples of its own.

DEFAULT_MODEL module-attribute

DEFAULT_MODEL: dict[str, Any] = {'backend': 'ollama', 'model': 'qwen3.5:35b-a3b', 'vision': True, 'reasoning_effort': 'none', 'max_tokens': 3500, 'timeout_s': 3600, 'retries': 1}

PRIVILEGED_TOOLS module-attribute

PRIVILEGED_TOOLS = 'hylo.codeagents.scenes:PrivilegedSceneTools'

SYSTEM module-attribute

SYSTEM = 'You write simulation scenes for a robot manipulation benchmark. A scene is one JSON document in the\nformat hylo.scene/v0.1 (its JSON Schema is below). The simulator turns it into a MuJoCo world: a Franka Panda arm\nwith a two-finger gripper at one end of a table, and your objects on the table. A checker loads your scene, lets it\nsettle, checks that the robot can reach everything and that the goal is not already met; then a separate agent\ntries to solve the task with the robot.\n\nThe world\n- Units: metres and kilograms; ANGLES IN DEGREES. +z is up; the table top is z = 0.\n{robot}\n- Keep every object the robot has to touch, and every place it has to put something, inside the area the arm\n  serves best (above). Do not put objects in a straight line between the arm base and the area.\n- The gripper opens {opening:.2f} m: whatever must be picked up needs a horizontal side of at most 0.06 m (blocks of\n  0.04 m, balls and cylinders of radius 0.02-0.03 m), mass at most 0.3 kg.\n- Typical sizes: block 0.04 m cube, 0.05 kg; ball radius 0.02 m; tray [0.14, 0.14, 0.04]; cup [0.045, 0.08].\n\nObjects\n- Every object has a unique `name` (identifier) and a unique `label`: the words the instruction uses for it.\n- Give `shape` and `size`, or `parts` (primitives placed in the object\'s own frame) for a built thing (a cabinet).\n  `tray` and `cup` are ready-made open containers: use them for a box, bin, bowl, basket or cup to put things in.\n- Start pose: `pose` with pos [x, y] rests the object on the table, or on the object named in `on`. Use `region`\n  (x and y ranges about 0.08-0.15 m wide, yaw range) for objects the robot moves, so every episode starts a bit\n  differently. A region must leave room for the object next to everything else.\n- `fixed: true` for things that must not move (cabinet, button housing, a bin fixed to the table).\n- Moving parts (drawer, door, lid, button) are separate objects with `parent` (what they are attached to) and a\n  `joint` (slide: metres along `axis`; hinge: degrees about `axis` through `anchor`). Their `pose.pos` is\n  [x, y, z] in the parent\'s frame. A part does not collide with its parent: its joint range is what stops it.\n  The parent of a drawer or door is usually fixed.\n- Objects must not overlap at the start; leave at least 0.03 m between them.\n- Make it physically what the task says: something to put things in is hollow (tray, cup, or walls and a floor\n  from parts), a drawer is a hollow box on a slide joint, a sliding lid uses a slide joint, a door or flap a hinge.\n\nSuccess predicate (`success`, field `op`)\n- on(a, b): a rests on top of b (b may be "table"). inside(a, b): a\'s centre inside container b (or `region`).\n  near(a, b or point, max_dist). above(a, b). upright(a, axis). lifted(a, height). row(objects, axis): in a line,\n  in the listed order of increasing x or y. joint_at_least / joint_at_most(object, value or fraction of range).\n  not(term). all_of(terms). any_of(terms). sequence(terms): each becomes true after the previous ones.\n- Relations about an object need it at rest and released by the gripper (unless released: false).\n- The predicate must be FALSE at the start. Use only object names that exist.\n- The instruction names every object the robot must act on by its label.\n\nReply with one or two sentences of plan, then the complete scene in ONE ```json block (no comments in the JSON).\n\nJSON Schema of the format:\n{schema}\n\nExample 1: "put the green cylinder in the tray"\n```json\n{example1}\n```\n\nExample 2: "press the button, then put the blue block on the yellow block"\n```json\n{example2}\n```'

EXAMPLE_1 module-attribute

EXAMPLE_1 = {'name': 'cylinder_to_tray', 'instruction': 'put the green cylinder in the tray', 'max_steps': 600, 'objects': [{'name': 'tray', 'label': 'tray', 'shape': 'tray', 'size': [0.15, 0.15, 0.04], 'colour': 'grey', 'fixed': True, 'pose': {'pos': [0.05, 0.18]}}, {'name': 'green_cylinder', 'label': 'green cylinder', 'shape': 'cylinder', 'size': [0.02, 0.06], 'colour': 'green', 'mass': 0.05, 'region': {'x': [-0.12, 0.0], 'y': [-0.2, -0.08], 'yaw_deg': [0, 0]}}, {'name': 'red_block', 'label': 'red block', 'shape': 'box', 'size': [0.04, 0.04, 0.04], 'colour': 'red', 'mass': 0.05, 'region': {'x': [0.06, 0.14], 'y': [-0.12, -0.02], 'yaw_deg': [-30, 30]}}], 'success': {'op': 'inside', 'a': 'green_cylinder', 'b': 'tray'}}

EXAMPLE_2 module-attribute

EXAMPLE_2 = {'name': 'button_then_stack', 'instruction': 'press the button, then put the blue block on the yellow block', 'max_steps': 900, 'objects': [{'name': 'housing', 'label': 'button housing', 'shape': 'box', 'size': [0.08, 0.08, 0.02], 'colour': 'black', 'fixed': True, 'pose': {'pos': [0.08, 0.2]}}, {'name': 'button', 'label': 'button', 'parent': 'housing', 'shape': 'cylinder', 'size': [0.025, 0.012], 'colour': 'red', 'mass': 0.02, 'pose': {'pos': [0, 0, 0.016]}, 'joint': {'type': 'slide', 'axis': [0, 0, 1], 'range': [-0.008, 0], 'spring': 300, 'damping': 3}}, {'name': 'yellow_block', 'label': 'yellow block', 'shape': 'box', 'size': [0.04, 0.04, 0.04], 'colour': 'yellow', 'mass': 0.05, 'region': {'x': [-0.05, 0.05], 'y': [-0.22, -0.12], 'yaw_deg': [-20, 20]}}, {'name': 'blue_block', 'label': 'blue block', 'shape': 'box', 'size': [0.04, 0.04, 0.04], 'colour': 'blue', 'mass': 0.05, 'region': {'x': [-0.2, -0.12], 'y': [0.0, 0.12], 'yaw_deg': [-20, 20]}}], 'success': {'op': 'sequence', 'terms': [{'op': 'joint_at_most', 'object': 'button', 'value': -0.005}, {'op': 'on', 'a': 'blue_block', 'b': 'yellow_block'}]}}

FENCE_JSON module-attribute

FENCE_JSON = re.compile('```(?:json)?[ \\t]*\\n(.*?)```', re.S | re.I)

PRIVILEGED_REFERENCE module-attribute

PRIVILEGED_REFERENCE = '## Privileged simulator state (this run is flagged privileged)\nThis run gives you the simulator\'s ground truth: start with robot.scene() and use its exact poses and sizes\ninstead of look / find / objects (perception is still there if you want to look).\nrobot.scene() -> dict\n    {name: {"label", "shape", "pos", "quat", "yaw", "size", "extent", "bounds": (min, max), "top", "movable",\n    "fixed", "parent", "joint": {"type", "value", "range", "units"}, "interior": {"centre", "half"}}}: exact object\n    poses and sizes from the simulator, fresh at every call. Prefer it to perception.\nrobot.object_points(name, spacing=0.006) -> (N, 3) points on the object\'s oriented bounding box (world), usable\n    wherever the toolkit takes observed object points.\nrobot.scene_table(height=None) -> Table: the table, or a support plane at `height` for place_at.\n\nExample (pick an object and put it on another one):\n    s = robot.scene(); table = robot.scene_table()\n    pts = robot.object_points("red_block"); box = robot.box(pts, table)\n    plan = robot.plan(robot.grasps("arm", pts, table), table)\n    out = robot.run(plan); print(out["tcp_error"], robot.holding("arm"))\n    up = out["tcp"]["arm"].copy(); up[2, 3] += 0.12\n    robot.run(robot.plan(robot.Goal("lift", "arm", tcp=up), table))\n    obj_in_tcp = np.linalg.inv(plan.goal.tcp) @ box.pose\n    local = (pts - box.pose[:3, 3]) @ box.pose[:3, :3]\n    goal = robot.place_at("arm", obj_in_tcp, local, xy=s["plate"]["pos"][:2], table=robot.scene_table(s["plate"]["top"]))\n    robot.run(robot.plan(goal, table))\n    retreat = robot.status()["tcp"]["arm"].copy(); retreat[2, 3] += 0.1\n    robot.run(robot.plan(robot.Goal("retreat", "arm", tcp=retreat), table))\nFor a drawer, door or lid: grasp its handle with robot.grasp_at (a TCP pose you build from scene() numbers) and move\nalong the joint with robot.Goal("push", ...) (a straight line from the current TCP).'

FrameRecorder

FrameRecorder(env: Any, camera: str = 'front')

An Environment wrapper that keeps one camera's frames (reset and every step); everything else passes.

spec

spec() -> Any

reset

reset(task: TaskInstance) -> Any

step

step(action: Any) -> Any

close

close() -> None

SceneBuilder

SceneBuilder(model: str | Mapping[str, Any] | ChatModel | None = None, *, attempts: int = 6, env_type: str = DEFAULT_ENV, seeds: Sequence[int] = (0, 1), reply_tokens: int | None = None, log: Callable[[str], None] | None = None)

A chat model writes a scene; the checker's problems go back to it until it passes (attempt budget).

model instance-attribute

model = build_chat(model or DEFAULT_MODEL)

say instance-attribute

say = log or (lambda msg: None)

system

system(checker: SceneChecker) -> str

build

build(task: str, out_dir: str | Path) -> dict[str, Any]

PrivilegedSceneTools

PrivilegedSceneTools(spec: RobotSpec, executor: Executor, *, segmenter: Any | None = None, control_hz: float = 20.0, show: Callable[[ndarray, str], None] | None = None, max_vel: float | Sequence[float] = 1.0, max_acc: float | Sequence[float] = 2.0, seed: int = 0)

Bases: Tools

The hylo-manip toolkit plus PRIVILEGED simulator state (the env must run with privileged_obs: true).

privileged class-attribute instance-attribute

privileged = True

scene

scene() -> dict[str, dict[str, Any]]

PRIVILEGED: every object of the scene now, from the simulator: {name: {"label", "shape", "pos" (3,) centre of its body frame, "quat" (w, x, y, z), "yaw" (rad), "size" (the scene file's size, if a primitive), "extent" (3,) full extents in its own frame, "bounds" ((3,), (3,)) world bounding box min / max, "top" (z of its highest point), "movable", "fixed", "parent", "joint" {"type", "value", "range", "units"} for drawers / doors / lids / buttons, "interior" {"centre", "half"} for trays and cups}}.

object_points

object_points(name: str, spacing: float = 0.006) -> np.ndarray

PRIVILEGED: (N, 3) world points on the surface of an object's oriented bounding box, spaced about spacing m: use them where the toolkit wants observed object points (robot.box, robot.grasps, robot.place_at's obj_points after moving them into the object frame).

scene_table

scene_table(height: float | None = None) -> Table

PRIVILEGED: the table as a Table (height from the simulator), or a Table at height (e.g. the top of an object to place on: robot.place_at(..., table=robot.scene_table(scene["box"]["top"]))).

extra_reference

extra_reference() -> str

write_mp4

write_mp4(frames: Sequence[ndarray], path: str | Path, fps: float = 20.0, max_bytes: int = VIDEO_MAX_BYTES) -> dict[str, Any]

H.264 MP4 of RGB frames (imageio-ffmpeg); re-encoded at lower quality / frame rate until <= max_bytes.

scene_schema

scene_schema() -> str

The format's JSON Schema, compact (titles dropped) for a prompt.

builder_system

builder_system(robot_notes: str, opening: float) -> str

extract_json

extract_json(text: str) -> str | None

The JSON document of a reply: the first fenced block that parses as an object, else the outermost {...}.

feedback_text

feedback_text(report: CheckReport | None, problems: Sequence[Problem], attempt: int, left: int) -> str

solve_scene

solve_scene(scene_dir: str | Path, model: str | Mapping[str, Any] | ChatModel | None = None, *, turns: int = 30, seed: int = 0, block_timeout_s: float = 90.0, reply_tokens: int | None = None, cameras: Sequence[str] = ('front', 'side', 'wrist'), video: bool = True, env_type: str = DEFAULT_ENV, max_cost_usd: float | None = None, act_wait_s: float = 4 * 3600.0, log: Callable[[str], None] | None = None) -> dict[str, Any]

Run code.llm with privileged state on DIR/scene.json; returns (and writes DIR/solve.json) the outcome. act_wait_s: how long the kernel waits for the model's next motion (a shared local model may queue calls).

scene_command

scene_command(argv: list[str]) -> int

scene builder: write a scene from task text (build), check it (check), solve it with privileged state (solve)