A language model writes a robot's program, runs it, reads what happened, and rewrites it. With no robot training, success on seven tasks climbs from 24% to 68%.
Pick a stop on the ladder and run 100 trials. Each dot is one trial. Then we build, piece by piece, how a coding agent controls a robot, how the paper tests it, and how it improves.
You need a little Python and what a language model is. We build the rest from zero.
The success rates are the paper's, averaged over the 7 CaP-Bench tasks with Gemini-3-Pro, 100 trials per task (Figure 8, left; the last stop is Table 5, 68.29%). Only the count of green dots is real. Which dots are green is a seeded shuffle for illustration. The yellow line is the paper's human expert average, 88.5% (Figure 1). It is a six-task mean, so it is a rough guide beside these seven-task averages.
Chapter 0
See why code is a good way to steer a robot, and why nobody knew how much of the success came from the model.
Picture a robot arm at a table. A red cube sits in front of it. Your instruction is short: “lift the red cube.” A person finds this easy. For a robot, it is a chain of hard steps. It must see the cube, work out where the cube is in space, plan an arm path that does not hit anything, close the gripper, and lift.
This lesson is about one way to build that chain. A language model writes a program for the robot. The robot runs the program. The model then reads what happened and writes a better one. The paper we follow, CaP-X (Fu et al., ICML 2026), asks a plain question about this idea: how good is it, really, and how do we make it better?
The first way is the classical one. Engineers write the program by hand. It combines perception (what is where), geometry (how to move there) and planning (what to do first). It is robust and easy to inspect. It is also slow to build, and it often fits one task only.
The second way is newer. A vision-language-action model (a VLA) is a neural network. It looks at camera images and a sentence, then outputs motor commands directly. It learns from a very large set of recorded robot demonstrations. It can fold a shirt. But it inherits the limits of its data, and nobody can read its “reasoning.” When the scene, the robot or the task changes, it often needs new data and new training.
The paper points to a third path. Modern language models write good code. They fix their own bugs in software work. What if a coding agent (a language model that writes, runs and repairs code) took the place of the human engineer?
A policy is the rule that turns what a robot senses into what it does next. A neural network can be a policy. A short Python program can be one too. A Code-as-Policy system (CaP) lets a model write that program. The first CaP papers (Liang et al., 2023; Singh et al., 2023) showed this works.
But those systems gave the model help. The helpers were high-level primitives: named functions that a human wrote and tuned, such as stack_objs_in_order(). One call does a whole job. So the model only has to put the calls in the right order.
That raises a fair doubt. When such a system succeeds, who did the hard work? Was it the model, or the human who built the macro? The paper calls the human-made help scaffolding. Its main complaint about earlier work is that nobody measured what happens when you remove it.
Play with the idea below. The program on the left is what a model writes when it has the macro. It is 22 lines long. One line, sample_grasp_pose, does a lot of hidden work. Drag the slider to open that line up.
Each bar is one line of code. The warm bar is the single call to sample_grasp_pose. Drag the slider and watch that one line grow into the code a model must write when the macro is taken away.
The line counts come from the paper’s Figure 2: the high-level program for “lift the red cube” is 22 numbered lines, and the low-level code Gemini-3-Pro wrote for the same grasp step is 37 lines. The stage sizes (7, 13, 7, 3, 7) are my count of that figure’s five labelled stages, blank lines included. The bar lengths are decoration.
That is the whole puzzle in one picture. With the macro closed, the model looks clever after 22 lines. With the macro open, the model must write perception, object grounding, grasp planning and frame changes itself. Real robot code looks like the open version. A fair test has to show both.
The paper builds four connected parts. Each gets its own chapters below.
CaP-Gym is an environment. A coding agent controls a robot by writing and running programs. It joins three robot simulators and holds 187 tasks (7 from Robosuite, 130 from LIBERO-PRO, 50 from BEHAVIOR). CaP-Bench is the test. It runs 12 models on 7 chosen tasks, and it changes three things at a time: how much human help the model gets, whether it may try again, and how it sees the scene.
CaP-Agent0 is a harness (a wrapper of loops and tools) built from what the test found. It needs no training. CaP-RL goes one step further. It trains the model itself with reinforcement learning, using the robot’s own success as the reward.
The first finding is a gap. On these tasks, human experts reached an average of 88.5% success. They wrote one script per task and fixed it by trial and error. (By my arithmetic this is the mean of six tasks, without Cube Re-stack: 93, 73, 100, 80, 94 and 91.) Frontier models, working in a single shot with low-level primitives, scored far below that. Gemini-3-Pro, the model the paper builds on, averaged 24% over the seven tasks in the matching setting S3 (the hero at the top of this page shows it). The rest of the paper explains the gap and then closes much of it.
We take the pieces in order. First comes what a program-as-policy is, then the environment it runs in, then the eight tiers of the test. Next come what the test showed and the three upgrades that make CaP-Agent0. Last come the comparison with humans and trained robots, the training experiment, and what still fails.
Chapter 1
Learn what a policy is, how a program becomes one, and why one missing line can break the whole robot.
Ask a friend to lift a red cube off a table using only written steps. You would write something like this. Find the cube. Open your hand. Move your hand above the cube. Close your hand. Raise it. If your friend follows the list in order, the cube comes up. If your friend skips step four, the cube stays where it is.
A robot program is that list, written in a language the robot understands. This chapter shows what such a program is made of. It also shows why a small change to it can matter a lot.
A pose says where something is and which way it points. The position is three numbers: x, y and z, in metres. The orientation says how the object is turned. The paper stores orientation as a quaternion: four numbers, written [w, x, y, z], that describe one 3D rotation. You do not need to do quaternion math here. Read it as “the way the hand is tilted.”
A segmentation mask is a picture the same size as the camera image. Each pixel is true if it belongs to the object and false if not. A tool such as SAM 3 takes an image and a phrase like “red cube” and returns masks, each with a score. Masks tell the robot which pixels are the cube.
Inverse kinematics (IK) goes the other way from how your arm feels. You think “put my hand there.” The robot needs seven joint angles that put its hand there. An IK solver takes a pose and returns those seven angles. In the paper’s code, solve_ik returns an array of shape (7,).
Now stack the three ideas. Here is the program a model wrote for “lift the red cube” with human-made helpers (from the paper’s Figure 2, comments shortened):
# 1. Find a good grasp for the red cube grasp_pos, grasp_quat = sample_grasp_pose("red cube") # 2. Open the gripper open_gripper() # 3. Move above the cube, approaching from 10 cm up goto_pose(grasp_pos, grasp_quat, z_approach=0.1) # 4. Close the gripper close_gripper() # 5. Lift by adding 0.2 m to z lift_pos = grasp_pos + np.array([0, 0, 0.2]) goto_pose(lift_pos, grasp_quat)
This is a policy: a rule that turns the situation into actions. Each call, such as goto_pose, is a primitive. A primitive is a function the robot already provides. The model chooses and orders the primitives. It does not move motors.
Why use code at all, and not a fixed list? Because code can branch. The paper’s generated programs contain lines like if not masks: print("No red cube found."); return. A plain list cannot say “if the cube is missing, stop and report.” Code can also loop, keep variables, and define helper functions.
A program that runs once, from top to bottom, never looks at the result. Engineers call that open loop. It is like throwing a dart with your eyes shut. A closed-loop policy looks at what happened and adjusts. The last chapters turn on this difference. The first tiers of the benchmark are open loop. The later tiers close the loop by letting the model read the result and write again.
Try the toy below. It runs the five-step program above on a flat side view. Switch lines off, one at a time, and watch the robot. This is a toy world I made to show the idea, not the paper’s simulator.
The five buttons are the five lines of the program. Press one to switch that line off. The robot runs the program again each time. Try each line and see which ones the cube needs.
Illustrative toy: a flat side view, one cube, and simple rules (a closed gripper cannot straddle the cube, and a cube moves only if it was grasped). The five lines are the program from the paper’s Figure 2. The sim and the rules are not the paper’s.
Switch off close_gripper and the arm goes up with open fingers. The cube stays. Switch off sample_grasp_pose and the program crashes on its next line with a NameError, because grasp_pos was never set. Switch off open_gripper and the fingers land on top of the cube.
The last case matters later. The paper finds that a small language model, before training, often skips the grasp. It writes code that moves straight to the place target and opens the gripper, as if the cube were already in its hand. The paper calls this step skipping. Chapter 9 shows reinforcement learning fixing it.
In this program, sample_grasp_pose is a macro. At the low level, the model would call the segmentation tool, read depth, ask a grasp planner for K candidate grasps, pick the best, and change coordinate frames. The grasp planner returns two arrays: the grasps, with shape (K, 4, 4), and their scores, with shape (K,). Each of the K grasps is a 4 × 4 matrix that holds a position and a rotation together.
So “write a program for the robot” can mean very different jobs. It can mean five easy lines, or, in the paper’s Figure 2, a single grasp step that opens into 37 lines of geometry. The next chapter shows the room where such programs run.
Chapter 2
Follow one turn: what the agent sees, what it writes, and what comes back.
Imagine a workshop with a robot, a camera and a bench of tools. A new worker sits at a desk with a laptop. The worker cannot touch the robot. They can only type a Python script, press run, and read what the script prints. If the cube falls, they type another script. The robot keeps its current pose between scripts. Nothing resets.
That workshop is CaP-Gym. The worker is the coding agent. This chapter walks through one turn of work and the data that moves in it.
A Gymnasium environment is a standard Python interface for tasks. It has a reset step and a step function. Many learning tools already speak it. CaP-Gym builds on it and joins two loops. The inner one is the low-level environment loop: a physics simulator, or the real world, that advances in small time steps. The outer one is a stateful code executor: a Python process that remembers its variables between runs.
The outer loop follows the REPL pattern: read, evaluate, print. You may know it from a Python notebook. You type code, it runs, and its printed output comes back. That pattern suits coding agents well, because an agent can add a print() line to look inside its own program.
The paper defines one turn as one exchange between the agent and a robot task. The agent receives observations. It writes one Python program. The environment runs that program to the end. A single program may call many primitives, and each primitive may advance the simulator many internal steps. A trial is a run of one or more turns on one task instance. The environment is never reset inside a trial.
Step through one turn below.
Press Next stage to move the token around the ring. The read-out says what travels between the boxes. After stage 6 the ring starts turn 2.
The stage names are mine. The contents come from the paper: the observation keys and array shapes are from the S3 tier’s get_observation docstring (Appendix G); the turn definition, the REPL design and the rule that the environment never resets are from Section 2 and Section 3. Feedback in stage 6 goes back to the agent only in multi-turn tiers.
The agent reads two things. The first is text: the task (“lift the red cube”) and the API documentation, a list of the functions it may call, with their signatures and docstrings. The second is the scene, but only as the program asks for it. The agent writes obs = get_observation(), and the call returns a dictionary.
Under the key obs["robot0_robotview"] sit the camera arrays. The color image is (H, W, 3) with dtype uint8. The depth image is (H, W, 1) with dtype float32. There are also the 3 × 3 camera intrinsics (how the lens maps 3D points to pixels) and a 4 × 4 camera pose matrix called pose_mat.
Now trace the shapes through the five perception steps from the paper’s Figure 2, for “lift the red cube”. Each line is one intermediate value.
| Code | Shape | Meaning |
|---|---|---|
| rgb = obs[...]["rgb"] | (H, W, 3) | the camera picture |
| depth = obs[...]["depth"] | (H, W, 1) | distance to each pixel |
| masks = segment_sam3_text_prompt(rgb, "red cube") | list of {"mask": (H, W), "score"} | every region SAM 3 thinks is a red cube |
| mask = max(masks, key=score)["mask"] | (H, W) | the best region |
| grasps, scores = plan_grasp(depth, K, seg) | (K, 4, 4) and (K,) | K candidate grasp poses and their scores |
| best = grasps[argmax(scores)] | (4, 4) | the top grasp, in camera coordinates |
| world = camera_pose @ best | (4, 4) | the same grasp, in robot coordinates |
The seven rows finish with a 4 × 4 pose in the robot’s own frame. Only then can an IK solver aim the arm. You can see why the macro sample_grasp_pose is handy: it packs all seven rows into one call.
The paper groups primitives in two kinds. Perception primitives turn raw sensor data into structured objects. They wrap SAM 3 (a model that finds an object from a text phrase), Molmo 2 (a model that points at things), and standard libraries OpenCV and Open3D. Control primitives turn a goal pose into a safe motion. They call motion planners and IK solvers such as PyRoKi, which handle collision checks and reachability. So the agent reasons about positions in Cartesian space and leaves the joint angles to the solver.
All the heavy primitives run as stateless services. A stateless service keeps no memory of earlier calls. Every request carries all its inputs. Compare a vending machine with a barista who remembers your order. The vending machine is stateless, so many people can use one machine at once. For CaP-Gym this means many trials can share the same SAM 3 server at once. The paper says this gives high-throughput parallel evaluation, which it needs for 12 models and 100 trials per tier.
CaP-Gym keeps each simulator’s own physics. It wraps Robosuite (7 tasks), LIBERO-PRO (130) and BEHAVIOR (50), a total of 187 tasks. It exposes them through one shared primitive design. The design is meant to work in simulation and on a real robot. Chapter 8 shows the same agent code running on a Franka Panda and an AgiBot G1.
Here is the loop as plain Python. This is my sketch of the paper’s description. The names are mine, not the code base’s.
# sketch of one CaP-Gym trial obs = env.reset() # once, at the start of the trial history = [] for turn in range(max_turns): prompt = build_prompt(task, api_docs, history, obs) code = model.generate(prompt) # one Python program stdout, stderr = executor.run(code) # same process, same variables history.append((code, stdout, stderr)) # only fed back in multi-turn tiers if env.task_done() or model_says_finish: break success = env.success() # the verifiable score for this trial
Notice what is not reset. If turn one drops the cube, turn two begins with the cube on the floor. The agent has to cope with the world as it now is. That makes recovery a skill that the benchmark can measure.
Chapter 3
Turn one messy question into eight clean experiments by changing one thing at a time.
Two cooks enter a contest. One gets a jar of ready-made sauce. The other starts from tomatoes. The first dish tastes better. Who cooks better? You cannot tell. To judge fairly you must run the contest several times. Once with the sauce for both. Once without it for both. Once with a second try allowed. Once with a friend who tastes the dish and gives advice.
That is the plan of CaP-Bench. It is the test part of CaP-X. It changes the help a model gets, one kind at a time, and it measures success each time.
The paper names three axes, which are three things it can turn.
The first is abstraction level: how much of the job a human has already done. At the high level, the agent gets macros such as sample_grasp_pose. At the low level, it gets only the raw tools: a segmenter, a grasp planner, an IK solver. The second is temporal interaction: one shot, or many turns. The third is perceptual grounding: how the agent finds out what the scene looks like. It might get exact numbers, raw camera images, or a text description of the picture.
Crossing the knobs gives eight tiers. Four are single-turn, named S1 to S4. Four are multi-turn, named M1 to M4. A tier is one fixed combination of help. Pick any tier below and read what it adds.
The grid shows what each tier gives the agent. The bars below show average success for the model you choose. Pick a model, then pick a tier to read what changed.
Grid: the paper’s Table 1 (I added the “exact state” label for its noiseless row). Bars: for S1 to S4 and M1 to M3, my average of that model’s seven per-task cells in the paper’s Figure 17, skipping cells the paper did not run (marked n/a). M4 is only reported for Gemini-3-Pro, as 55% (Figure 8). Yellow ticks: the human expert reference on S1 to S4, averaged the same way.
S1 is the privileged tier. The agent gets ground-truth object poses and masks straight from the simulator. It still uses human macros. S1 removes perception noise, so it measures pure planning. The paper calls it the reasoning upper bound. S2 keeps the macros but uses real perception on raw color and depth images. This is the setting most earlier work used.
S3 takes away the macros. The agent gets the raw tools and, for each, a docstring with a usage example. S4 is the same as S3 with the examples removed. Only the function signatures and docstrings remain. The agent must work out the program structure alone.
The multi-turn tiers add a loop. M1 uses the S2 tools and lets the agent read stdout and stderr after every run. So the agent can add print lines and inspect its own variables. M2 adds the camera image straight into the model’s context. M3 adds the Visual Differencing Module (VDM): a separate vision-language model that turns the pictures into text and lists what changed since the last turn. M4 puts the VDM on top of the low-level tools and examples from S3. Every multi-turn tier keeps the stdout and stderr from M1.
See how clean the design is. S2 versus S3 isolates the macros. S3 versus S4 isolates the usage examples. S2 versus M1 isolates retries. M1 versus M2 versus M3 isolates how the agent sees. Each comparison changes one thing.
The paper runs 12 models. Closed models include Gemini-3-Pro, GPT-5.1, GPT-5.2, o1, o4-mini, Claude Haiku 4.5 and Claude Opus 4.5. Open models include GPT-OSS 20B and 120B, Qwen3 235B, Kimi K2 and DeepSeek-V3.1. Each model faces seven tasks: Cube Lift, Cube Stack, Spill Wipe, Peg Insertion, Cube Re-stack, Two-Arm Lift and Two-Arm Handover. Each task runs 100 trials per tier.
The score is success rate at Pass@1. Pass@1 means the first attempt counts and there is no best-of-N. A trial is a success if the simulator’s own task check says so. That check is an objective, verifiable signal: the cube is lifted or it is not. This matters for Chapter 9, where the same signal becomes a training reward.
The human reference is not a casual attempt. Seven of the paper’s authors, each with more than two years of robot programming, wrote one Python script per task per tier. They used exactly the same primitives as the model. They ran and debugged the script offline, as many times as needed, until it worked reliably. The result was 88.5% average single-turn success. Cube Lift and Cube Stack took hours. Peg Insertion and Two-Arm Handover took two to three weeks each. So “human” here means “after long iteration.”
A worked example shows why the tier changes the work. For Cube Stack at S1, the agent calls get_object_pose("red cube") and gets the true position. At S2 the same macro runs a perception model first, so the number can be wrong. At S3 the agent writes its own segmentation, depth back-projection and grasp ranking. It succeeds only if every line is right. The model is the same in all three cases. Only the help differs.
Chapter 4
Measure what happens when you take away the human-made macros, one rung at a time.
A child learns to ride a bike with training wheels. Take one wheel off and the child wobbles. Take both off and some children fall. The wheels were doing real work. A fair test of balance has to remove them.
The macros in a Code-as-Policy system are the training wheels. This chapter removes them, one rung at a time, and records what happens.
Start at the bottom rung, S4: raw tools, no examples, one shot. This is the matching test for the human experts, who used exactly the same tools. The experts scored 88.5% on average in the single-turn tiers (the six tasks the models also ran single-turn). No model came close. The paper’s Figure 1 plots the models by release date. Newer models climb, but all of them sit far under the human line. The best, Gemini-3-Pro, averages 27.7% at S4 over the seven tasks, by my average of its Figure 17 cells.
The same models do very well on other coding tests. Software engineering benchmarks, maths and science exams all show strong scores. Writing code that moves a robot is harder. The code has to be right about geometry, camera frames and physics. Nothing in the text of a program tells you that.
Now climb. The paper averages the closed models and the open models separately. Moving from S4 up to S1 adds help at each step: examples (S3), macros with real perception (S2), then macros with exact state (S1). Success rises at every step. My averages of the Figure 17 cells for the seven closed models are 17.5, 20.8, 35.5 and 55.6 percent. For the five open models they are 9.9, 12.5, 30.1 and 45.0 percent. Use the device to read any rung.
Each bar is 100 trials. Green trials succeed. Grey trials run without error but fail the task. Red trials crash or do not run. The yellow tick is the human expert. Choose a group of models, then compare the rungs.
My averages of the per-task cells in the paper’s Figure 17: success rate and code compilation rate, each averaged over the seven tasks (skipping cells the paper did not run) and then over the models in the group. “Run but fail” is compilation rate minus success rate. Human is the expert average on the same tier.
Look at the grey. At S4 the closed models compile 88.5% of their programs, yet only 17.5% of trials succeed. So 71.0 points of trials ran cleanly and still failed. Code that runs is not code that works.
Split the success rate in two parts. Call it S for success, C for the share of programs that run, and q for the share of running programs that solve the task.
Work it for the closed models. At S1: C is 99.7 and S is 55.6, so q is 55.6 ÷ 99.7 = 55.8%. At S4: C is 88.5 and S is 17.5, so q is 17.5 ÷ 88.5 = 19.8%. From S1 to S4, C shrinks by a factor of 0.89. But q shrinks by a factor of 0.35. Most of the fall comes from q, the judgement, not from C, the syntax.
0.89 × 0.35 ≈ 0.31 (= 17.5 ÷ 55.6)
This agrees with the paper’s own caution that the drop at S3 and S4 is only in part from reduced code correctness. For open models the syntax loss is larger: C falls from 92.9 to 57.6. Weaker open models often cannot even write a program that runs against an unfamiliar API.
If macros help so much, why remove them? The paper gives two reasons. First, macros hide failures. A model that reaches 56% with the exact-state macros may be unable to do the low-level reasoning at all, and the score never shows it. Second, macros cap what the agent can do. The paper calls this a generality ceiling. A fixed macro cannot express a fallback strategy that nobody thought to put in it.
Here is one real example, abridged from the paper’s case study of the “wipe up the brown spill” task. At low level, the model chose by itself a cascade of perception fallbacks:
# ask Molmo to point at the spill, then segment around that point molmo_res = point_prompt_molmo(rgb, "brown spill") masks = segment_sam3_point_prompt(rgb, spill_pt) if spill_pt else [] if not masks: # fall back to broader wording masks = segment_sam3_text_prompt(rgb, "stain") if not masks: masks = segment_sam3_text_prompt(rgb, "brown liquid") if not masks: print("No masks found after all attempts."); return
A single macro such as find_object(name) would not do this. The agent needed the open tools to build the cascade.
The S3 tier differs from S4 only by usage examples in the docstrings. The paper reports that almost all models gain from them, and its Figure 18 is titled “+20%”. My Figure 17 averages agree with a relative gain of about a fifth: 20.8 against 17.5 for closed models, and 12.5 against 9.9 for open models. The gain is not uniform. Gemini-3-Pro’s own seven-task averages are 24.3 with examples and 27.7 without.
The paper draws a design lesson. If agents can recover structure from low-level tools, then a human does not need to write the macros. That idea leads to the skill library in Chapter 6.
Chapter 5
See why text feedback helps, why raw pictures hurt, and how a vision module repairs it.
You pour a cup of coffee while looking away. You hear a splash. Now you have three ways to fix things. You can listen to a friend who says, “the cup is full, it spilled on the left.” You can look at a photo of the table, taken with a blurry phone. Or you can have a friend look at two photos, before and after, and tell you what changed. Which gives the best fix?
This chapter asks the same question of a coding agent. Chapter 4 tested one shot. Now the agent may run its program, see what happened, and write again. The paper calls this its Takeaway 3.
The tiers differ in what comes back after each run.
In M1 the agent gets stdout (everything the program printed) and stderr (the error messages). This is plain text. It enables what the paper calls a state introspection loop. The agent can add print lines that expose hidden values, such as the object pose the perception model estimated. Then it can read those numbers on the next turn and decide what went wrong.
In M2 the environment also shows the model the current camera picture. In M3 a helper called the Visual Differencing Module (VDM) writes text about the picture instead. Pick a feedback type below and see how it scores.
Bars are the seven tasks. The outline is the same model with no feedback (S2, one shot). Pick a model and a feedback type. Watch the Spill Wipe bar when you choose raw images.
Cells are the paper’s Figure 17 (success rate, 100 trials). Averages cover only the tasks where both tiers have a number (the paper did not run Cube Re-stack in the single-turn tiers for some models), so they differ a little from the paper’s Figure 5. The strip at the bottom is a simplified picture of the agent’s input.
The paper reports a surprise. Showing the agent the camera picture (M2) did worse than text-only feedback (M1) for several models. For Gemini-3-Pro, the average falls from 46.9 to 43.1. On Spill Wipe it falls from 91 to 59.
The authors give a guess, and they say it is a hypothesis. Foundation models are rarely trained to reason about code and pictures of physical task execution together. They call this a cross-modal alignment gap. The picture is in the context, but the model does not tie it to the line of code that caused it. A ten-word text note about the scene is easier to use than ten thousand pixels.
The effect is not universal. In my averages, GPT-5.1 and Claude Haiku 4.5 do slightly better with the image than without it. The paper’s claim is about the typical case.
The VDM is a vision-language model that stands between the camera and the coding agent. It has a simple job, and it has three inputs: the task instruction, the current image, and (after turn one) the previous image.
On the first turn it writes a scene description and picks out the task-relevant attributes. On later turns it describes what differs from the previous image and whether the task looks complete. The text goes into the agent’s context with the stdout and stderr. A sketch of the data flow:
# one multi-turn step with the VDM (sketch of the paper's description) img_now = obs["robot0_robotview"]["images"]["rgb"] # (H, W, 3) uint8 if turn == 1: note = vdm(task, img_now) # scene description + task-relevant facts else: note = vdm(task, img_now, img_prev) # what changed, and is the task done? context = [task, api_docs, last_code, stdout, stderr, note] # all text code = coding_agent.generate(context)
Two real VDM notes from the paper show the effect. On the real Franka, the task was “stack these as high as you can,” with a yellow cube, a blue cube and a tennis ball. The VDM wrote that the cubes “have flat surfaces suitable for stacking, while the tennis ball is spherical and would likely need to be placed on top.” The coding agent then built the only stable order. For “place the blue cube on top of the yellow cube,” the VDM noticed the blue cube was at the bottom of a three-cube tower. The agent then planned to remove the green and yellow cubes first. The instruction said nothing of this.
Take Gemini-3-Pro on Cube Stack. One shot (S2) it scores 37. With stdout and stderr (M1) it scores 67. With the raw image (M2) it scores 58. With VDM text (M3) it scores 87. Each step of help adds or removes real trials, and the VDM step is the largest. Over all seven tasks, Gemini-3-Pro averages 39.1 at S2, 46.9 at M1, 43.1 at M2 and 60.3 at M3.
One more result links back to Chapter 4. With VDM feedback on the low-level tools (M4), Gemini-3-Pro averages 55%. That beats the one-shot macro tier S2 (39.1) and comes close to the macro-based multi-turn tier M3 (60.3). The paper reads this as a test-time compute scaling hypothesis: robustness can be built at run time, by giving an agent more chances to check and repair, instead of building it in with human macros.
Failures are often recoverable. The paper sees both code errors and physical failures, such as an unstable grasp, fixed by a later turn. In the successful runs without a vision helper (M1), the agents compensate by instrumenting their own code. They print object poses and check, for example, relative heights to confirm a stack.
Chapter 6
Mine nine helper functions out of successful runs and hand them back to the agent.
A woodworker cuts the same angled joint a hundred times. The first few times, they measure and mark by hand. Then they make a jig, a small wooden guide, and keep it in a drawer. Next time they reach for the jig. The cuts are faster and the errors are fewer. The jig is not part of the saw. The woodworker made it from their own work.
CaP-Agent0 does the same for code. It keeps a drawer of small helper functions that earlier agents wrote and that worked. This chapter shows where the drawer comes from and what is in it.
Look at what models write at the low-level tiers. Capable models, left alone, write helper functions for the same chores again and again. They convert a rotation matrix to a quaternion. They back-project a depth image into 3D points. They change points from camera coordinates to world coordinates. The paper notes that when it did not supply the 3D transform helpers in its real-robot setup, the models almost always wrote them and made mistakes from time to time.
Rewriting the same function is wasteful, and each rewrite is a new chance for a bug. The paper takes ideas from agents that collect reusable tools over time (Wang et al., 2023a) and applies them here.
The recipe has four steps.
def name(...) blocks.The word task-agnostic matters. A function that only works for “stack the red cube” is no use for “wipe the spill.” Geometry helpers work for any task, so they survive the filter. The paper ran this pipeline once. It says the process is naturally iterative, since the library could keep growing as more runs succeed.
| Function | What it does |
|---|---|
rotation_matrix_to_quaternion | Turns a 3 × 3 rotation into a unit quaternion [w, x, y, z], using a stable method that survives a near-zero trace. |
decompose_transform | Splits a 4 × 4 pose into a position and a quaternion. |
depth_to_point_cloud | Turns a depth image and the camera intrinsics into 3D points in the camera frame. |
mask_to_world_points | Keeps only the masked pixels and puts their 3D points in the world frame. |
pixel_to_world_point | Turns one pixel (u, v) and its depth into a 3D world point. |
transform_points | Applies a 4 × 4 transform to N points. |
interpolate_segment | Makes waypoints along a line, one every 3 cm by default. |
normalize_vector | Scales a vector to length 1. |
select_top_down_grasp | Picks the best-scoring grasp that points downward. |
Three of these need a short explanation if you have not met them. First, a point cloud is a list of 3D points, shape (N, 3). Second, extrinsics are the 4 × 4 matrix that places the camera in the world. Third, homogeneous coordinates are a trick: add a 1 to a point, so that rotating and shifting become one matrix multiply. The paper’s transform_points does exactly this, converting (N, 3) to (N, 4) before the multiply.
Work one point. Let R turn the plane by 90° about the vertical axis, so (x, y) becomes (−y, x). Let t = (0.5, 0, 0.2) metres. Take p = (0.1, 0, 0). Rotate: (0, 0.1, 0). Shift: (0.5, 0.1, 0.2). That is p′.
The most interesting skill is the last one. A learned grasp planner, such as Contact-GraspNet, outputs many candidate grasps with confidence scores. But the score does not know the task. On a table, a grasp from straight above is usually safer than a sideways one, even when the sideways one has a higher score. The paper’s case study shows an agent that wrote its own filter for this. The library holds the same idea. Here is the library code, trimmed:
def select_top_down_grasp(grasps, scores, cam_to_world, vertical_threshold=0.8): best_grasp, best_score = None, -np.inf world_z = np.array([0, 0, 1]) for i, g_cam in enumerate(grasps): # grasps: (N, 4, 4) in the camera frame g_world = cam_to_world @ g_cam # same grasp, in the world frame approach = g_world[:3, :3][:, 2] # the gripper's approach direction alignment = -np.dot(approach, world_z) # 1.0 means straight down if alignment > vertical_threshold and scores[i] > best_score: best_score, best_grasp = scores[i], g_world return best_grasp, best_score # (None, -inf) if no grasp qualifies
Try it. The eight candidate grasps below point at a cube. The planner likes the one at the top of its score list. Drag the threshold and see which candidate the filter picks.
Each arrow is a candidate grasp. Its number is the planner’s score. Arrows that fail the vertical test fade. Drag the threshold from loose to strict.
The eight angles and scores are made up for illustration. The rule is the library’s: alignment = −(approach · world z), kept if above the threshold, the best score wins, and the paper’s case-study version falls back to the highest score overall if none qualify. The default 0.8 is the library’s default.
The library is not a fixed API. It is a set of helpers the agent may call or ignore. The agent keeps the full low-level interface, so it keeps all its freedom. It simply does not have to rederive the common parts. The paper contrasts this with a human-designed high-level API, which fixes the agent’s options in advance.
The measured gain is real and modest. In the ablation on Gemini-3-Pro (Figure 8, left), the average success goes from 55 with the loop and VDM (M4) to 59 with the skill library added. That is four points over seven tasks. The paper does not ablate the nine skills one by one, and the library was built from the same seven Robosuite tasks it is tested on. The paper does not report how well it carries to other task suites.
Chapter 7
Ask several models for code, merge the best parts, and measure the gain.
Nine engineers each sketch a plan for the same job. Eight forget the same edge case. One remembers it. A good lead does not vote by hand count. The lead reads all nine plans and builds one plan that carries every good catch. That is the third upgrade in CaP-Agent0.
The paper looked at failures in the S2 and S3 tiers and reached a view. Many failures come from too little exploration at run time, not from a lack of skill. The model could have written a good program. It just wrote one draft, and the draft missed a case.
Spending more compute at answer time is called test-time compute. There are many ways to do it. You can let a model think longer. You can retry. Or you can sample several drafts and combine them, which is what CaP-Agent0 does, in the style of recent ensemble methods (Pan et al., 2025; Jin et al., 2025; Rodionov et al., 2025).
At every turn, the system asks for nine candidate programs at once. A candidate is one full draft. There are two setups.
In the single-model setup it asks Gemini-3-Pro nine times, at temperatures 0.1, 0.2 and so on up to 0.9. Temperature is a randomness dial. At a low value the model writes the most likely text and repeats itself. At a high value it varies more. Spreading the temperatures buys variety.
In the multi-model setup it asks Gemini-3-Pro, Claude Opus 4.5 and GPT-5.2 three times each, at temperatures 0.1, 0.5 and 0.9. Different models make different mistakes, so the pool is more varied than one model can supply at any temperature.
Now a central coding agent reads the nine drafts and writes one final program. Programs cannot be voted on the way multiple-choice answers can, since two good programs rarely match line for line. So the paper merges them instead. The agent’s instructions are short and sharp:
The output rule is strict: reasoning is allowed, but the reply must contain exactly one fenced code block.
The same trick covers the decision to continue. After each turn, every candidate also votes REGENERATE (write new code) or FINISH (the task is done). The synthesizer sees both counts. It then returns either the word FINISH, or REGENERATE followed by one new code block.
# one CaP-Agent0 turn (sketch of the paper's description) drafts = parallel([agent_call(prompt, model=m, temperature=T) for (m, T) in POOL]) # 9 calls if turn > 1: votes = Counter(d.vote for d in drafts) # REGENERATE vs FINISH counts prompt_s = synth_prompt(votes, drafts) reply = synthesizer(prompt_s) # "FINISH" or "REGENERATE" + one code block
Play with the idea. Each row below is a draft. Each column is a failure the final program should guard against. A filled dot means the draft includes that guard. The bottom row is the merged program. Which one-model blind spot can nine drafts never fix?
Choose one model or three, then add drafts. The merged row shows every guard that at least one draft carries. Watch the one column that a single model never fills.
Illustrative toy. The pool sizes, the temperatures and the merge rule are the paper’s. Which guard each draft carries is a seeded random draw, and the blind spots are invented to show the idea. The paper measures the real gain below: 66% for one model, 68% for three.
The real effect is smaller than the toy suggests, and it is clean. All rows are Gemini-3-Pro as the coding agent, over the seven tasks, 100 trials each (Figure 8, left; Table 5).
| Setup | Average success |
|---|---|
| S3, one shot, low-level | 24% |
| M4: loop, VDM, low-level | 55% |
| + skill library (SL) | 59% |
| + 9 drafts from one model (1M) | 66% |
| + 3 models (3M), CaP-Agent0 | 68.29% |
| 3M plus a stricter debugging prompt | 65.43% |
Nine drafts from one model add seven points (59 to 66). Spreading them over three models adds two more (66 to 68). The last row is a lesson in humility. The authors wrote a prompt that told the agent to act as an “experienced debugger,” to trust no printed output blindly, and to treat missing evidence as failure. It did not help. The average went down, from 68.29 to 65.43. So better wording is not a free gain.
The paper reports one more effect. The ensemble lowers the average number of turns needed. Look at the case study on Cube Re-stack. A single-query agent wrote code with no fallback for sample_grasp_pose. The call returned a pose near (0.04, 0.09, −0.04), close to the robot base. The run failed. On the next turn the agent noticed the pose was wrong and added a check for it. It fixed only the failure it had just seen.
The ensemble drafts, on the other hand, wrote a pick_object helper in the first turn. If the grasp planner returned nothing, the helper fell back to a centroid grasp built from the mask. The paper’s wording is that the single agent patches retroactively and the ensemble anticipates. Eight engineers who each fear a different failure cover more ground than one engineer who learns by crashing.
Chapter 8
Compare CaP-Agent0 with expert code, with trained robot policies, and with a real robot.
Three contestants line up for the same set of jobs. The first is a patient robotics engineer who spent hours or weeks on a script for each job. The second is a trained robot policy, a VLA, that learned from a large set of recorded demonstrations. The third is CaP-Agent0, which has seen none of the tasks and trains on nothing. Who wins?
The paper asks this three ways: on its seven core tasks, on a wider set of 30 manipulation tasks and two mobile ones, and on real robots. The answer is mixed, and that makes it worth reading closely.
First, the home ground. The comparison below sets CaP-Agent0 against the human expert script and against a single-shot Gemini-3-Pro at the low-level tier S3. All three use the same primitives. CaP-Agent0 gets the loop, the VDM, the skill library and nine drafts from three models.
It reaches or passes the human on four of the seven tasks: Cube Lift (97 against 93), Cube Stack (98 against 73), Spill Wipe (100 against 100) and Cube Re-stack (89 against 47). It stays below the human on three: Two-Arm Lift (74 against 94), Two-Arm Handover (20 against 91) and Peg Insertion, where it scores 0 against the human’s 80.
Look at Cube Re-stack. The cubes start stacked, and the agent must take them apart first (the paper’s case study begins with “Unstack the green cube from the red cube”). That needs state checks between steps. A one-shot script cannot easily do that, and the loop helps a lot. The human script scored 47, and the one-shot model scored 0.
Pick a benchmark. Each group of bars is one task or one suite. Compare the warm bar, CaP-Agent0, with the others. Mind that the scales differ: LIBERO-PRO scores are small.
CaP-Bench: Human is the expert script at tier S3 (Figure 17), S3 is Gemini-3-Pro one shot (Figure 17), CaP-Agent0 is Table 5. LIBERO-PRO: Table 2, scores as percent, 50 trials per task, averaged over each suite’s tasks. BEHAVIOR: Table 3, 25 trials per task, R1Pro humanoid; navigation counts as success within 1 m of the target.
LIBERO-PRO is a harder version of an older benchmark called LIBERO. It nudges each task in small, reasonable ways. The paper tests two. Under position perturbation, objects swap places, for example the frying pan and the coffee pot. Under instruction perturbation, the sentence changes so a different object must be moved, such as “put the frying pan on the stove” where training said the moka pot.
The trained policies suffer. OpenVLA and π0 score 0.00 on every cell. π0.5 scores 0.17, 0.38 and 0.20 on the three suites under position swaps and nearly zero when the instruction changes (0.01, 0.00 and 0.01). The paper explains that VLAs are trained on one instruction distribution and do poorly off it. CaP-Agent0 reads a new instruction like any other sentence. It scores 0.18, 0.17 and 0.14 under instruction change. Under position swaps it scores 0.22, 0.26 and 0.12, so it beats π0.5 on one suite and trails it on two.
All scores here are low in absolute terms. The paper says CaP-Agent0 is “comparable” to the trained policies and in some cases above them. That is a fair summary of the table and no stronger. The failure reasons, from the paper’s appendix, are concrete. SAM 3 sometimes segments a “tomato sauce can” when asked for the “alphabet soup can.” Cameras are not top-down, so grasps come in at an angle. The agent has no collision-aware planner, so it knocks neighbouring objects over.
The BEHAVIOR tests use an R1Pro, a wheeled humanoid that must find and pick up a radio from a table or a soda can from the floor. It may start with the object out of view. The robot adjusts its camera and its base, which makes the action space larger than a tabletop arm’s.
Here CaP-Agent0 matches or beats the human script on three of four numbers. Radio pickup: 56% against the human’s 36%. Soda can: 72% for both. Navigation: 80% against 88% for the radio, 84% against 80% for the can. The paper credits closed-loop behaviour. With the radio, the agent steps back to get a better view when the object is lost. With the soda can, it adapts its search when the camera misses. When the can is knocked over, it samples a new grasp.
The same loop runs on a Franka Panda and on an AgiBot G1, with no post-training, using Gemini-3-Pro and Claude Opus 4.5. These are qualitative demonstrations, not a table of success rates. One task finds a rare item (an auto-pencil refill holder) in a cluttered scene. Another finds a lime under one of three cups. A third solves 59 + 8 by choosing numbered blocks. A fourth stacks two cubes and a tennis ball in the only stable order. A person can also type feedback between turns, as in the apple example: after “grasped the apple too high,” the agent changes its code and succeeds on the second attempt.
Be careful with the word “beats.” The human script is a single static program iterated offline. CaP-Agent0 is an interactive agent that watches and repairs. The paper says plainly that this is the intended comparison. It is also not free: each CaP-Agent0 trial takes about two minutes, and a human needed up to three weeks for the hardest tasks. Chapter 10 returns to cost and to the three tasks where CaP-Agent0 still falls short.
Chapter 9
Use the robot's own success as the reward and watch a 7B model learn to grasp first.
A 7-billion-parameter coding model is asked to stack the red cube on the green cube. It writes a program that moves to a spot above the green cube and opens the gripper. It never picks up the red cube. In the simulator, nothing is stacked. The program ran without errors, so a code checker would be happy. The robot is not.
So far in this lesson, nobody has changed the model. The upgrades were all wrappers: loops, libraries and drafts. This chapter does something different. It trains the model, and the teacher is the robot’s own result. This is CaP-RL.
Reinforcement learning (RL) trains a model by trial and reward. The model tries something. A score comes back. The model changes itself to make high-scoring tries more likely. The key ingredient is the score. If a score can be checked by a program, with no human judge, it is a verifiable reward. The recipe is called RL with verifiable rewards (RLVR). A robot simulator gives the perfect verifiable reward: the cube is on the other cube, or it is not. (The CS336 alignment lesson covers RLVR in general.)
CaP-RL applies the algorithm GRPO (Group Relative Policy Optimization; Shao et al., 2024) to Qwen2.5-Coder-7B-Instruct. The paper gives few training details, so here is the standard idea. For each task prompt, the model writes a group of G programs. Each program runs in the simulator and gets a reward r. Then GRPO asks a simple question of every program: was it better or worse than its siblings?
Work an example. Say 3 of 8 programs succeed. The mean is μ = 3/8 = 0.375. The spread is σ = √(0.375 × 0.625) = 0.484. Each success gets A = (1 − 0.375)/0.484 = +1.29. Each failure gets A = (0 − 0.375)/0.484 = −0.77. Check the sum: 3 × 1.29 − 5 × 0.77 = 0. The advantages always sum to zero. The update then raises the probability of the tokens in the +1.29 programs and lowers it for the others.
Now see the catch. If all 8 programs fail, every reward equals the mean, and every advantage is 0. The model learns nothing from that group. The same holds if all 8 succeed. Learning needs a mix. Try it below.
Set how often the current model succeeds. Press Sample 8 programs. Green bars are successes, red bars are failures, and the bar height is the advantage that GRPO assigns.
Illustrative. The group size of 8 and the 0 or 1 reward are my choices for the toy; the paper does not state its group size here. The success rates 25%, 4% and 30% are the base model’s S2 results on Lift, Stack and Wipe (Table 4). The chance that a group carries a signal is 1 − p8 − (1 − p)8.
At the base model’s 4% success on Cube Stack, a group of 8 has a mixed result only about 28% of the time. That is why the paper begins with the easiest setting.
The paper trains on three tasks: Cube Lift, Cube Stack and Spill Wipe. It trains for 50 iterations per task. And it trains on the privileged tier S1, where the program gets exact object poses.
Why S1? At S2 the perception can be wrong. A perfectly good program would fail because the segmenter missed the cube, and the model would be punished for a bug that was not its own. The paper calls the confusion credit assignment ambiguity: you cannot tell which part of the pipeline deserves the blame. S1 removes the noise, so the reward measures program quality only.
It then tests on S2, with real perception, which the model never saw in training.
# CaP-RL, as a sketch (group size and optimizer details are not given in the paper) for it in range(50): # 50 iterations per task q = build_prompt(task, tier="S1") # privileged state APIs progs = [policy.sample(q) for _ in range(G)] r = np.array([env.run_and_check(p) for p in progs]) # verifiable: did it succeed? A = (r - r.mean()) / (r.std() + 1e-6) # group-relative advantage policy.grpo_update(q, progs, A) # raise the likelihood of better programs
| Task | Human | Qwen 7B | + CaP-RL |
|---|---|---|---|
| Sim, Cube Lift (100 trials) | 93 | 25 | 80 |
| Sim, Cube Stack | 73 | 4 | 44 |
| Sim, Spill Wipe | 100 | 30 | 93 |
| Real Franka, Cube Lift (25 trials) | 92 | 24 | 84 |
| Real Franka, Cube Stack | 84 | 12 | 76 |
All values are success percentages (Table 4). Lift rises from 25 to 80, Stack from 4 to 44 and Wipe from 30 to 93. The model gets close to the human script on two of three simulated tasks. On the real robot, with no real-world training, Lift reaches 84 and Stack 76, against 92 and 84 for the human.
The paper compares code before and after training for stacking the red cube on the green cube. Before, the program computed a target five centimetres above the green cube, moved there and opened the gripper. It skipped the grasp and acted as if it already held the cube. After training it writes the whole chain: identify, grasp, carry, release.
# before: a hard-coded offset, and no grasp at all placement_position = np.array(green_cube_position) + np.array([0, 0, 0.05]) goto_pose(placement_position, (0, 0, 1, 0), z_approach=0.1); open_gripper() # after: grasp first, and height from the two cubes' sizes placement_pos = green_cube_pos + np.array([0, 0, red_extent[2]/2 + green_extent[2]/2]) grasp_pos, grasp_quat = sample_grasp_pose("red cube"); goto_pose(grasp_pos, grasp_quat, z_approach=0.1) close_gripper(); goto_pose(placement_pos, (0, 0, 1, 0), z_approach=0.1); open_gripper()
The second change is subtler. The new program asks for the cubes’ bounding-box sizes and computes the placement height from them. A fixed 5 cm offset works for one cube size only. The size-based height works for any. The paper reads this as a move from memorizing to grounded geometric reasoning. It also reports that the trained model handled variants it never saw, such as “put the tennis ball on the green cube,” and randomized colours.
The paper’s explanation is neat. What crosses the gap from simulation to reality is the action space: programs that call shared perception and control tools. The model never learns to map pixels to motor torques. It learns which tools to call and in what order, and the tools are the same in simulation and on the Franka. So reality changes the pixels, but not the program’s shape.
Be careful about the scope. One base model, three tasks, and two real-world tasks with 25 trials each. The result is a strong sign, not a general law. For a related lesson on how RL changes coding agents, see Coding RL environments. For another paper that trains a small model to rewrite an agent’s code, see Harness Learning.
Chapter 10
Find the tasks stuck near zero, the price of each trial, and the questions the paper leaves open.
Read the report card for CaP-Agent0 again. Most subjects show high marks. One column shows a zero. Peg Insertion: 0%. A good student looks at that zero first. It marks the edge of what the method can do. This chapter looks at three edges: the tasks that still fail, the cost of each trial, and the questions the paper leaves open.
CaP-Agent0 scores 0% on Peg Insertion, 20% on Two-Arm Handover and 74% on Two-Arm Lift. The human scripts score 80%, 91% and 94%. Peg insertion needs a tight fit. Handover needs two arms to agree on a moment. The paper says the pattern is general. Programmatic control works well on long-horizon, reasoning-heavy tasks. It stays brittle on contact-rich behaviour, where the robot must feel and adjust all the time. The paper’s examples are insertion and pouring.
The paper names the cause as the need for tight visual servoing and continuous feedback. Here is my reading of why a CaP program struggles with that. It is a plan written in advance, and it runs to the end. Between turns, the agent sees what happened. Inside a turn, nothing watches. Contact-rich work needs a feedback loop that runs many times per second. A language model that writes one program every 7 to 24 seconds cannot close that loop.
A trained VLA works at the other end. The paper quotes about 73 ms per action chunk for π0 and about 167 ms per action for OpenVLA. A VLA answers far faster per output, since it emits motor commands directly. The paper warns that a direct comparison misleads, because one program is a whole manipulation sequence and one VLA output is a single action. The paper’s proposal for the future is a hybrid, CaP-VLA: the coding agent handles the task logic and recovery, and a VLA handles the fast low-level contact.
The paper times a Cube Stack trial for Gemini-3-Pro, averaged over 20 trials. The tiers form a ladder of cost: 12.9 s at S1, 20.0 s at S2, 28.4 s at S3, 60.8 s at M1 and 113.6 s at M3. The model’s own code-writing time is only part of it: 6.8, 9.6, 23.8, 20.1 and 15.8 s. The rest is running the program on the robot, the perception calls and, in M3, the vision module.
Put cost against success and you get a frontier. Drag the budget and see which setup you could afford.
Each point is one tier on Cube Stack with Gemini-3-Pro. Left to right is seconds per trial; up is success. Drag the budget line and read what you can afford.
Times: the paper’s Table 9 (Gemini-3-Pro, cube stack, N = 20, LLM plus execution). Success: the Cube Stack cells of Figure 17 for the same tiers. The hollow point (S1) uses exact simulator state, so it cannot run on a real camera. The table does not include CaP-Agent0’s nine-draft ensemble; the paper gives about 2 minutes per trial for CaP-Agent0 on a Robosuite task (Appendix K).
The numbers carry a plain lesson. Every rung of added help costs time. The step from S2 to M3 raises Cube Stack success from 37 to 87 and also multiplies the trial time by 5.7. For a task that takes a person minutes to set up, that is a good deal. For a factory line that needs one pick per second, it is not.
The paper itself flags several limits, and a few more follow from the setup.
The paper lists several directions. Embodiment-aware planning: an agent that knows its robot’s reach and limits. Better grounding of visual facts into code. Better search at test time. Automatic tuning of prompts and agents, with tools such as DSPy. Control primitives that take constraints and avoid collisions, rather than IK alone. More environments, including ones where the robot must look around to find out what is there.
You can also link it to other ideas on this site. A coding agent here is one instance of the idea in Code as agent harness. The loop of write, run and read mirrors harness engineering. The tiers are a task environment with controlled difficulty. And robot learning gives the trained-policy side of the comparison. An earlier language-model policy appears in GPT as a policy.
Chapter 11
Numbers, terms, the core loop in code, and where to go next.
CaP-X: A Framework for Benchmarking and Improving Coding Agents for Robot Manipulation was written by Letian Fu, Justin Yu, Karim El-Refai, Ethan Kou and Haoru Xue (equal contribution), with Huang Huang, Wenli Xiao, Guanzhi Wang, Dantong Niu, Fei-Fei Li, Guanya Shi, Jiajun Wu, Shankar Sastry, Yuke Zhu, Ken Goldberg and Linxi “Jim” Fan. The authors come from NVIDIA, UC Berkeley, Stanford and Carnegie Mellon. It appeared in the Proceedings of the 43rd International Conference on Machine Learning (Seoul, 2026) and is arXiv:2603.22435. The project page is capgym.github.io. This lesson is an independent teaching walk-through. All credit for the ideas and the measurements belongs to the authors, and every number below comes from their paper unless it is marked as my average.
The whole paper in one paragraph. Code-as-Policy lets a language model write the robot’s program. Earlier systems hid the hard parts inside human-made macros, so nobody knew how much the model contributed. CaP-Gym puts coding agents in a standard robot environment. CaP-Bench removes the macros one rung at a time and finds a large gap to expert humans. Multi-turn text feedback closes part of the gap, and a vision module that turns pictures into text closes more. CaP-Agent0 adds a mined skill library and nine merged drafts, with no training, and reaches the human level on four of seven tasks. CaP-RL then trains a 7B model with the robot’s own success as the reward, and the skill transfers to a real arm.
| Measurement | Value | Source |
|---|---|---|
| Tasks in CaP-Gym (Robosuite + LIBERO-PRO + BEHAVIOR) | 187 (7 + 130 + 50) | Section 1 |
| Human expert average, single-turn tiers (7 authors) | 88.5% | Fig. 1, App. K.1 |
| Human effort: simple tasks vs. peg insertion and handover | hours vs. 2 to 3 weeks | App. K.1 |
| Gemini-3-Pro, low-level one shot (S3) | 24% | Fig. 8 |
| + loop and VDM (M4) → + skill library → + 9 drafts, 1 model → + 3 models | 55 → 59 → 66 → 68.29% | Fig. 8, Table 5 |
| Closed-model average, S4 → S3 → S2 → S1 (my average) | 17.5 → 20.8 → 35.5 → 55.6% | Fig. 17 cells |
| Gemini-3-Pro, S2 / M1 / M2 / M3 (my average) | 39.1 / 46.9 / 43.1 / 60.3% | Fig. 17 cells |
| Library size | 9 functions | App. H.1 |
| CaP-Agent0 vs. human code, single-turn | at or above on 4 of 7 tasks | Fig. 8 |
| LIBERO-PRO instruction change, CaP-Agent0 vs. π0.5 | 0.18 / 0.17 / 0.14 vs. 0.01 / 0.00 / 0.01 | Table 2 |
| BEHAVIOR radio pickup, task success: CaP-Agent0 vs. human | 56% vs. 36% | Table 3 |
| CaP-RL on Qwen2.5-Coder-7B: Lift, Stack, Wipe (sim) | 25→80, 4→44, 30→93% | Table 4 |
| CaP-RL on a real Franka: Lift, Stack | 24→84, 12→76% | Table 4 |
| Cube Stack trial time, S1 → M3 (Gemini-3-Pro) | 12.9 s → 113.6 s | Table 9 |
| Term | Plain meaning |
|---|---|
| Code-as-Policy (CaP) | A model writes the robot’s control program as code. |
| Primitive, macro | A function the robot provides. A macro (high-level primitive) does a whole job in one call. |
| Scaffolding | The human-made help that sits between the model and the robot. |
| Tier (S1 to S4, M1 to M4) | One fixed mix of help: macros, examples, retries, picture handling. |
| Pass@1 | Only the first attempt counts. |
| Turn, trial | A turn is one program run. A trial is one or more turns on one task, with no reset. |
| REPL | Read, evaluate, print: run code and read what it prints. |
| Stateless service | A tool that keeps no memory between calls, so many trials can share it. |
| VDM | Visual Differencing Module: turns images into text about the scene and what changed. |
| Test-time compute | Extra work at answer time: retries, drafts, longer thinking. |
| Skill library | Helper functions mined from successful runs and given back to the agent. |
| RLVR, GRPO | RL with a checkable reward. GRPO scores each sample against its group. |
| Contact-rich | Tasks that need constant force and touch feedback, such as insertion. |
| Step skipping | Code that jumps to the goal and omits a needed step, such as the grasp. |
This is the loop every chapter built a piece of. It is my sketch of the paper’s description, not the released code.
def cap_agent0_trial(env, task, api_docs, skills, vdm, pool, synth, max_turns):
obs = env.reset() # once per trial, never again (Ch 2)
context = [task, api_docs, skills] # 9 mined helpers ride along (Ch 6)
last_rgb = obs.rgb # (H, W, 3) uint8
context.append(vdm(task, last_rgb)) # turn-1 scene description (Ch 5)
for turn in range(max_turns):
drafts = parallel([call(m, context, T) for m, T in pool]) # 9 drafts, 3 models (Ch 7)
reply = synth(context, drafts) # one program, or the word FINISH
if reply.startswith("FINISH"): break
stdout, stderr = env.executor.run(extract_code(reply)) # stateful sandbox (Ch 2)
rgb = env.observe().rgb
context += [reply, stdout, stderr, vdm(task, rgb, last_rgb)] # what changed (Ch 5)
last_rgb = rgb
return env.success() # the verifiable score (Ch 3, Ch 9)
The paper stands on the first Code-as-Policy work (Liang et al., 2023; Singh et al., 2023), on classical task-and-motion planning, and on the VLA line (RT-2, OpenVLA, π0, π0.5). Its loop of write, run and read also matches the agent harnesses of software engineering. Its skill library follows agents that collect reusable tools over time. Its RL step uses GRPO. This site already covers several neighbours. Read Code as agent harness for the general case, GPT as a policy for language models that act, and π0 for the trained-policy side. VLA and robot learning give the background. Harness engineering and Harness Learning cover the wrapper side. Task environments, coding RL environments and alignment and RLVR cover the benchmark and training sides.